commit a0b6c0db4758beabcf1ae16bf395a2948b65c750 Author: ChronosX88 Date: Wed Mar 24 00:16:10 2021 +0300 Initialize project diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aa724b7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..61a9130 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..23a89bb --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,22 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..a5f05cd --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..d5d35ec --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/render.experimental.xml b/.idea/render.experimental.xml new file mode 100644 index 0000000..8ec256a --- /dev/null +++ b/.idea/render.experimental.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..eb8e289 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,57 @@ +plugins { + id 'com.android.application' + id 'kotlin-android' +} + +android { + compileSdkVersion 30 + buildToolsVersion "30.0.3" + + defaultConfig { + applicationId "io.github.chronosx88.radium" + minSdkVersion 19 + targetSdkVersion 30 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = '1.8' + } +} + +dependencies { + + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + implementation 'androidx.core:core-ktx:1.2.0' + implementation 'androidx.appcompat:appcompat:1.2.0' + implementation 'com.google.android.material:material:1.2.1' + implementation 'androidx.constraintlayout:constraintlayout:2.0.4' + implementation 'androidx.navigation:navigation-fragment:2.2.2' + implementation 'androidx.navigation:navigation-ui:2.2.2' + implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0' + implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0' + implementation 'androidx.navigation:navigation-fragment-ktx:2.2.2' + implementation 'androidx.navigation:navigation-ui-ktx:2.2.2' + implementation 'de.hdodenhof:circleimageview:3.1.0' + + implementation 'com.github.bumptech.glide:glide:4.12.0' + implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' + annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0' + + testImplementation 'junit:junit:4.+' + androidTestImplementation 'androidx.test.ext:junit:1.1.1' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' +} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/app/src/androidTest/java/io/github/chronosx88/radium/ExampleInstrumentedTest.kt b/app/src/androidTest/java/io/github/chronosx88/radium/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..5f78765 --- /dev/null +++ b/app/src/androidTest/java/io/github/chronosx88/radium/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package io.github.chronosx88.radium + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("io.github.chronosx88.radium", appContext.packageName) + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..f263bc7 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/radium/ChatListActivity.kt b/app/src/main/java/io/github/chronosx88/radium/ChatListActivity.kt new file mode 100644 index 0000000..ffa1d7f --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/radium/ChatListActivity.kt @@ -0,0 +1,79 @@ +package io.github.chronosx88.radium + +import android.os.Bundle +import android.view.MenuItem +import androidx.activity.viewModels +import androidx.appcompat.app.ActionBarDrawerToggle +import androidx.appcompat.app.AppCompatActivity +import androidx.appcompat.widget.Toolbar +import androidx.core.view.GravityCompat +import androidx.drawerlayout.widget.DrawerLayout +import androidx.lifecycle.Observer +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import com.google.android.material.floatingactionbutton.FloatingActionButton +import com.google.android.material.snackbar.Snackbar + +class ChatListActivity : AppCompatActivity() { + private lateinit var drawer: DrawerLayout + private val viewModel: ChatListViewModel by viewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + initActivity() + initRecyclerView() + } + + fun initActivity() { + val toolbar: Toolbar = findViewById(R.id.toolbar) + setSupportActionBar(toolbar) + + val fab: FloatingActionButton = findViewById(R.id.fab) + fab.setOnClickListener { view -> + Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) + .setAction("Action", null).show() + } + + drawer = findViewById(R.id.drawer_layout) + + val drawerToggle = ActionBarDrawerToggle(this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close) + drawer.addDrawerListener(drawerToggle) + drawerToggle.syncState() + + supportActionBar?.setDisplayHomeAsUpEnabled(true) + } + + fun initRecyclerView() { + val chatList: RecyclerView = findViewById(R.id.chat_list_rv) + + val adapter = ChatListAdapter(this) + chatList.adapter = adapter + chatList.layoutManager = LinearLayoutManager(this) + + viewModel.chats.observe(this, Observer { chats -> + adapter.data.addAll(chats) + adapter.notifyDataSetChanged() + }) + } + + override fun onBackPressed() { + if (drawer.isDrawerOpen(GravityCompat.START)) { + drawer.closeDrawer(GravityCompat.START) + } else { + super.onBackPressed() + } + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + super.onOptionsItemSelected(item) + return when (item.itemId) { + android.R.id.home -> { + drawer.openDrawer(GravityCompat.START) + true + } + else -> super.onOptionsItemSelected(item) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/radium/ChatListAdapter.kt b/app/src/main/java/io/github/chronosx88/radium/ChatListAdapter.kt new file mode 100644 index 0000000..c179e81 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/radium/ChatListAdapter.kt @@ -0,0 +1,58 @@ +package io.github.chronosx88.radium + +import android.content.Context +import android.graphics.drawable.Drawable +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.TextView +import androidx.appcompat.content.res.AppCompatResources +import androidx.recyclerview.widget.RecyclerView +import com.bumptech.glide.Glide +import de.hdodenhof.circleimageview.CircleImageView +import io.github.chronosx88.radium.models.Chat +import io.github.chronosx88.radium.utils.time.LocaleUtils +import java.util.ArrayList + +class ChatListAdapter(val context: Context) : RecyclerView.Adapter() { + val data = ArrayList() + + class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { + val chatName: TextView = view.findViewById(R.id.chat_list_item_name) + val avatar: CircleImageView = view.findViewById(R.id.chat_list_item_avatar) + val lastMsg: TextView = view.findViewById(R.id.chat_list_item_last_msg) + val lastMessageReadState: ImageView = view.findViewById(R.id.chat_list_read_icon) + val lastMessageTime: TextView = view.findViewById(R.id.chat_list_last_msg_timestamp) + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + val view = LayoutInflater.from(parent.context) + .inflate(R.layout.chat_list_item, parent, false) + return ViewHolder(view) + + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + holder.chatName.text = data[position].name + holder.lastMsg.text = data[position].lastMsg.text + + if (data[position].lastMsg.author) { + val doneIcon: Drawable? = AppCompatResources.getDrawable(context, R.drawable.ic_done_purple_24) + val doneAllIcon: Drawable? = AppCompatResources.getDrawable(context, R.drawable.ic_done_all_purple_24) + holder.lastMessageReadState.setImageDrawable(if (data[position].lastMsg.read) doneAllIcon!! else doneIcon!!) + } else { + holder.lastMessageReadState.visibility = View.INVISIBLE + } + + + Glide.with(holder.itemView) + .load(data[position].photoURL) + .into(holder.avatar) + + val lastMessageDateText = LocaleUtils.stringForMessageListDate(data[position].lastMsg.timestamp) + holder.lastMessageTime.text = lastMessageDateText + } + + override fun getItemCount(): Int = data.size +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/radium/ChatListViewModel.kt b/app/src/main/java/io/github/chronosx88/radium/ChatListViewModel.kt new file mode 100644 index 0000000..7f75c4e --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/radium/ChatListViewModel.kt @@ -0,0 +1,41 @@ +package io.github.chronosx88.radium + +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import io.github.chronosx88.radium.models.Chat +import io.github.chronosx88.radium.models.Message +import kotlinx.coroutines.launch + +class ChatListViewModel : ViewModel() { + private val _chats = MutableLiveData>() + val chats : LiveData> = _chats + + init { + viewModelScope.launch { + _chats.value = arrayOf( + Chat( + "Michael Jordan", + Message( + "That's great!", + true, + 1616522699913, + true + ), + "https://upload.wikimedia.org/wikipedia/commons/a/ae/Michael_Jordan_in_2014.jpg" + ), + Chat( + "Linus Torvalds", + Message( + "software is like sex : it's better when it's free", + false, + 823522140000, + true + ), + "https://upload.wikimedia.org/wikipedia/commons/0/01/LinuxCon_Europe_Linus_Torvalds_03_%28cropped%29.jpg" + ) + ) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/radium/RadiumApplication.kt b/app/src/main/java/io/github/chronosx88/radium/RadiumApplication.kt new file mode 100644 index 0000000..be615e5 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/radium/RadiumApplication.kt @@ -0,0 +1,12 @@ +package io.github.chronosx88.radium + +import android.app.Application +import io.github.chronosx88.radium.utils.time.LocaleUtils + +class RadiumApplication : Application() { + override fun onCreate() { + super.onCreate() + + LocaleUtils.initFormatters(this.applicationContext) // FIXME this is bullshit, need to think about better solution + } +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/radium/models/Chat.kt b/app/src/main/java/io/github/chronosx88/radium/models/Chat.kt new file mode 100644 index 0000000..6df5803 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/radium/models/Chat.kt @@ -0,0 +1,7 @@ +package io.github.chronosx88.radium.models + +data class Chat( + val name: String, + val lastMsg: Message, + val photoURL: String +) diff --git a/app/src/main/java/io/github/chronosx88/radium/models/Message.kt b/app/src/main/java/io/github/chronosx88/radium/models/Message.kt new file mode 100644 index 0000000..5cae97c --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/radium/models/Message.kt @@ -0,0 +1,8 @@ +package io.github.chronosx88.radium.models + +data class Message( + val text: String, + val author: Boolean, + val timestamp: Long, + val read: Boolean +) \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/radium/utils/time/DateParser.java b/app/src/main/java/io/github/chronosx88/radium/utils/time/DateParser.java new file mode 100644 index 0000000..ab98deb --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/radium/utils/time/DateParser.java @@ -0,0 +1,92 @@ +package io.github.chronosx88.radium.utils.time; + + +import java.text.ParseException; +import java.text.ParsePosition; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +/** + *

DateParser is the "missing" interface for the parsing methods of + * {@link java.text.DateFormat}.

+ * + * @since 3.2 + */ +public interface DateParser { + + /** + * Equivalent to DateFormat.parse(String). + *

+ * See {@link java.text.DateFormat#parse(String)} for more information. + * + * @param source A String whose beginning should be parsed. + * @return A Date parsed from the string + * @throws ParseException if the beginning of the specified string cannot be parsed. + */ + Date parse(String source) throws ParseException; + + /** + * Equivalent to DateFormat.parse(String, ParsePosition). + *

+ * See {@link java.text.DateFormat#parse(String, ParsePosition)} for more information. + * + * @param source A String, part of which should be parsed. + * @param pos A ParsePosition object with index and error index information + * as described above. + * @return A Date parsed from the string. In case of error, returns null. + * @throws NullPointerException if text or pos is null. + */ + Date parse(String source, ParsePosition pos); + + // Accessors + //----------------------------------------------------------------------- + + /** + *

Get the pattern used by this parser.

+ * + * @return the pattern, {@link java.text.SimpleDateFormat} compatible + */ + String getPattern(); + + /** + *

+ * Get the time zone used by this parser. + *

+ *

+ *

+ * The default {@link TimeZone} used to create a {@link Date} when the {@link TimeZone} is not specified by + * the format pattern. + *

+ * + * @return the time zone + */ + TimeZone getTimeZone(); + + /** + *

Get the locale used by this parser.

+ * + * @return the locale + */ + Locale getLocale(); + + /** + * Parses text from a string to produce a Date. + * + * @param source A String whose beginning should be parsed. + * @return a java.util.Date object + * @throws ParseException if the beginning of the specified string cannot be parsed. + * @see java.text.DateFormat#parseObject(String) + */ + Object parseObject(String source) throws ParseException; + + /** + * Parse a date/time string according to the given parse position. + * + * @param source A String whose beginning should be parsed. + * @param pos the parse position + * @return a java.util.Date object + * @see java.text.DateFormat#parseObject(String, ParsePosition) + */ + Object parseObject(String source, ParsePosition pos); +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/radium/utils/time/DatePrinter.java b/app/src/main/java/io/github/chronosx88/radium/utils/time/DatePrinter.java new file mode 100644 index 0000000..b825035 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/radium/utils/time/DatePrinter.java @@ -0,0 +1,126 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.chronosx88.radium.utils.time; + +import java.text.FieldPosition; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +/** + *

DatePrinter is the "missing" interface for the format methods of + * {@link java.text.DateFormat}.

+ * + * @since 3.2 + */ +public interface DatePrinter { + + /** + *

Formats a millisecond {@code long} value.

+ * + * @param millis the millisecond value to format + * @return the formatted string + * @since 2.1 + */ + String format(long millis); + + /** + *

Formats a {@code Date} object using a {@code GregorianCalendar}.

+ * + * @param date the date to format + * @return the formatted string + */ + String format(Date date); + + /** + *

Formats a {@code Calendar} object.

+ * + * @param calendar the calendar to format + * @return the formatted string + */ + String format(Calendar calendar); + + /** + *

Formats a milliseond {@code long} value into the + * supplied {@code StringBuffer}.

+ * + * @param millis the millisecond value to format + * @param buf the buffer to format into + * @return the specified string buffer + */ + StringBuffer format(long millis, StringBuffer buf); + + /** + *

Formats a {@code Date} object into the + * supplied {@code StringBuffer} using a {@code GregorianCalendar}.

+ * + * @param date the date to format + * @param buf the buffer to format into + * @return the specified string buffer + */ + StringBuffer format(Date date, StringBuffer buf); + + /** + *

Formats a {@code Calendar} object into the + * supplied {@code StringBuffer}.

+ * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + */ + StringBuffer format(Calendar calendar, StringBuffer buf); + + // Accessors + //----------------------------------------------------------------------- + + /** + *

Gets the pattern used by this printer.

+ * + * @return the pattern, {@link java.text.SimpleDateFormat} compatible + */ + String getPattern(); + + /** + *

Gets the time zone used by this printer.

+ *

+ *

This zone is always used for {@code Date} printing.

+ * + * @return the time zone + */ + TimeZone getTimeZone(); + + /** + *

Gets the locale used by this printer.

+ * + * @return the locale + */ + Locale getLocale(); + + /** + *

Formats a {@code Date}, {@code Calendar} or + * {@code Long} (milliseconds) object.

+ *

+ * See {@link java.text.DateFormat#format(Object, StringBuffer, FieldPosition)} + * + * @param obj the object to format + * @param toAppendTo the buffer to append to + * @param pos the position - ignored + * @return the buffer passed in + */ + StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos); +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/radium/utils/time/FastDateFormat.java b/app/src/main/java/io/github/chronosx88/radium/utils/time/FastDateFormat.java new file mode 100644 index 0000000..688022a --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/radium/utils/time/FastDateFormat.java @@ -0,0 +1,597 @@ +package io.github.chronosx88.radium.utils.time; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.Format; +import java.text.ParseException; +import java.text.ParsePosition; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +/** + *

FastDateFormat is a fast and thread-safe version of + * {@link java.text.SimpleDateFormat}.

+ * + *

This class can be used as a direct replacement to + * {@code SimpleDateFormat} in most formatting and parsing situations. + * This class is especially useful in multi-threaded server environments. + * {@code SimpleDateFormat} is not thread-safe in any JDK version, + * nor will it be as Sun have closed the bug/RFE. + *

+ * + *

All patterns are compatible with + * SimpleDateFormat (except time zones and some year patterns - see below).

+ * + *

Since 3.2, FastDateFormat supports parsing as well as printing.

+ * + *

Java 1.4 introduced a new pattern letter, {@code 'Z'}, to represent + * time zones in RFC822 format (eg. {@code +0800} or {@code -1100}). + * This pattern letter can be used here (on all JDK versions).

+ * + *

In addition, the pattern {@code 'ZZ'} has been made to represent + * ISO8601 full format time zones (eg. {@code +08:00} or {@code -11:00}). + * This introduces a minor incompatibility with Java 1.4, but at a gain of + * useful functionality.

+ * + *

Javadoc cites for the year pattern: For formatting, if the number of + * pattern letters is 2, the year is truncated to 2 digits; otherwise it is + * interpreted as a number. Starting with Java 1.7 a pattern of 'Y' or + * 'YYY' will be formatted as '2003', while it was '03' in former Java + * versions. FastDateFormat implements the behavior of Java 7.

+ * + * @since 2.0 + * @version $Id: FastDateFormat.java 1572877 2014-02-28 08:42:25Z britter $ + */ +public class FastDateFormat extends Format implements DateParser, DatePrinter { + /** + * Required for serialization support. + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 2L; + + /** + * FULL locale dependent date or time style. + */ + public static final int FULL = DateFormat.FULL; + /** + * LONG locale dependent date or time style. + */ + public static final int LONG = DateFormat.LONG; + /** + * MEDIUM locale dependent date or time style. + */ + public static final int MEDIUM = DateFormat.MEDIUM; + /** + * SHORT locale dependent date or time style. + */ + public static final int SHORT = DateFormat.SHORT; + + private static final FormatCache cache = new FormatCache() { + @Override + protected FastDateFormat createInstance(final String pattern, final TimeZone timeZone, final Locale locale) { + return new FastDateFormat(pattern, timeZone, locale); + } + }; + + private final FastDatePrinter printer; + private final FastDateParser parser; + + //----------------------------------------------------------------------- + + /** + *

Gets a formatter instance using the default pattern in the + * default locale.

+ * + * @return a date/time formatter + */ + public static FastDateFormat getInstance() { + return cache.getInstance(); + } + + /** + *

Gets a formatter instance using the specified pattern in the + * default locale.

+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible + * pattern + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + */ + public static FastDateFormat getInstance(final String pattern) { + return cache.getInstance(pattern, null, null); + } + + /** + *

Gets a formatter instance using the specified pattern and + * time zone.

+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible + * pattern + * @param timeZone optional time zone, overrides time zone of + * formatted date + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + */ + public static FastDateFormat getInstance(final String pattern, final TimeZone timeZone) { + return cache.getInstance(pattern, timeZone, null); + } + + /** + *

Gets a formatter instance using the specified pattern and + * locale.

+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible + * pattern + * @param locale optional locale, overrides system locale + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + */ + public static FastDateFormat getInstance(final String pattern, final Locale locale) { + return cache.getInstance(pattern, null, locale); + } + + /** + *

Gets a formatter instance using the specified pattern, time zone + * and locale.

+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible + * pattern + * @param timeZone optional time zone, overrides time zone of + * formatted date + * @param locale optional locale, overrides system locale + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + * or {@code null} + */ + public static FastDateFormat getInstance(final String pattern, final TimeZone timeZone, final Locale locale) { + return cache.getInstance(pattern, timeZone, locale); + } + + //----------------------------------------------------------------------- + + /** + *

Gets a date formatter instance using the specified style in the + * default time zone and locale.

+ * + * @param style date style: FULL, LONG, MEDIUM, or SHORT + * @return a localized standard date formatter + * @throws IllegalArgumentException if the Locale has no date + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getDateInstance(final int style) { + return cache.getDateInstance(style, null, null); + } + + /** + *

Gets a date formatter instance using the specified style and + * locale in the default time zone.

+ * + * @param style date style: FULL, LONG, MEDIUM, or SHORT + * @param locale optional locale, overrides system locale + * @return a localized standard date formatter + * @throws IllegalArgumentException if the Locale has no date + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getDateInstance(final int style, final Locale locale) { + return cache.getDateInstance(style, null, locale); + } + + /** + *

Gets a date formatter instance using the specified style and + * time zone in the default locale.

+ * + * @param style date style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted date + * @return a localized standard date formatter + * @throws IllegalArgumentException if the Locale has no date + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getDateInstance(final int style, final TimeZone timeZone) { + return cache.getDateInstance(style, timeZone, null); + } + + /** + *

Gets a date formatter instance using the specified style, time + * zone and locale.

+ * + * @param style date style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted date + * @param locale optional locale, overrides system locale + * @return a localized standard date formatter + * @throws IllegalArgumentException if the Locale has no date + * pattern defined + */ + public static FastDateFormat getDateInstance(final int style, final TimeZone timeZone, final Locale locale) { + return cache.getDateInstance(style, timeZone, locale); + } + + //----------------------------------------------------------------------- + + /** + *

Gets a time formatter instance using the specified style in the + * default time zone and locale.

+ * + * @param style time style: FULL, LONG, MEDIUM, or SHORT + * @return a localized standard time formatter + * @throws IllegalArgumentException if the Locale has no time + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getTimeInstance(final int style) { + return cache.getTimeInstance(style, null, null); + } + + /** + *

Gets a time formatter instance using the specified style and + * locale in the default time zone.

+ * + * @param style time style: FULL, LONG, MEDIUM, or SHORT + * @param locale optional locale, overrides system locale + * @return a localized standard time formatter + * @throws IllegalArgumentException if the Locale has no time + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getTimeInstance(final int style, final Locale locale) { + return cache.getTimeInstance(style, null, locale); + } + + /** + *

Gets a time formatter instance using the specified style and + * time zone in the default locale.

+ * + * @param style time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted time + * @return a localized standard time formatter + * @throws IllegalArgumentException if the Locale has no time + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getTimeInstance(final int style, final TimeZone timeZone) { + return cache.getTimeInstance(style, timeZone, null); + } + + /** + *

Gets a time formatter instance using the specified style, time + * zone and locale.

+ * + * @param style time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted time + * @param locale optional locale, overrides system locale + * @return a localized standard time formatter + * @throws IllegalArgumentException if the Locale has no time + * pattern defined + */ + public static FastDateFormat getTimeInstance(final int style, final TimeZone timeZone, final Locale locale) { + return cache.getTimeInstance(style, timeZone, locale); + } + + //----------------------------------------------------------------------- + + /** + *

Gets a date/time formatter instance using the specified style + * in the default time zone and locale.

+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getDateTimeInstance(final int dateStyle, final int timeStyle) { + return cache.getDateTimeInstance(dateStyle, timeStyle, null, null); + } + + /** + *

Gets a date/time formatter instance using the specified style and + * locale in the default time zone.

+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getDateTimeInstance(final int dateStyle, final int timeStyle, final Locale locale) { + return cache.getDateTimeInstance(dateStyle, timeStyle, null, locale); + } + + /** + *

Gets a date/time formatter instance using the specified style and + * time zone in the default locale.

+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted date + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + * @since 2.1 + */ + public static FastDateFormat getDateTimeInstance(final int dateStyle, final int timeStyle, final TimeZone timeZone) { + return getDateTimeInstance(dateStyle, timeStyle, timeZone, null); + } + + /** + *

Gets a date/time formatter instance using the specified style, + * time zone and locale.

+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted date + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + */ + public static FastDateFormat getDateTimeInstance( + final int dateStyle, final int timeStyle, final TimeZone timeZone, final Locale locale) { + return cache.getDateTimeInstance(dateStyle, timeStyle, timeZone, locale); + } + + // Constructor + //----------------------------------------------------------------------- + + /** + *

Constructs a new FastDateFormat.

+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale to use + * @throws NullPointerException if pattern, timeZone, or locale is null. + */ + protected FastDateFormat(final String pattern, final TimeZone timeZone, final Locale locale) { + this(pattern, timeZone, locale, null); + } + + // Constructor + //----------------------------------------------------------------------- + + /** + *

Constructs a new FastDateFormat.

+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale to use + * @param centuryStart The start of the 100 year period to use as the "default century" for 2 digit year parsing. If centuryStart is null, defaults to now - 80 years + * @throws NullPointerException if pattern, timeZone, or locale is null. + */ + protected FastDateFormat(final String pattern, final TimeZone timeZone, final Locale locale, final Date centuryStart) { + printer = new FastDatePrinter(pattern, timeZone, locale); + parser = new FastDateParser(pattern, timeZone, locale, centuryStart); + } + + // Format methods + //----------------------------------------------------------------------- + + /** + *

Formats a {@code Date}, {@code Calendar} or + * {@code Long} (milliseconds) object.

+ * + * @param obj the object to format + * @param toAppendTo the buffer to append to + * @param pos the position - ignored + * @return the buffer passed in + */ + @Override + public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { + return printer.format(obj, toAppendTo, pos); + } + + /** + *

Formats a millisecond {@code long} value.

+ * + * @param millis the millisecond value to format + * @return the formatted string + * @since 2.1 + */ + @Override + public String format(final long millis) { + return printer.format(millis); + } + + /** + *

Formats a {@code Date} object using a {@code GregorianCalendar}.

+ * + * @param date the date to format + * @return the formatted string + */ + @Override + public String format(final Date date) { + return printer.format(date); + } + + /** + *

Formats a {@code Calendar} object.

+ * + * @param calendar the calendar to format + * @return the formatted string + */ + @Override + public String format(final Calendar calendar) { + return printer.format(calendar); + } + + /** + *

Formats a millisecond {@code long} value into the + * supplied {@code StringBuffer}.

+ * + * @param millis the millisecond value to format + * @param buf the buffer to format into + * @return the specified string buffer + * @since 2.1 + */ + @Override + public StringBuffer format(final long millis, final StringBuffer buf) { + return printer.format(millis, buf); + } + + /** + *

Formats a {@code Date} object into the + * supplied {@code StringBuffer} using a {@code GregorianCalendar}.

+ * + * @param date the date to format + * @param buf the buffer to format into + * @return the specified string buffer + */ + @Override + public StringBuffer format(final Date date, final StringBuffer buf) { + return printer.format(date, buf); + } + + /** + *

Formats a {@code Calendar} object into the + * supplied {@code StringBuffer}.

+ * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + */ + @Override + public StringBuffer format(final Calendar calendar, final StringBuffer buf) { + return printer.format(calendar, buf); + } + + // Parsing + //----------------------------------------------------------------------- + + + /* (non-Javadoc) + * @see DateParser#parse(java.lang.String) + */ + @Override + public Date parse(final String source) throws ParseException { + return parser.parse(source); + } + + /* (non-Javadoc) + * @see DateParser#parse(java.lang.String, java.text.ParsePosition) + */ + @Override + public Date parse(final String source, final ParsePosition pos) { + return parser.parse(source, pos); + } + + /* (non-Javadoc) + * @see java.text.Format#parseObject(java.lang.String, java.text.ParsePosition) + */ + @Override + public Object parseObject(final String source, final ParsePosition pos) { + return parser.parseObject(source, pos); + } + + // Accessors + //----------------------------------------------------------------------- + + /** + *

Gets the pattern used by this formatter.

+ * + * @return the pattern, {@link java.text.SimpleDateFormat} compatible + */ + @Override + public String getPattern() { + return printer.getPattern(); + } + + /** + *

Gets the time zone used by this formatter.

+ *

+ *

This zone is always used for {@code Date} formatting.

+ * + * @return the time zone + */ + @Override + public TimeZone getTimeZone() { + return printer.getTimeZone(); + } + + /** + *

Gets the locale used by this formatter.

+ * + * @return the locale + */ + @Override + public Locale getLocale() { + return printer.getLocale(); + } + + /** + *

Gets an estimate for the maximum string length that the + * formatter will produce.

+ *

+ *

The actual formatted length will almost always be less than or + * equal to this amount.

+ * + * @return the maximum formatted length + */ + public int getMaxLengthEstimate() { + return printer.getMaxLengthEstimate(); + } + + // Basics + //----------------------------------------------------------------------- + + /** + *

Compares two objects for equality.

+ * + * @param obj the object to compare to + * @return {@code true} if equal + */ + @Override + public boolean equals(final Object obj) { + if (!(obj instanceof FastDateFormat)) { + return false; + } + final FastDateFormat other = (FastDateFormat) obj; + // no need to check parser, as it has same invariants as printer + return printer.equals(other.printer); + } + + /** + *

Returns a hashcode compatible with equals.

+ * + * @return a hashcode compatible with equals + */ + @Override + public int hashCode() { + return printer.hashCode(); + } + + /** + *

Gets a debugging string version of this formatter.

+ * + * @return a debugging string + */ + @Override + public String toString() { + return "FastDateFormat[" + printer.getPattern() + "," + printer.getLocale() + "," + printer.getTimeZone().getID() + "]"; + } + + + /** + *

Performs the formatting by applying the rules to the + * specified calendar.

+ * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + */ + protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) { + return printer.applyRules(calendar, buf); + } +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/radium/utils/time/FastDateParser.java b/app/src/main/java/io/github/chronosx88/radium/utils/time/FastDateParser.java new file mode 100644 index 0000000..dfa6b63 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/radium/utils/time/FastDateParser.java @@ -0,0 +1,874 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.chronosx88.radium.utils.time; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serializable; +import java.text.DateFormatSymbols; +import java.text.ParseException; +import java.text.ParsePosition; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.SortedMap; +import java.util.TimeZone; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + *

FastDateParser is a fast and thread-safe version of + * {@link java.text.SimpleDateFormat}.

+ * + *

This class can be used as a direct replacement for + * SimpleDateFormat in most parsing situations. + * This class is especially useful in multi-threaded server environments. + * SimpleDateFormat is not thread-safe in any JDK version, + * nor will it be as Sun has closed the + * bug/RFE. + *

+ * + *

Only parsing is supported, but all patterns are compatible with + * SimpleDateFormat.

+ * + *

Timing tests indicate this class is as about as fast as SimpleDateFormat + * in single thread applications and about 25% faster in multi-thread applications.

+ * + * @version $Id: FastDateParser.java 1572877 2014-02-28 08:42:25Z britter $ + * @since 3.2 + */ +public class FastDateParser implements DateParser, Serializable { + /** + * Required for serialization support. + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 2L; + + static final Locale JAPANESE_IMPERIAL = new Locale("ja", "JP", "JP"); + + // defining fields + private final String pattern; + private final TimeZone timeZone; + private final Locale locale; + private final int century; + private final int startYear; + + // derived fields + private transient Pattern parsePattern; + private transient Strategy[] strategies; + + // dynamic fields to communicate with Strategy + private transient String currentFormatField; + private transient Strategy nextStrategy; + + /** + *

Constructs a new FastDateParser.

+ * + * @param pattern non-null {@link java.text.SimpleDateFormat} compatible + * pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale + */ + protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale) { + this(pattern, timeZone, locale, null); + } + + /** + *

Constructs a new FastDateParser.

+ * + * @param pattern non-null {@link java.text.SimpleDateFormat} compatible + * pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale + * @param centuryStart The start of the century for 2 digit year parsing + * @since 3.3 + */ + protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale, final Date centuryStart) { + this.pattern = pattern; + this.timeZone = timeZone; + this.locale = locale; + + final Calendar definingCalendar = Calendar.getInstance(timeZone, locale); + int centuryStartYear; + if (centuryStart != null) { + definingCalendar.setTime(centuryStart); + centuryStartYear = definingCalendar.get(Calendar.YEAR); + } else if (locale.equals(JAPANESE_IMPERIAL)) { + centuryStartYear = 0; + } else { + // from 80 years ago to 20 years from now + definingCalendar.setTime(new Date()); + centuryStartYear = definingCalendar.get(Calendar.YEAR) - 80; + } + century = centuryStartYear / 100 * 100; + startYear = centuryStartYear - century; + + init(definingCalendar); + } + + /** + * Initialize derived fields from defining fields. + * This is called from constructor and from readObject (de-serialization) + * + * @param definingCalendar the {@link java.util.Calendar} instance used to initialize this FastDateParser + */ + private void init(Calendar definingCalendar) { + + final StringBuilder regex = new StringBuilder(); + final List collector = new ArrayList(); + + final Matcher patternMatcher = formatPattern.matcher(pattern); + if (!patternMatcher.lookingAt()) { + throw new IllegalArgumentException( + "Illegal pattern character '" + pattern.charAt(patternMatcher.regionStart()) + "'"); + } + + currentFormatField = patternMatcher.group(); + Strategy currentStrategy = getStrategy(currentFormatField, definingCalendar); + for (; ; ) { + patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd()); + if (!patternMatcher.lookingAt()) { + nextStrategy = null; + break; + } + final String nextFormatField = patternMatcher.group(); + nextStrategy = getStrategy(nextFormatField, definingCalendar); + if (currentStrategy.addRegex(this, regex)) { + collector.add(currentStrategy); + } + currentFormatField = nextFormatField; + currentStrategy = nextStrategy; + } + if (patternMatcher.regionStart() != patternMatcher.regionEnd()) { + throw new IllegalArgumentException("Failed to parse \"" + pattern + "\" ; gave up at index " + patternMatcher.regionStart()); + } + if (currentStrategy.addRegex(this, regex)) { + collector.add(currentStrategy); + } + currentFormatField = null; + strategies = collector.toArray(new Strategy[collector.size()]); + parsePattern = Pattern.compile(regex.toString()); + } + + // Accessors + //----------------------------------------------------------------------- + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#getPattern() + */ + @Override + public String getPattern() { + return pattern; + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#getTimeZone() + */ + @Override + public TimeZone getTimeZone() { + return timeZone; + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#getLocale() + */ + @Override + public Locale getLocale() { + return locale; + } + + /** + * Returns the generated pattern (for testing purposes). + * + * @return the generated pattern + */ + Pattern getParsePattern() { + return parsePattern; + } + + // Basics + //----------------------------------------------------------------------- + + /** + *

Compare another object for equality with this object.

+ * + * @param obj the object to compare to + * @return trueif equal to this instance + */ + @Override + public boolean equals(final Object obj) { + if (!(obj instanceof FastDateParser)) { + return false; + } + final FastDateParser other = (FastDateParser) obj; + return pattern.equals(other.pattern) + && timeZone.equals(other.timeZone) + && locale.equals(other.locale); + } + + /** + *

Return a hashcode compatible with equals.

+ * + * @return a hashcode compatible with equals + */ + @Override + public int hashCode() { + return pattern.hashCode() + 13 * (timeZone.hashCode() + 13 * locale.hashCode()); + } + + /** + *

Get a string version of this formatter.

+ * + * @return a debugging string + */ + @Override + public String toString() { + return "FastDateParser[" + pattern + "," + locale + "," + timeZone.getID() + "]"; + } + + // Serializing + //----------------------------------------------------------------------- + + /** + * Create the object after serialization. This implementation reinitializes the + * transient properties. + * + * @param in ObjectInputStream from which the object is being deserialized. + * @throws IOException if there is an IO issue. + * @throws ClassNotFoundException if a class cannot be found. + */ + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + + final Calendar definingCalendar = Calendar.getInstance(timeZone, locale); + init(definingCalendar); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String) + */ + @Override + public Object parseObject(final String source) throws ParseException { + return parse(source); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String) + */ + @Override + public Date parse(final String source) throws ParseException { + final Date date = parse(source, new ParsePosition(0)); + if (date == null) { + // Add a note re supported date range + if (locale.equals(JAPANESE_IMPERIAL)) { + throw new ParseException( + "(The " + locale + " locale does not support dates before 1868 AD)\n" + + "Unparseable date: \"" + source + "\" does not match " + parsePattern.pattern(), 0); + } + throw new ParseException("Unparseable date: \"" + source + "\" does not match " + parsePattern.pattern(), 0); + } + return date; + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String, java.text.ParsePosition) + */ + @Override + public Object parseObject(final String source, final ParsePosition pos) { + return parse(source, pos); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String, java.text.ParsePosition) + */ + @Override + public Date parse(final String source, final ParsePosition pos) { + final int offset = pos.getIndex(); + final Matcher matcher = parsePattern.matcher(source.substring(offset)); + if (!matcher.lookingAt()) { + return null; + } + // timing tests indicate getting new instance is 19% faster than cloning + final Calendar cal = Calendar.getInstance(timeZone, locale); + cal.clear(); + + for (int i = 0; i < strategies.length; ) { + final Strategy strategy = strategies[i++]; + strategy.setCalendar(this, cal, matcher.group(i)); + } + pos.setIndex(offset + matcher.end()); + return cal.getTime(); + } + + // Support for strategies + //----------------------------------------------------------------------- + + /** + * Escape constant fields into regular expression + * + * @param regex The destination regex + * @param value The source field + * @param unquote If true, replace two success quotes ('') with single quote (') + * @return The StringBuilder + */ + private static StringBuilder escapeRegex(final StringBuilder regex, final String value, final boolean unquote) { + regex.append("\\Q"); + for (int i = 0; i < value.length(); ++i) { + char c = value.charAt(i); + switch (c) { + case '\'': + if (unquote) { + if (++i == value.length()) { + return regex; + } + c = value.charAt(i); + } + break; + case '\\': + if (++i == value.length()) { + break; + } + /* + * If we have found \E, we replace it with \E\\E\Q, i.e. we stop the quoting, + * quote the \ in \E, then restart the quoting. + * + * Otherwise we just output the two characters. + * In each case the initial \ needs to be output and the final char is done at the end + */ + regex.append(c); // we always want the original \ + c = value.charAt(i); // Is it followed by E ? + if (c == 'E') { // \E detected + regex.append("E\\\\E\\"); // see comment above + c = 'Q'; // appended below + } + break; + default: + break; + } + regex.append(c); + } + regex.append("\\E"); + return regex; + } + + private static String[] getDisplayNameArray(int field, boolean isLong, Locale locale) { + DateFormatSymbols dfs = new DateFormatSymbols(locale); + switch (field) { + case Calendar.AM_PM: + return dfs.getAmPmStrings(); + case Calendar.DAY_OF_WEEK: + return isLong ? dfs.getWeekdays() : dfs.getShortWeekdays(); + case Calendar.ERA: + return dfs.getEras(); + case Calendar.MONTH: + return isLong ? dfs.getMonths() : dfs.getShortMonths(); + } + return null; + } + + private static void insertValuesInMap(Map map, String[] values) { + if (values == null) { + return; + } + for (int i = 0; i < values.length; ++i) { + if (values[i] != null && values[i].length() > 0) { + map.put(values[i], i); + } + } + } + + private static Map getDisplayNames(int field, Locale locale) { + Map result = new HashMap(); + insertValuesInMap(result, getDisplayNameArray(field, false, locale)); + insertValuesInMap(result, getDisplayNameArray(field, true, locale)); + return result.isEmpty() ? null : result; + } + + /** + * Get the short and long values displayed for a field + * + * @param field The field of interest + * @param definingCalendar The calendar to obtain the short and long values + * @param locale The locale of display names + * @return A Map of the field key / value pairs + */ + private static Map getDisplayNames(final int field, final Calendar definingCalendar, final Locale locale) { + return getDisplayNames(field, locale); + } + + /** + * Adjust dates to be within appropriate century + * + * @param twoDigitYear The year to adjust + * @return A value between centuryStart(inclusive) to centuryStart+100(exclusive) + */ + private int adjustYear(final int twoDigitYear) { + int trial = century + twoDigitYear; + return twoDigitYear >= startYear ? trial : trial + 100; + } + + /** + * Is the next field a number? + * + * @return true, if next field will be a number + */ + boolean isNextNumber() { + return nextStrategy != null && nextStrategy.isNumber(); + } + + /** + * What is the width of the current field? + * + * @return The number of characters in the current format field + */ + int getFieldWidth() { + return currentFormatField.length(); + } + + /** + * A strategy to parse a single field from the parsing pattern + */ + private static abstract class Strategy { + /** + * Is this field a number? + * The default implementation returns false. + * + * @return true, if field is a number + */ + boolean isNumber() { + return false; + } + + /** + * Set the Calendar with the parsed field. + *

+ * The default implementation does nothing. + * + * @param parser The parser calling this strategy + * @param cal The Calendar to set + * @param value The parsed field to translate and set in cal + */ + void setCalendar(final FastDateParser parser, final Calendar cal, final String value) { + + } + + /** + * Generate a Pattern regular expression to the StringBuilder + * which will accept this field + * + * @param parser The parser calling this strategy + * @param regex The StringBuilder to append to + * @return true, if this field will set the calendar; + * false, if this field is a constant value + */ + abstract boolean addRegex(FastDateParser parser, StringBuilder regex); + } + + /** + * A Pattern to parse the user supplied SimpleDateFormat pattern + */ + private static final Pattern formatPattern = Pattern.compile( + "D+|E+|F+|G+|H+|K+|M+|L+|S+|W+|Z+|a+|d+|h+|k+|m+|s+|w+|y+|z+|''|'[^']++(''[^']*+)*+'|[^'A-Za-z]++"); + + /** + * Obtain a Strategy given a field from a SimpleDateFormat pattern + * + * @param formatField A sub-sequence of the SimpleDateFormat pattern + * @param definingCalendar The calendar to obtain the short and long values + * @return The Strategy that will handle parsing for the field + */ + private Strategy getStrategy(final String formatField, final Calendar definingCalendar) { + switch (formatField.charAt(0)) { + case '\'': + if (formatField.length() > 2) { + return new CopyQuotedStrategy(formatField.substring(1, formatField.length() - 1)); + } + //$FALL-THROUGH$ + default: + return new CopyQuotedStrategy(formatField); + case 'D': + return DAY_OF_YEAR_STRATEGY; + case 'E': + return getLocaleSpecificStrategy(Calendar.DAY_OF_WEEK, definingCalendar); + case 'F': + return DAY_OF_WEEK_IN_MONTH_STRATEGY; + case 'G': + return getLocaleSpecificStrategy(Calendar.ERA, definingCalendar); + case 'H': + return MODULO_HOUR_OF_DAY_STRATEGY; + case 'K': + return HOUR_STRATEGY; + case 'M': + case 'L': + return formatField.length() >= 3 ? getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) : NUMBER_MONTH_STRATEGY; + case 'S': + return MILLISECOND_STRATEGY; + case 'W': + return WEEK_OF_MONTH_STRATEGY; + case 'a': + return getLocaleSpecificStrategy(Calendar.AM_PM, definingCalendar); + case 'd': + return DAY_OF_MONTH_STRATEGY; + case 'h': + return MODULO_HOUR_STRATEGY; + case 'k': + return HOUR_OF_DAY_STRATEGY; + case 'm': + return MINUTE_STRATEGY; + case 's': + return SECOND_STRATEGY; + case 'w': + return WEEK_OF_YEAR_STRATEGY; + case 'y': + return formatField.length() > 2 ? LITERAL_YEAR_STRATEGY : ABBREVIATED_YEAR_STRATEGY; + case 'Z': + case 'z': + return getLocaleSpecificStrategy(Calendar.ZONE_OFFSET, definingCalendar); + } + } + + @SuppressWarnings("unchecked") // OK because we are creating an array with no entries + private static final ConcurrentMap[] caches = new ConcurrentMap[Calendar.FIELD_COUNT]; + + /** + * Get a cache of Strategies for a particular field + * + * @param field The Calendar field + * @return a cache of Locale to Strategy + */ + private static ConcurrentMap getCache(final int field) { + synchronized (caches) { + if (caches[field] == null) { + caches[field] = new ConcurrentHashMap(3); + } + return caches[field]; + } + } + + /** + * Construct a Strategy that parses a Text field + * + * @param field The Calendar field + * @param definingCalendar The calendar to obtain the short and long values + * @return a TextStrategy for the field and Locale + */ + private Strategy getLocaleSpecificStrategy(final int field, final Calendar definingCalendar) { + final ConcurrentMap cache = getCache(field); + Strategy strategy = cache.get(locale); + if (strategy == null) { + strategy = field == Calendar.ZONE_OFFSET + ? new TimeZoneStrategy(locale) + : new TextStrategy(field, definingCalendar, locale); + final Strategy inCache = cache.putIfAbsent(locale, strategy); + if (inCache != null) { + return inCache; + } + } + return strategy; + } + + /** + * A strategy that copies the static or quoted field in the parsing pattern + */ + private static class CopyQuotedStrategy extends Strategy { + private final String formatField; + + /** + * Construct a Strategy that ensures the formatField has literal text + * + * @param formatField The literal text to match + */ + CopyQuotedStrategy(final String formatField) { + this.formatField = formatField; + } + + /** + * {@inheritDoc} + */ + @Override + boolean isNumber() { + char c = formatField.charAt(0); + if (c == '\'') { + c = formatField.charAt(1); + } + return Character.isDigit(c); + } + + /** + * {@inheritDoc} + */ + @Override + boolean addRegex(final FastDateParser parser, final StringBuilder regex) { + escapeRegex(regex, formatField, true); + return false; + } + } + + /** + * A strategy that handles a text field in the parsing pattern + */ + private static class TextStrategy extends Strategy { + private final int field; + private final Map keyValues; + + /** + * Construct a Strategy that parses a Text field + * + * @param field The Calendar field + * @param definingCalendar The Calendar to use + * @param locale The Locale to use + */ + TextStrategy(final int field, final Calendar definingCalendar, final Locale locale) { + this.field = field; + this.keyValues = getDisplayNames(field, definingCalendar, locale); + } + + /** + * {@inheritDoc} + */ + @Override + boolean addRegex(final FastDateParser parser, final StringBuilder regex) { + regex.append('('); + for (final String textKeyValue : keyValues.keySet()) { + escapeRegex(regex, textKeyValue, false).append('|'); + } + regex.setCharAt(regex.length() - 1, ')'); + return true; + } + + /** + * {@inheritDoc} + */ + @Override + void setCalendar(final FastDateParser parser, final Calendar cal, final String value) { + final Integer iVal = keyValues.get(value); + if (iVal == null) { + final StringBuilder sb = new StringBuilder(value); + sb.append(" not in ("); + for (final String textKeyValue : keyValues.keySet()) { + sb.append(textKeyValue).append(' '); + } + sb.setCharAt(sb.length() - 1, ')'); + throw new IllegalArgumentException(sb.toString()); + } + cal.set(field, iVal.intValue()); + } + } + + + /** + * A strategy that handles a number field in the parsing pattern + */ + private static class NumberStrategy extends Strategy { + private final int field; + + /** + * Construct a Strategy that parses a Number field + * + * @param field The Calendar field + */ + NumberStrategy(final int field) { + this.field = field; + } + + /** + * {@inheritDoc} + */ + @Override + boolean isNumber() { + return true; + } + + /** + * {@inheritDoc} + */ + @Override + boolean addRegex(final FastDateParser parser, final StringBuilder regex) { + // See LANG-954: We use {Nd} rather than {IsNd} because Android does not support the Is prefix + if (parser.isNextNumber()) { + regex.append("(\\p{Nd}{").append(parser.getFieldWidth()).append("}+)"); + } else { + regex.append("(\\p{Nd}++)"); + } + return true; + } + + /** + * {@inheritDoc} + */ + @Override + void setCalendar(final FastDateParser parser, final Calendar cal, final String value) { + cal.set(field, modify(Integer.parseInt(value))); + } + + /** + * Make any modifications to parsed integer + * + * @param iValue The parsed integer + * @return The modified value + */ + int modify(final int iValue) { + return iValue; + } + } + + private static final Strategy ABBREVIATED_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR) { + /** + * {@inheritDoc} + */ + @Override + void setCalendar(final FastDateParser parser, final Calendar cal, final String value) { + int iValue = Integer.parseInt(value); + if (iValue < 100) { + iValue = parser.adjustYear(iValue); + } + cal.set(Calendar.YEAR, iValue); + } + }; + + /** + * A strategy that handles a timezone field in the parsing pattern + */ + private static class TimeZoneStrategy extends Strategy { + + private final String validTimeZoneChars; + private final SortedMap tzNames = new TreeMap(String.CASE_INSENSITIVE_ORDER); + + /** + * Index of zone id + */ + private static final int ID = 0; + /** + * Index of the long name of zone in standard time + */ + private static final int LONG_STD = 1; + /** + * Index of the short name of zone in standard time + */ + private static final int SHORT_STD = 2; + /** + * Index of the long name of zone in daylight saving time + */ + private static final int LONG_DST = 3; + /** + * Index of the short name of zone in daylight saving time + */ + private static final int SHORT_DST = 4; + + /** + * Construct a Strategy that parses a TimeZone + * + * @param locale The Locale + */ + TimeZoneStrategy(final Locale locale) { + final String[][] zones = DateFormatSymbols.getInstance(locale).getZoneStrings(); + for (String[] zone : zones) { + if (zone[ID].startsWith("GMT")) { + continue; + } + final TimeZone tz = TimeZone.getTimeZone(zone[ID]); + if (!tzNames.containsKey(zone[LONG_STD])) { + tzNames.put(zone[LONG_STD], tz); + } + if (!tzNames.containsKey(zone[SHORT_STD])) { + tzNames.put(zone[SHORT_STD], tz); + } + if (tz.useDaylightTime()) { + if (!tzNames.containsKey(zone[LONG_DST])) { + tzNames.put(zone[LONG_DST], tz); + } + if (!tzNames.containsKey(zone[SHORT_DST])) { + tzNames.put(zone[SHORT_DST], tz); + } + } + } + + final StringBuilder sb = new StringBuilder(); + sb.append("(GMT[+\\-]\\d{0,1}\\d{2}|[+\\-]\\d{2}:?\\d{2}|"); + for (final String id : tzNames.keySet()) { + escapeRegex(sb, id, false).append('|'); + } + sb.setCharAt(sb.length() - 1, ')'); + validTimeZoneChars = sb.toString(); + } + + /** + * {@inheritDoc} + */ + @Override + boolean addRegex(final FastDateParser parser, final StringBuilder regex) { + regex.append(validTimeZoneChars); + return true; + } + + /** + * {@inheritDoc} + */ + @Override + void setCalendar(final FastDateParser parser, final Calendar cal, final String value) { + TimeZone tz; + if (value.charAt(0) == '+' || value.charAt(0) == '-') { + tz = TimeZone.getTimeZone("GMT" + value); + } else if (value.startsWith("GMT")) { + tz = TimeZone.getTimeZone(value); + } else { + tz = tzNames.get(value); + if (tz == null) { + throw new IllegalArgumentException(value + " is not a supported timezone name"); + } + } + cal.setTimeZone(tz); + } + } + + private static final Strategy NUMBER_MONTH_STRATEGY = new NumberStrategy(Calendar.MONTH) { + @Override + int modify(final int iValue) { + return iValue - 1; + } + }; + private static final Strategy LITERAL_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR); + private static final Strategy WEEK_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_YEAR); + private static final Strategy WEEK_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_MONTH); + private static final Strategy DAY_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.DAY_OF_YEAR); + private static final Strategy DAY_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_MONTH); + private static final Strategy DAY_OF_WEEK_IN_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_WEEK_IN_MONTH); + private static final Strategy HOUR_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY); + private static final Strategy MODULO_HOUR_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY) { + @Override + int modify(final int iValue) { + return iValue % 24; + } + }; + private static final Strategy MODULO_HOUR_STRATEGY = new NumberStrategy(Calendar.HOUR) { + @Override + int modify(final int iValue) { + return iValue % 12; + } + }; + private static final Strategy HOUR_STRATEGY = new NumberStrategy(Calendar.HOUR); + private static final Strategy MINUTE_STRATEGY = new NumberStrategy(Calendar.MINUTE); + private static final Strategy SECOND_STRATEGY = new NumberStrategy(Calendar.SECOND); + private static final Strategy MILLISECOND_STRATEGY = new NumberStrategy(Calendar.MILLISECOND); +} diff --git a/app/src/main/java/io/github/chronosx88/radium/utils/time/FastDatePrinter.java b/app/src/main/java/io/github/chronosx88/radium/utils/time/FastDatePrinter.java new file mode 100644 index 0000000..89cf27e --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/radium/utils/time/FastDatePrinter.java @@ -0,0 +1,1291 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.chronosx88.radium.utils.time; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serializable; +import java.text.DateFormat; +import java.text.DateFormatSymbols; +import java.text.FieldPosition; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Locale; +import java.util.TimeZone; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + *

FastDatePrinter is a fast and thread-safe version of + * {@link java.text.SimpleDateFormat}.

+ * + *

This class can be used as a direct replacement to + * {@code SimpleDateFormat} in most formatting situations. + * This class is especially useful in multi-threaded server environments. + * {@code SimpleDateFormat} is not thread-safe in any JDK version, + * nor will it be as Sun have closed the bug/RFE. + *

+ * + *

Only formatting is supported, but all patterns are compatible with + * SimpleDateFormat (except time zones and some year patterns - see below).

+ * + *

Java 1.4 introduced a new pattern letter, {@code 'Z'}, to represent + * time zones in RFC822 format (eg. {@code +0800} or {@code -1100}). + * This pattern letter can be used here (on all JDK versions).

+ * + *

In addition, the pattern {@code 'ZZ'} has been made to represent + * ISO8601 full format time zones (eg. {@code +08:00} or {@code -11:00}). + * This introduces a minor incompatibility with Java 1.4, but at a gain of + * useful functionality.

+ * + *

Javadoc cites for the year pattern: For formatting, if the number of + * pattern letters is 2, the year is truncated to 2 digits; otherwise it is + * interpreted as a number. Starting with Java 1.7 a pattern of 'Y' or + * 'YYY' will be formatted as '2003', while it was '03' in former Java + * versions. FastDatePrinter implements the behavior of Java 7.

+ * + * @version $Id: FastDatePrinter.java 1567799 2014-02-12 23:25:58Z sebb $ + * @since 3.2 + */ +public class FastDatePrinter implements DatePrinter, Serializable { + // A lot of the speed in this class comes from caching, but some comes + // from the special int to StringBuffer conversion. + // + // The following produces a padded 2 digit number: + // buffer.append((char)(value / 10 + '0')); + // buffer.append((char)(value % 10 + '0')); + // + // Note that the fastest append to StringBuffer is a single char (used here). + // Note that Integer.toString() is not called, the conversion is simply + // taking the value and adding (mathematically) the ASCII value for '0'. + // So, don't change this code! It works and is very fast. + + /** + * Required for serialization support. + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + /** + * FULL locale dependent date or time style. + */ + public static final int FULL = DateFormat.FULL; + /** + * LONG locale dependent date or time style. + */ + public static final int LONG = DateFormat.LONG; + /** + * MEDIUM locale dependent date or time style. + */ + public static final int MEDIUM = DateFormat.MEDIUM; + /** + * SHORT locale dependent date or time style. + */ + public static final int SHORT = DateFormat.SHORT; + + /** + * The pattern. + */ + private final String mPattern; + /** + * The time zone. + */ + private final TimeZone mTimeZone; + /** + * The locale. + */ + private final Locale mLocale; + /** + * The parsed rules. + */ + private transient Rule[] mRules; + /** + * The estimated maximum length. + */ + private transient int mMaxLengthEstimate; + + // Constructor + //----------------------------------------------------------------------- + + /** + *

Constructs a new FastDatePrinter.

+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale to use + * @throws NullPointerException if pattern, timeZone, or locale is null. + */ + protected FastDatePrinter(final String pattern, final TimeZone timeZone, final Locale locale) { + mPattern = pattern; + mTimeZone = timeZone; + mLocale = locale; + + init(); + } + + /** + *

Initializes the instance for first use.

+ */ + private void init() { + final List rulesList = parsePattern(); + mRules = rulesList.toArray(new Rule[rulesList.size()]); + + int len = 0; + for (int i = mRules.length; --i >= 0; ) { + len += mRules[i].estimateLength(); + } + + mMaxLengthEstimate = len; + } + + // Parse the pattern + //----------------------------------------------------------------------- + + /** + *

Returns a list of Rules given a pattern.

+ * + * @return a {@code List} of Rule objects + * @throws IllegalArgumentException if pattern is invalid + */ + + protected List parsePattern() { + final DateFormatSymbols symbols = new DateFormatSymbols(mLocale); + final List rules = new ArrayList(); + + final String[] ERAs = symbols.getEras(); + final String[] months = symbols.getMonths(); + + final String[] shortMonths = symbols.getShortMonths(); + final String[] weekdays = symbols.getWeekdays(); + final String[] shortWeekdays = symbols.getShortWeekdays(); + final String[] AmPmStrings = symbols.getAmPmStrings(); + + final int length = mPattern.length(); + final int[] indexRef = new int[1]; + + for (int i = 0; i < length; i++) { + indexRef[0] = i; + final String token = parseToken(mPattern, indexRef); + i = indexRef[0]; + + final int tokenLen = token.length(); + if (tokenLen == 0) { + break; + } + + Rule rule; + final char c = token.charAt(0); + + switch (c) { + case 'G': // era designator (text) + rule = new TextField(Calendar.ERA, ERAs); + break; + case 'y': // year (number) + if (tokenLen == 2) { + rule = TwoDigitYearField.INSTANCE; + } else { + rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen); + } + break; + case 'L': // month in year (text and number) + if (tokenLen >= 4) { + rule = new TextField(Calendar.MONTH, months); + } else if (tokenLen == 3) { + rule = new TextField(Calendar.MONTH, shortMonths); + } else if (tokenLen == 2) { + rule = TwoDigitMonthField.INSTANCE; + } else { + rule = UnpaddedMonthField.INSTANCE; + } + break; + case 'M': // month in year (text and number) + if (tokenLen >= 4) { + rule = new TextField(Calendar.MONTH, months); + } else if (tokenLen == 3) { + rule = new TextField(Calendar.MONTH, shortMonths); + } else if (tokenLen == 2) { + rule = TwoDigitMonthField.INSTANCE; + } else { + rule = UnpaddedMonthField.INSTANCE; + } + break; + case 'd': // day in month (number) + rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen); + break; + case 'h': // hour in am/pm (number, 1..12) + rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen)); + break; + case 'H': // hour in day (number, 0..23) + rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen); + break; + case 'm': // minute in hour (number) + rule = selectNumberRule(Calendar.MINUTE, tokenLen); + break; + case 's': // second in minute (number) + rule = selectNumberRule(Calendar.SECOND, tokenLen); + break; + case 'S': // millisecond (number) + rule = selectNumberRule(Calendar.MILLISECOND, tokenLen); + break; + case 'E': // day in week (text) + rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays); + break; + case 'D': // day in year (number) + rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen); + break; + case 'F': // day of week in month (number) + rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen); + break; + case 'w': // week in year (number) + rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen); + break; + case 'W': // week in month (number) + rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen); + break; + case 'a': // am/pm marker (text) + rule = new TextField(Calendar.AM_PM, AmPmStrings); + break; + case 'k': // hour in day (1..24) + rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen)); + break; + case 'K': // hour in am/pm (0..11) + rule = selectNumberRule(Calendar.HOUR, tokenLen); + break; + case 'z': // time zone (text) + if (tokenLen >= 4) { + rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG); + } else { + rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT); + } + break; + case 'Z': // time zone (value) + if (tokenLen == 1) { + rule = TimeZoneNumberRule.INSTANCE_NO_COLON; + } else { + rule = TimeZoneNumberRule.INSTANCE_COLON; + } + break; + case '\'': // literal text + final String sub = token.substring(1); + if (sub.length() == 1) { + rule = new CharacterLiteral(sub.charAt(0)); + } else { + rule = new StringLiteral(sub); + } + break; + default: + throw new IllegalArgumentException("Illegal pattern component: " + token); + } + + rules.add(rule); + } + + return rules; + } + + /** + *

Performs the parsing of tokens.

+ * + * @param pattern the pattern + * @param indexRef index references + * @return parsed token + */ + protected String parseToken(final String pattern, final int[] indexRef) { + final StringBuilder buf = new StringBuilder(); + + int i = indexRef[0]; + final int length = pattern.length(); + + char c = pattern.charAt(i); + if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') { + // Scan a run of the same character, which indicates a time + // pattern. + buf.append(c); + + while (i + 1 < length) { + final char peek = pattern.charAt(i + 1); + if (peek == c) { + buf.append(c); + i++; + } else { + break; + } + } + } else { + // This will identify token as text. + buf.append('\''); + + boolean inLiteral = false; + + for (; i < length; i++) { + c = pattern.charAt(i); + + if (c == '\'') { + if (i + 1 < length && pattern.charAt(i + 1) == '\'') { + // '' is treated as escaped ' + i++; + buf.append(c); + } else { + inLiteral = !inLiteral; + } + } else if (!inLiteral && + (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) { + i--; + break; + } else { + buf.append(c); + } + } + } + + indexRef[0] = i; + return buf.toString(); + } + + /** + *

Gets an appropriate rule for the padding required.

+ * + * @param field the field to get a rule for + * @param padding the padding required + * @return a new rule with the correct padding + */ + protected NumberRule selectNumberRule(final int field, final int padding) { + switch (padding) { + case 1: + return new UnpaddedNumberField(field); + case 2: + return new TwoDigitNumberField(field); + default: + return new PaddedNumberField(field, padding); + } + } + + // Format methods + //----------------------------------------------------------------------- + + /** + *

Formats a {@code Date}, {@code Calendar} or + * {@code Long} (milliseconds) object.

+ * + * @param obj the object to format + * @param toAppendTo the buffer to append to + * @param pos the position - ignored + * @return the buffer passed in + */ + @Override + public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { + if (obj instanceof Date) { + return format((Date) obj, toAppendTo); + } else if (obj instanceof Calendar) { + return format((Calendar) obj, toAppendTo); + } else if (obj instanceof Long) { + return format(((Long) obj).longValue(), toAppendTo); + } else { + throw new IllegalArgumentException("Unknown class: " + + (obj == null ? "" : obj.getClass().getName())); + } + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(long) + */ + @Override + public String format(final long millis) { + final Calendar c = newCalendar(); // hard code GregorianCalendar + c.setTimeInMillis(millis); + return applyRulesToString(c); + } + + /** + * Creates a String representation of the given Calendar by applying the rules of this printer to it. + * + * @param c the Calender to apply the rules to. + * @return a String representation of the given Calendar. + */ + private String applyRulesToString(final Calendar c) { + return applyRules(c, new StringBuffer(mMaxLengthEstimate)).toString(); + } + + /** + * Creation method for ne calender instances. + * + * @return a new Calendar instance. + */ + private GregorianCalendar newCalendar() { + // hard code GregorianCalendar + return new GregorianCalendar(mTimeZone, mLocale); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date) + */ + @Override + public String format(final Date date) { + final Calendar c = newCalendar(); // hard code GregorianCalendar + c.setTime(date); + return applyRulesToString(c); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar) + */ + @Override + public String format(final Calendar calendar) { + return format(calendar, new StringBuffer(mMaxLengthEstimate)).toString(); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(long, java.lang.StringBuffer) + */ + @Override + public StringBuffer format(final long millis, final StringBuffer buf) { + return format(new Date(millis), buf); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, java.lang.StringBuffer) + */ + @Override + public StringBuffer format(final Date date, final StringBuffer buf) { + final Calendar c = newCalendar(); // hard code GregorianCalendar + c.setTime(date); + return applyRules(c, buf); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, java.lang.StringBuffer) + */ + @Override + public StringBuffer format(final Calendar calendar, final StringBuffer buf) { + return applyRules(calendar, buf); + } + + /** + *

Performs the formatting by applying the rules to the + * specified calendar.

+ * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + */ + protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) { + for (final Rule rule : mRules) { + rule.appendTo(buf, calendar); + } + return buf; + } + + // Accessors + //----------------------------------------------------------------------- + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#getPattern() + */ + @Override + public String getPattern() { + return mPattern; + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#getTimeZone() + */ + @Override + public TimeZone getTimeZone() { + return mTimeZone; + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#getLocale() + */ + @Override + public Locale getLocale() { + return mLocale; + } + + /** + *

Gets an estimate for the maximum string length that the + * formatter will produce.

+ *

+ *

The actual formatted length will almost always be less than or + * equal to this amount.

+ * + * @return the maximum formatted length + */ + public int getMaxLengthEstimate() { + return mMaxLengthEstimate; + } + + // Basics + //----------------------------------------------------------------------- + + /** + *

Compares two objects for equality.

+ * + * @param obj the object to compare to + * @return {@code true} if equal + */ + @Override + public boolean equals(final Object obj) { + if (!(obj instanceof FastDatePrinter)) { + return false; + } + final FastDatePrinter other = (FastDatePrinter) obj; + return mPattern.equals(other.mPattern) + && mTimeZone.equals(other.mTimeZone) + && mLocale.equals(other.mLocale); + } + + /** + *

Returns a hashcode compatible with equals.

+ * + * @return a hashcode compatible with equals + */ + @Override + public int hashCode() { + return mPattern.hashCode() + 13 * (mTimeZone.hashCode() + 13 * mLocale.hashCode()); + } + + /** + *

Gets a debugging string version of this formatter.

+ * + * @return a debugging string + */ + @Override + public String toString() { + return "FastDatePrinter[" + mPattern + "," + mLocale + "," + mTimeZone.getID() + "]"; + } + + // Serializing + //----------------------------------------------------------------------- + + /** + * Create the object after serialization. This implementation reinitializes the + * transient properties. + * + * @param in ObjectInputStream from which the object is being deserialized. + * @throws IOException if there is an IO issue. + * @throws ClassNotFoundException if a class cannot be found. + */ + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + init(); + } + + // Rules + //----------------------------------------------------------------------- + + /** + *

Inner class defining a rule.

+ */ + private interface Rule { + /** + * Returns the estimated lentgh of the result. + * + * @return the estimated length + */ + int estimateLength(); + + /** + * Appends the value of the specified calendar to the output buffer based on the rule implementation. + * + * @param buffer the output buffer + * @param calendar calendar to be appended + */ + void appendTo(StringBuffer buffer, Calendar calendar); + } + + /** + *

Inner class defining a numeric rule.

+ */ + private interface NumberRule extends Rule { + /** + * Appends the specified value to the output buffer based on the rule implementation. + * + * @param buffer the output buffer + * @param value the value to be appended + */ + void appendTo(StringBuffer buffer, int value); + } + + /** + *

Inner class to output a constant single character.

+ */ + private static class CharacterLiteral implements Rule { + private final char mValue; + + /** + * Constructs a new instance of {@code CharacterLiteral} + * to hold the specified value. + * + * @param value the character literal + */ + CharacterLiteral(final char value) { + mValue = value; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 1; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + buffer.append(mValue); + } + } + + /** + *

Inner class to output a constant string.

+ */ + private static class StringLiteral implements Rule { + private final String mValue; + + /** + * Constructs a new instance of {@code StringLiteral} + * to hold the specified value. + * + * @param value the string literal + */ + StringLiteral(final String value) { + mValue = value; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return mValue.length(); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + buffer.append(mValue); + } + } + + /** + *

Inner class to output one of a set of values.

+ */ + private static class TextField implements Rule { + private final int mField; + private final String[] mValues; + + /** + * Constructs an instance of {@code TextField} + * with the specified field and values. + * + * @param field the field + * @param values the field values + */ + TextField(final int field, final String[] values) { + mField = field; + mValues = values; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + int max = 0; + for (int i = mValues.length; --i >= 0; ) { + final int len = mValues[i].length(); + if (len > max) { + max = len; + } + } + return max; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + buffer.append(mValues[calendar.get(mField)]); + } + } + + /** + *

Inner class to output an unpadded number.

+ */ + private static class UnpaddedNumberField implements NumberRule { + private final int mField; + + /** + * Constructs an instance of {@code UnpadedNumberField} with the specified field. + * + * @param field the field + */ + UnpaddedNumberField(final int field) { + mField = field; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 4; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + appendTo(buffer, calendar.get(mField)); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final StringBuffer buffer, final int value) { + if (value < 10) { + buffer.append((char) (value + '0')); + } else if (value < 100) { + buffer.append((char) (value / 10 + '0')); + buffer.append((char) (value % 10 + '0')); + } else { + buffer.append(Integer.toString(value)); + } + } + } + + /** + *

Inner class to output an unpadded month.

+ */ + private static class UnpaddedMonthField implements NumberRule { + static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField(); + + /** + * Constructs an instance of {@code UnpaddedMonthField}. + */ + UnpaddedMonthField() { + super(); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + appendTo(buffer, calendar.get(Calendar.MONTH) + 1); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final StringBuffer buffer, final int value) { + if (value < 10) { + buffer.append((char) (value + '0')); + } else { + buffer.append((char) (value / 10 + '0')); + buffer.append((char) (value % 10 + '0')); + } + } + } + + /** + *

Inner class to output a padded number.

+ */ + private static class PaddedNumberField implements NumberRule { + private final int mField; + private final int mSize; + + /** + * Constructs an instance of {@code PaddedNumberField}. + * + * @param field the field + * @param size size of the output field + */ + PaddedNumberField(final int field, final int size) { + if (size < 3) { + // Should use UnpaddedNumberField or TwoDigitNumberField. + throw new IllegalArgumentException(); + } + mField = field; + mSize = size; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 4; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + appendTo(buffer, calendar.get(mField)); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final StringBuffer buffer, final int value) { + if (value < 100) { + for (int i = mSize; --i >= 2; ) { + buffer.append('0'); + } + buffer.append((char) (value / 10 + '0')); + buffer.append((char) (value % 10 + '0')); + } else { + int digits; + if (value < 1000) { + digits = 3; + } else { + digits = Integer.toString(value).length(); + } + for (int i = mSize; --i >= digits; ) { + buffer.append('0'); + } + buffer.append(Integer.toString(value)); + } + } + } + + /** + *

Inner class to output a two digit number.

+ */ + private static class TwoDigitNumberField implements NumberRule { + private final int mField; + + /** + * Constructs an instance of {@code TwoDigitNumberField} with the specified field. + * + * @param field the field + */ + TwoDigitNumberField(final int field) { + mField = field; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + appendTo(buffer, calendar.get(mField)); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final StringBuffer buffer, final int value) { + if (value < 100) { + buffer.append((char) (value / 10 + '0')); + buffer.append((char) (value % 10 + '0')); + } else { + buffer.append(Integer.toString(value)); + } + } + } + + /** + *

Inner class to output a two digit year.

+ */ + private static class TwoDigitYearField implements NumberRule { + static final TwoDigitYearField INSTANCE = new TwoDigitYearField(); + + /** + * Constructs an instance of {@code TwoDigitYearField}. + */ + TwoDigitYearField() { + super(); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + appendTo(buffer, calendar.get(Calendar.YEAR) % 100); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final StringBuffer buffer, final int value) { + buffer.append((char) (value / 10 + '0')); + buffer.append((char) (value % 10 + '0')); + } + } + + /** + *

Inner class to output a two digit month.

+ */ + private static class TwoDigitMonthField implements NumberRule { + static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField(); + + /** + * Constructs an instance of {@code TwoDigitMonthField}. + */ + TwoDigitMonthField() { + super(); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + appendTo(buffer, calendar.get(Calendar.MONTH) + 1); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final StringBuffer buffer, final int value) { + buffer.append((char) (value / 10 + '0')); + buffer.append((char) (value % 10 + '0')); + } + } + + /** + *

Inner class to output the twelve hour field.

+ */ + private static class TwelveHourField implements NumberRule { + private final NumberRule mRule; + + /** + * Constructs an instance of {@code TwelveHourField} with the specified + * {@code NumberRule}. + * + * @param rule the rule + */ + TwelveHourField(final NumberRule rule) { + mRule = rule; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return mRule.estimateLength(); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + int value = calendar.get(Calendar.HOUR); + if (value == 0) { + value = calendar.getLeastMaximum(Calendar.HOUR) + 1; + } + mRule.appendTo(buffer, value); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final int value) { + mRule.appendTo(buffer, value); + } + } + + /** + *

Inner class to output the twenty four hour field.

+ */ + private static class TwentyFourHourField implements NumberRule { + private final NumberRule mRule; + + /** + * Constructs an instance of {@code TwentyFourHourField} with the specified + * {@code NumberRule}. + * + * @param rule the rule + */ + TwentyFourHourField(final NumberRule rule) { + mRule = rule; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return mRule.estimateLength(); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + int value = calendar.get(Calendar.HOUR_OF_DAY); + if (value == 0) { + value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1; + } + mRule.appendTo(buffer, value); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final int value) { + mRule.appendTo(buffer, value); + } + } + + //----------------------------------------------------------------------- + + private static final ConcurrentMap cTimeZoneDisplayCache = + new ConcurrentHashMap(7); + + /** + *

Gets the time zone display name, using a cache for performance.

+ * + * @param tz the zone to query + * @param daylight true if daylight savings + * @param style the style to use {@code TimeZone.LONG} or {@code TimeZone.SHORT} + * @param locale the locale to use + * @return the textual name of the time zone + */ + static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale) { + final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale); + String value = cTimeZoneDisplayCache.get(key); + if (value == null) { + // This is a very slow call, so cache the results. + value = tz.getDisplayName(daylight, style, locale); + final String prior = cTimeZoneDisplayCache.putIfAbsent(key, value); + if (prior != null) { + value = prior; + } + } + return value; + } + + /** + *

Inner class to output a time zone name.

+ */ + private static class TimeZoneNameRule implements Rule { + private final Locale mLocale; + private final int mStyle; + private final String mStandard; + private final String mDaylight; + + /** + * Constructs an instance of {@code TimeZoneNameRule} with the specified properties. + * + * @param timeZone the time zone + * @param locale the locale + * @param style the style + */ + TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style) { + mLocale = locale; + mStyle = style; + + mStandard = getTimeZoneDisplay(timeZone, false, style, locale); + mDaylight = getTimeZoneDisplay(timeZone, true, style, locale); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + // We have no access to the Calendar object that will be passed to + // appendTo so base estimate on the TimeZone passed to the + // constructor + return Math.max(mStandard.length(), mDaylight.length()); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + final TimeZone zone = calendar.getTimeZone(); + if (zone.useDaylightTime() + && calendar.get(Calendar.DST_OFFSET) != 0) { + buffer.append(getTimeZoneDisplay(zone, true, mStyle, mLocale)); + } else { + buffer.append(getTimeZoneDisplay(zone, false, mStyle, mLocale)); + } + } + } + + /** + *

Inner class to output a time zone as a number {@code +/-HHMM} + * or {@code +/-HH:MM}.

+ */ + private static class TimeZoneNumberRule implements Rule { + static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true); + static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false); + + final boolean mColon; + + /** + * Constructs an instance of {@code TimeZoneNumberRule} with the specified properties. + * + * @param colon add colon between HH and MM in the output if {@code true} + */ + TimeZoneNumberRule(final boolean colon) { + mColon = colon; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 5; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final StringBuffer buffer, final Calendar calendar) { + int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); + + if (offset < 0) { + buffer.append('-'); + offset = -offset; + } else { + buffer.append('+'); + } + + final int hours = offset / (60 * 60 * 1000); + buffer.append((char) (hours / 10 + '0')); + buffer.append((char) (hours % 10 + '0')); + + if (mColon) { + buffer.append(':'); + } + + final int minutes = offset / (60 * 1000) - 60 * hours; + buffer.append((char) (minutes / 10 + '0')); + buffer.append((char) (minutes % 10 + '0')); + } + } + + // ---------------------------------------------------------------------- + + /** + *

Inner class that acts as a compound key for time zone names.

+ */ + private static class TimeZoneDisplayKey { + private final TimeZone mTimeZone; + private final int mStyle; + private final Locale mLocale; + + /** + * Constructs an instance of {@code TimeZoneDisplayKey} with the specified properties. + * + * @param timeZone the time zone + * @param daylight adjust the style for daylight saving time if {@code true} + * @param style the timezone style + * @param locale the timezone locale + */ + TimeZoneDisplayKey(final TimeZone timeZone, + final boolean daylight, final int style, final Locale locale) { + mTimeZone = timeZone; + if (daylight) { + mStyle = style | 0x80000000; + } else { + mStyle = style; + } + mLocale = locale; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + return (mStyle * 31 + mLocale.hashCode()) * 31 + mTimeZone.hashCode(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof TimeZoneDisplayKey) { + final TimeZoneDisplayKey other = (TimeZoneDisplayKey) obj; + return + mTimeZone.equals(other.mTimeZone) && + mStyle == other.mStyle && + mLocale.equals(other.mLocale); + } + return false; + } + } +} diff --git a/app/src/main/java/io/github/chronosx88/radium/utils/time/FormatCache.java b/app/src/main/java/io/github/chronosx88/radium/utils/time/FormatCache.java new file mode 100644 index 0000000..88df5c3 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/radium/utils/time/FormatCache.java @@ -0,0 +1,267 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.github.chronosx88.radium.utils.time; + +import java.text.DateFormat; +import java.text.Format; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Locale; +import java.util.TimeZone; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + *

FormatCache is a cache and factory for {@link Format}s.

+ * + * @since 3.0 + * @version $Id: FormatCache 892161 2009-12-18 07:21:10Z $ + */ +// TODO: Before making public move from getDateTimeInstance(Integer,...) to int; or some other approach. +abstract class FormatCache { + /** + * No date or no time. Used in same parameters as DateFormat.SHORT or DateFormat.LONG + */ + static final int NONE = -1; + + private final ConcurrentMap cInstanceCache + = new ConcurrentHashMap(7); + + private static final ConcurrentMap cDateTimeInstanceCache + = new ConcurrentHashMap(7); + + /** + *

Gets a formatter instance using the default pattern in the + * default timezone and locale.

+ * + * @return a date/time formatter + */ + public F getInstance() { + return getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, TimeZone.getDefault(), Locale.getDefault()); + } + + /** + *

Gets a formatter instance using the specified pattern, time zone + * and locale.

+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible + * pattern, non-null + * @param timeZone the time zone, null means use the default TimeZone + * @param locale the locale, null means use the default Locale + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + * or null + */ + public F getInstance(final String pattern, TimeZone timeZone, Locale locale) { + if (pattern == null) { + throw new NullPointerException("pattern must not be null"); + } + if (timeZone == null) { + timeZone = TimeZone.getDefault(); + } + if (locale == null) { + locale = Locale.getDefault(); + } + final MultipartKey key = new MultipartKey(pattern, timeZone, locale); + F format = cInstanceCache.get(key); + if (format == null) { + format = createInstance(pattern, timeZone, locale); + final F previousValue = cInstanceCache.putIfAbsent(key, format); + if (previousValue != null) { + // another thread snuck in and did the same work + // we should return the instance that is in ConcurrentMap + format = previousValue; + } + } + return format; + } + + /** + *

Create a format instance using the specified pattern, time zone + * and locale.

+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern, this will not be null. + * @param timeZone time zone, this will not be null. + * @param locale locale, this will not be null. + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + * or null + */ + abstract protected F createInstance(String pattern, TimeZone timeZone, Locale locale); + + /** + *

Gets a date/time formatter instance using the specified style, + * time zone and locale.

+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT, null indicates no date in format + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT, null indicates no time in format + * @param timeZone optional time zone, overrides time zone of + * formatted date, null means use default Locale + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + */ + // This must remain private, see LANG-884 + private F getDateTimeInstance(final Integer dateStyle, final Integer timeStyle, final TimeZone timeZone, Locale locale) { + if (locale == null) { + locale = Locale.getDefault(); + } + final String pattern = getPatternForStyle(dateStyle, timeStyle, locale); + return getInstance(pattern, timeZone, locale); + } + + /** + *

Gets a date/time formatter instance using the specified style, + * time zone and locale.

+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted date, null means use default Locale + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + */ + // package protected, for access from FastDateFormat; do not make public or protected + F getDateTimeInstance(final int dateStyle, final int timeStyle, final TimeZone timeZone, Locale locale) { + return getDateTimeInstance(Integer.valueOf(dateStyle), Integer.valueOf(timeStyle), timeZone, locale); + } + + /** + *

Gets a date formatter instance using the specified style, + * time zone and locale.

+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted date, null means use default Locale + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + */ + // package protected, for access from FastDateFormat; do not make public or protected + F getDateInstance(final int dateStyle, final TimeZone timeZone, Locale locale) { + return getDateTimeInstance(Integer.valueOf(dateStyle), null, timeZone, locale); + } + + /** + *

Gets a time formatter instance using the specified style, + * time zone and locale.

+ * + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of + * formatted date, null means use default Locale + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + */ + // package protected, for access from FastDateFormat; do not make public or protected + F getTimeInstance(final int timeStyle, final TimeZone timeZone, Locale locale) { + return getDateTimeInstance(null, Integer.valueOf(timeStyle), timeZone, locale); + } + + /** + *

Gets a date/time format for the specified styles and locale.

+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT, null indicates no date in format + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT, null indicates no time in format + * @param locale The non-null locale of the desired format + * @return a localized standard date/time format + * @throws IllegalArgumentException if the Locale has no date/time pattern defined + */ + // package protected, for access from test code; do not make public or protected + static String getPatternForStyle(final Integer dateStyle, final Integer timeStyle, final Locale locale) { + final MultipartKey key = new MultipartKey(dateStyle, timeStyle, locale); + + String pattern = cDateTimeInstanceCache.get(key); + if (pattern == null) { + try { + DateFormat formatter; + if (dateStyle == null) { + formatter = DateFormat.getTimeInstance(timeStyle.intValue(), locale); + } else if (timeStyle == null) { + formatter = DateFormat.getDateInstance(dateStyle.intValue(), locale); + } else { + formatter = DateFormat.getDateTimeInstance(dateStyle.intValue(), timeStyle.intValue(), locale); + } + pattern = ((SimpleDateFormat) formatter).toPattern(); + final String previous = cDateTimeInstanceCache.putIfAbsent(key, pattern); + if (previous != null) { + // even though it doesn't matter if another thread put the pattern + // it's still good practice to return the String instance that is + // actually in the ConcurrentMap + pattern = previous; + } + } catch (final ClassCastException ex) { + throw new IllegalArgumentException("No date time pattern for locale: " + locale); + } + } + return pattern; + } + + // ---------------------------------------------------------------------- + + /** + *

Helper class to hold multi-part Map keys

+ */ + private static class MultipartKey { + private final Object[] keys; + private int hashCode; + + /** + * Constructs an instance of MultipartKey to hold the specified objects. + * + * @param keys the set of objects that make up the key. Each key may be null. + */ + public MultipartKey(final Object... keys) { + this.keys = keys; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(final Object obj) { + // Eliminate the usual boilerplate because + // this inner static class is only used in a generic ConcurrentHashMap + // which will not compare against other Object types + return Arrays.equals(keys, ((MultipartKey) obj).keys); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + if (hashCode == 0) { + int rc = 0; + for (final Object key : keys) { + if (key != null) { + rc = rc * 7 + key.hashCode(); + } + } + hashCode = rc; + } + return hashCode; + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/radium/utils/time/LocaleUtils.kt b/app/src/main/java/io/github/chronosx88/radium/utils/time/LocaleUtils.kt new file mode 100644 index 0000000..9bdac0c --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/radium/utils/time/LocaleUtils.kt @@ -0,0 +1,87 @@ +/* + * This is the source code of Telegram for Android v. 1.3.x. + * It is licensed under GNU GPL v. 2 or later. + * You should have received a copy of the license in this archive (see LICENSE). + * + * Copyright Nikolai Kudashov, 2013-2018. + */ + +package io.github.chronosx88.radium.utils.time + +import android.content.Context +import android.text.format.DateFormat +import android.util.Log +import io.github.chronosx88.radium.R +import java.util.* + +// NOTE kindly taken from https://github.com/DrKLO/Telegram +object LocaleUtils { + private lateinit var formatterDay: FastDateFormat + private lateinit var formatterWeek: FastDateFormat + private lateinit var formatterDayMonth: FastDateFormat + private lateinit var formatterYear: FastDateFormat + + fun initFormatters(context: Context) { + val locale = Locale.getDefault(); + val lang = locale.language.toLowerCase() + formatterDayMonth = createFormatter( + locale, + context.getString(R.string.formatterMonth), + "dd MMM" + ) + formatterYear = createFormatter( + locale, + context.getString(R.string.formatterYear), + "dd.MM.yy" + ) + formatterWeek = createFormatter( + locale, + context.getString(R.string.formatterWeek), + "EEE" + ) + formatterDay = createFormatter( + if (lang.equals("ar") || lang.equals("ko")) locale else Locale.US, + if (DateFormat.is24HourFormat(context)) context.getString(R.string.formatterDay24H) else context.getString(R.string.formatterDay12H), + if (DateFormat.is24HourFormat(context)) "HH:mm" else "h:mm a" + ) + } + + private fun createFormatter( + locale: Locale, + format: String, + defaultFormat: String + ): FastDateFormat { + var formatter: FastDateFormat? + try { + formatter = FastDateFormat.getInstance(format, locale) + } catch (e: java.lang.Exception) { + formatter = FastDateFormat.getInstance(defaultFormat, locale) + } + return formatter!! + } + + fun stringForMessageListDate(date: Long): String? { + try { +// date *= 1000 + val rightNow = Calendar.getInstance() + val day: Int = rightNow.get(Calendar.DAY_OF_YEAR) + rightNow.setTimeInMillis(date) + val dateDay: Int = rightNow.get(Calendar.DAY_OF_YEAR) + return if (Math.abs(System.currentTimeMillis() - date) >= 31536000000L) { + formatterYear.format(Date(date)) + } else { + val dayDiff = dateDay - day + if (dayDiff == 0 || dayDiff == -1 && System.currentTimeMillis() - date < 60 * 60 * 8 * 1000) { + formatterDay.format(Date(date)) + } else if (dayDiff > -7 && dayDiff <= -1) { + formatterWeek.format(Date(date)) + } else { + formatterDayMonth.format(Date(date)) + } + } + } catch (e: Exception) { + Log.e("LOC_ERR", e.toString()) + } + return "LOC_ERR" + } +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/radium/utils/time/SunDate.java b/app/src/main/java/io/github/chronosx88/radium/utils/time/SunDate.java new file mode 100644 index 0000000..bbd65fc --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/radium/utils/time/SunDate.java @@ -0,0 +1,152 @@ +/* + * This is the source code of Telegram for Android v. 5.x.x. + * It is licensed under GNU GPL v. 2 or later. + * You should have received a copy of the license in this archive (see LICENSE). + * + * Copyright Nikolai Kudashov, 2013-2018. + */ +package io.github.chronosx88.radium.utils.time; + +import java.util.Calendar; +import java.util.TimeZone; + +public class SunDate { + + private static final double DEGRAD = Math.PI / 180.0; + private static final double RADEG = 180.0 / Math.PI; + private static final double INV360 = 1.0 / 360.0; + + private static long days_since_2000_Jan_0(int y, int m, int d) { + return 367L * y - ((7 * (y + ((m + 9) / 12))) / 4) + ((275 * m) / 9) + d - 730530L; + } + + private static double revolution(double x) { + return x - 360.0 * Math.floor(x * INV360); + } + + private static double rev180(double x) { + return x - 360.0 * Math.floor(x * INV360 + 0.5); + } + + private static double GMST0(double d) { + return revolution((180.0 + 356.0470 + 282.9404) + (0.9856002585 + 4.70935E-5) * d); + } + + private static double sind(double x) { + return Math.sin(x * DEGRAD); + } + + private static double cosd(double x) { + return Math.cos(x * DEGRAD); + } + + private static double tand(double x) { + return Math.tan(x * DEGRAD); + } + + private static double acosd(double x) { + return RADEG * Math.acos(x); + } + + private static double atan2d(double y, double x) { + return RADEG * Math.atan2(y, x); + } + + private static void sunposAtDay(double p, double[] ot, double[] d) { + double S, a, V, l, k, i; + + S = revolution(356.0470 + 0.9856002585 * p); + l = 282.9404 + 4.70935E-5 * p; + a = 0.016709 - 1.151E-9 * p; + + V = a * RADEG * sind(S) * (1.0 + a * cosd(S)) + S; + k = cosd(V) - a; + + i = Math.sqrt(1.0 - a * a) * sind(V); + d[0] = Math.sqrt(k * k + i * i); + i = atan2d(i, k); + ot[0] = i + l; + if (ot[0] >= 360.0) { + ot[0] -= 360.0; + } + } + + private static void sun_RA_decAtDay(double d, double[] RA, double[] dec, double[] r) { + double[] lon = new double[1]; + double obl_ecl; + double xs, ys; + double xe, ye, ze; + + sunposAtDay(d, lon, r); + + xs = r[0] * cosd(lon[0]); + ys = r[0] * sind(lon[0]); + + obl_ecl = 23.4393 - 3.563E-7 * d; + + xe = xs; + ye = ys * cosd(obl_ecl); + ze = ys * sind(obl_ecl); + + RA[0] = atan2d(ye, xe); + dec[0] = atan2d(ze, Math.sqrt(xe * xe + ye * ye)); + } + + private static int sunRiseSetHelperForYear(int year, int month, int day, double lon, double lat, double altit, int upper_limb, double[] sun) { + double[] sRA = new double[1]; + double[] sdec = new double[1]; + double[] sr = new double[1]; + + double d, sradius, t, tsouth, sidtime; + int rc = 0; + d = days_since_2000_Jan_0(year, month, day) + 0.5 - lon / 360.0; + sidtime = revolution(GMST0(d) + 180.0 + lon); + sun_RA_decAtDay(d, sRA, sdec, sr); + tsouth = 12.0 - rev180(sidtime - sRA[0]) / 15.0; + sradius = 0.2666 / sr[0]; + if (upper_limb != 0) { + altit -= sradius; + } + + double cost; + cost = (sind(altit) - sind(lat) * sind(sdec[0])) / (cosd(lat) * cosd(sdec[0])); + if (cost >= 1.0) { + rc = -1; + t = 0.0; + } else if (cost <= -1.0) { + rc = +1; + t = 12.0; + } else { + t = acosd(cost) / 15.0; + } + sun[0] = tsouth - t; + sun[1] = tsouth + t; + + return rc; + } + + private static int sunRiseSetForYear(int year, int month, int day, double lon, double lat, double[] sun) { + return sunRiseSetHelperForYear(year, month, day, lon, lat, (-35.0 / 60.0), 1, sun); + } + + public static int[] calculateSunriseSunset(double lat, double lon) { + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(System.currentTimeMillis()); + double[] sun = new double[2]; + sunRiseSetForYear(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), lon, lat, sun); + int timeZoneOffset = TimeZone.getDefault().getOffset(System.currentTimeMillis()) / 1000 / 60; + int sunrise = (int) (sun[0] * 60) + timeZoneOffset; + int sunset = (int) (sun[1] * 60) + timeZoneOffset; + if (sunrise < 0) { + sunrise += 60 * 24; + } else if (sunrise > 60 * 24) { + sunrise -= 60 * 24; + } + if (sunset < 0) { + sunset += 60 * 24; + } else if (sunset > 60 * 24) { + sunset += 60 * 24; + } + return new int[] {sunrise, sunset}; + } +} \ No newline at end of file diff --git a/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_done_all_purple_24.xml b/app/src/main/res/drawable/ic_done_all_purple_24.xml new file mode 100644 index 0000000..a401016 --- /dev/null +++ b/app/src/main/res/drawable/ic_done_all_purple_24.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_done_purple_24.xml b/app/src/main/res/drawable/ic_done_purple_24.xml new file mode 100644 index 0000000..4e10389 --- /dev/null +++ b/app/src/main/res/drawable/ic_done_purple_24.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_home_24.xml b/app/src/main/res/drawable/ic_home_24.xml new file mode 100644 index 0000000..3a4c7da --- /dev/null +++ b/app/src/main/res/drawable/ic_home_24.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07d5da9 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_settings_24.xml b/app/src/main/res/drawable/ic_settings_24.xml new file mode 100644 index 0000000..41a82ed --- /dev/null +++ b/app/src/main/res/drawable/ic_settings_24.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_white_pen_24.xml b/app/src/main/res/drawable/ic_white_pen_24.xml new file mode 100644 index 0000000..faddfce --- /dev/null +++ b/app/src/main/res/drawable/ic_white_pen_24.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/side_nav_bar.xml b/app/src/main/res/drawable/side_nav_bar.xml new file mode 100644 index 0000000..6d81870 --- /dev/null +++ b/app/src/main/res/drawable/side_nav_bar.xml @@ -0,0 +1,9 @@ + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..01e2945 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,24 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/app_bar_main.xml b/app/src/main/res/layout/app_bar_main.xml new file mode 100644 index 0000000..7803d9d --- /dev/null +++ b/app/src/main/res/layout/app_bar_main.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/chat_list_item.xml b/app/src/main/res/layout/chat_list_item.xml new file mode 100644 index 0000000..71e0008 --- /dev/null +++ b/app/src/main/res/layout/chat_list_item.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/content_main.xml b/app/src/main/res/layout/content_main.xml new file mode 100644 index 0000000..12f3d18 --- /dev/null +++ b/app/src/main/res/layout/content_main.xml @@ -0,0 +1,16 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/nav_header_main.xml b/app/src/main/res/layout/nav_header_main.xml new file mode 100644 index 0000000..1bf27a3 --- /dev/null +++ b/app/src/main/res/layout/nav_header_main.xml @@ -0,0 +1,35 @@ + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/menu/activity_main_drawer.xml b/app/src/main/res/menu/activity_main_drawer.xml new file mode 100644 index 0000000..f18a0d0 --- /dev/null +++ b/app/src/main/res/menu/activity_main_drawer.xml @@ -0,0 +1,12 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..eca70cf --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..eca70cf --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..a571e60 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000..61da551 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..c41dd28 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000..db5080a Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..6dba46d Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000..da31a87 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..15ac681 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..b216f2d Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..f25a419 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..e96783c Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/values-night/themes.xml b/app/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..5b2bae6 --- /dev/null +++ b/app/src/main/res/values-night/themes.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/values-v21/themes.xml b/app/src/main/res/values-v21/themes.xml new file mode 100644 index 0000000..560939a --- /dev/null +++ b/app/src/main/res/values-v21/themes.xml @@ -0,0 +1,20 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/app/src/main/res/values/dimens.xml b/app/src/main/res/values/dimens.xml new file mode 100644 index 0000000..4ab4520 --- /dev/null +++ b/app/src/main/res/values/dimens.xml @@ -0,0 +1,8 @@ + + + 16dp + 16dp + 8dp + 176dp + 16dp + \ No newline at end of file diff --git a/app/src/main/res/values/drawables.xml b/app/src/main/res/values/drawables.xml new file mode 100644 index 0000000..c4e4cea --- /dev/null +++ b/app/src/main/res/values/drawables.xml @@ -0,0 +1,8 @@ + + @android:drawable/ic_menu_camera + @android:drawable/ic_menu_gallery + @android:drawable/ic_menu_slideshow + @android:drawable/ic_menu_manage + @android:drawable/ic_menu_share + @android:drawable/ic_menu_send + \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..977022a --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,19 @@ + + Radium + Open navigation drawer + Close navigation drawer + Some user + user@cadmium.org + Navigation header + Settings + + Home + Settings + + + EEE + HH:mm + h:mm a + MMM dd + dd.MM.yy + \ No newline at end of file diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..b142dc3 --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,25 @@ + + + + + + +