Move packages to com.moez.QKSMS

This commit is contained in:
Moez Bhatti
2018-06-20 14:29:07 -04:00
parent d8141737b3
commit a5f518042e
268 changed files with 1101 additions and 1116 deletions
@@ -0,0 +1,38 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
class GlideCompletionListener<T>(private val listener: () -> Unit) : RequestListener<T> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<T>?, isFirstResource: Boolean): Boolean {
listener()
return false
}
override fun onResourceReady(resource: T, model: Any?, target: Target<T>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
listener()
return false
}
}
@@ -0,0 +1,96 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common
import android.content.Context
import android.content.res.ColorStateList
import android.support.annotation.ArrayRes
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.moez.QKSMS.common.base.QkAdapter
import com.moez.QKSMS.common.base.QkViewHolder
import com.moez.QKSMS.common.util.Colors
import com.moez.QKSMS.common.util.extensions.resolveThemeColor
import com.moez.QKSMS.common.util.extensions.setVisible
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.menu_list_item.view.*
import javax.inject.Inject
data class MenuItem(val title: String, val actionId: Int)
class MenuItemAdapter @Inject constructor(private val context: Context, private val colors: Colors) : QkAdapter<MenuItem>() {
val menuItemClicks: Subject<Int> = PublishSubject.create()
private val disposables = CompositeDisposable()
var selectedItem: Int? = null
set(value) {
val old = data.map { it.actionId }.indexOfFirst { it == field }
val new = data.map { it.actionId }.indexOfFirst { it == value }
field = value
old.let { notifyItemChanged(it) }
new.let { notifyItemChanged(it) }
}
fun setData(@ArrayRes titles: Int, @ArrayRes values: Int = -1) {
val valueInts = if (values != -1) context.resources.getIntArray(values) else null
data = context.resources.getStringArray(titles)
.mapIndexed { index, title -> MenuItem(title, valueInts?.getOrNull(index) ?: index) }
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val view = layoutInflater.inflate(R.layout.menu_list_item, parent, false)
val states = arrayOf(
intArrayOf(android.R.attr.state_selected),
intArrayOf(-android.R.attr.state_selected))
val text = parent.context.resolveThemeColor(android.R.attr.textColorTertiary)
view.check.imageTintList = ColorStateList(states, intArrayOf(colors.theme().theme, text))
return QkViewHolder(view)
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val menuItem = getItem(position)
val view = holder.itemView
view.clicks().subscribe { menuItemClicks.onNext(menuItem.actionId) }
view.title.text = menuItem.title
view.check.isSelected = (menuItem.actionId == selectedItem)
view.check.setVisible(selectedItem != null)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
disposables.clear()
}
}
@@ -0,0 +1,240 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common
import android.app.Activity
import android.app.ActivityOptions
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.ContactsContract
import android.provider.Settings
import android.provider.Telephony
import android.view.View
import com.moez.QKSMS.BuildConfig
import com.moez.QKSMS.feature.blocked.BlockedActivity
import com.moez.QKSMS.feature.compose.ComposeActivity
import com.moez.QKSMS.feature.conversationinfo.ConversationInfoActivity
import com.moez.QKSMS.feature.gallery.GalleryActivity
import com.moez.QKSMS.feature.notificationprefs.NotificationPrefsActivity
import com.moez.QKSMS.feature.plus.PlusActivity
import com.moez.QKSMS.feature.settings.SettingsActivity
import com.moez.QKSMS.feature.settings.about.AboutActivity
import com.moez.QKSMS.feature.themepicker.ThemePickerActivity
import com.moez.QKSMS.manager.NotificationManager
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class Navigator @Inject constructor(private val context: Context, private val notificationManager: NotificationManager) {
private fun startActivity(intent: Intent) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
private fun startActivityExternal(intent: Intent) {
if (intent.resolveActivity(context.packageManager) != null) {
startActivity(intent)
} else {
startActivity(Intent.createChooser(intent, null))
}
}
fun showQksmsPlusActivity() {
val intent = Intent(context, PlusActivity::class.java)
startActivity(intent)
}
fun showDefaultSmsDialog() {
val intent = Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT)
if (Telephony.Sms.getDefaultSmsPackage(context) != context.packageName) {
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, context.packageName)
}
startActivity(intent)
}
fun showCompose(body: String? = null, images: List<Uri>? = null) {
val intent = Intent(context, ComposeActivity::class.java)
intent.putExtra(Intent.EXTRA_TEXT, body)
images?.takeIf { it.isNotEmpty() }?.let {
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(images))
}
startActivity(intent)
}
fun showConversation(threadId: Long, query: String? = null) {
val intent = Intent(context, ComposeActivity::class.java)
.putExtra("threadId", threadId)
.putExtra("query", query)
startActivity(intent)
}
fun showConversationInfo(threadId: Long) {
val intent = Intent(context, ConversationInfoActivity::class.java)
intent.putExtra("threadId", threadId)
startActivity(intent)
}
fun showMedia(partId: Long) {
val intent = Intent(context, GalleryActivity::class.java)
intent.putExtra("partId", partId)
startActivity(intent)
}
/**
* Shows the attachment full-screen
* The transitionName for the view should be the id of the image being displayed
*/
fun showImageAnimated(from: Activity, view: View) {
val intent = Intent(context, GalleryActivity::class.java)
intent.putExtra("partId", view.transitionName.toLong())
val options = ActivityOptions.makeSceneTransitionAnimation(from, view, view.transitionName)
from.startActivity(intent, options.toBundle())
}
fun showSettings() {
val intent = Intent(context, SettingsActivity::class.java)
startActivity(intent)
}
fun showAbout() {
val intent = Intent(context, AboutActivity::class.java)
startActivity(intent)
}
fun showDeveloper() {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/moezbhatti"))
startActivity(intent)
}
fun showSourceCode() {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/moezbhatti/qksms"))
startActivity(intent)
}
fun showChangelog() {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/moezbhatti/qksms/releases"))
startActivity(intent)
}
fun showLicense() {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/moezbhatti/qksms/blob/master/LICENSE"))
startActivity(intent)
}
fun showBlockedConversations() {
val intent = Intent(context, BlockedActivity::class.java)
startActivity(intent)
}
fun showThemePicker(threadId: Long = 0) {
val intent = Intent(context, ThemePickerActivity::class.java)
intent.putExtra("threadId", threadId)
startActivity(intent)
}
fun makePhoneCall(address: String) {
val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$address"))
startActivityExternal(intent)
}
fun showDonation() {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://bit.ly/QKSMSDonation"))
startActivity(intent)
}
fun showRating() {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=${context.packageName}"))
.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY
or Intent.FLAG_ACTIVITY_NEW_DOCUMENT
or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + context.packageName)))
}
}
/**
* Launch the Play Store and display the Should I Answer? listing
*/
fun showSia() {
val url = "https://play.google.com/store/apps/details?id=org.mistergroup.shouldianswerpersonal"
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(intent)
}
fun showSupport() {
val intent = Intent(Intent.ACTION_SENDTO)
intent.data = Uri.parse("mailto:")
intent.putExtra(Intent.EXTRA_EMAIL, arrayOf("team@qklabs.com"))
intent.putExtra(Intent.EXTRA_SUBJECT, "QKSMS Support")
intent.putExtra(Intent.EXTRA_TEXT, StringBuilder("\n\n")
.append("--- Please write your message above this line ---\n\n")
.append("Version: ${BuildConfig.VERSION_NAME}\n")
.append("Device: ${Build.BRAND} ${Build.MODEL}\n")
.append("SDK: ${Build.VERSION.SDK_INT}")
.toString())
startActivityExternal(intent)
}
fun addContact(address: String) {
val intent = Intent(Intent.ACTION_INSERT)
.setType(ContactsContract.Contacts.CONTENT_TYPE)
.putExtra(ContactsContract.Intents.Insert.PHONE, address)
startActivityExternal(intent)
}
fun saveVcard(uri: Uri) {
val intent = Intent(Intent.ACTION_VIEW)
.setDataAndType(uri, "text/x-vcard")
startActivityExternal(intent)
}
fun showNotificationSettings(threadId: Long = 0) {
val intent = Intent(context, NotificationPrefsActivity::class.java)
intent.putExtra("threadId", threadId)
startActivity(intent)
}
fun showNotificationChannel(threadId: Long = 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (threadId != 0L) {
notificationManager.createNotificationChannel(threadId)
}
val channelId = notificationManager.buildNotificationChannelId(threadId)
val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
intent.putExtra(Settings.EXTRA_CHANNEL_ID, channelId)
intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
startActivity(intent)
}
}
}
@@ -0,0 +1,109 @@
package com.moez.QKSMS.common
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
import android.app.Activity
import android.app.Application
import android.app.Service
import android.content.BroadcastReceiver
import android.support.text.emoji.EmojiCompat
import android.support.text.emoji.FontRequestEmojiCompatConfig
import android.support.v4.provider.FontRequest
import com.akaita.java.rxjava2debug.RxJava2Debug
import com.bugsnag.android.Bugsnag
import com.bugsnag.android.Configuration
import com.moez.QKSMS.BuildConfig
import com.moez.QKSMS.R
import com.moez.QKSMS.common.util.BugsnagTree
import com.moez.QKSMS.injection.AppComponentManager
import com.moez.QKSMS.injection.appComponent
import com.moez.QKSMS.manager.AnalyticsManager
import com.moez.QKSMS.migration.QkRealmMigration
import com.moez.QKSMS.util.NightModeManager
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasActivityInjector
import dagger.android.HasBroadcastReceiverInjector
import dagger.android.HasServiceInjector
import io.realm.Realm
import io.realm.RealmConfiguration
import timber.log.Timber
import javax.inject.Inject
class QKApplication : Application(), HasActivityInjector, HasBroadcastReceiverInjector, HasServiceInjector {
/**
* Inject this so that it is forced to initialize
*/
@Suppress("unused")
@Inject lateinit var analyticsManager: AnalyticsManager
@Inject lateinit var dispatchingActivityInjector: DispatchingAndroidInjector<Activity>
@Inject lateinit var dispatchingBroadcastReceiverInjector: DispatchingAndroidInjector<BroadcastReceiver>
@Inject lateinit var dispatchingServiceInjector: DispatchingAndroidInjector<Service>
@Inject lateinit var nightModeManager: NightModeManager
private val packages = arrayOf("com.moez.QKSMS")
override fun onCreate() {
super.onCreate()
Bugsnag.init(this, Configuration(BuildConfig.BUGSNAG_API_KEY).apply {
appVersion = BuildConfig.VERSION_NAME
projectPackages = packages
})
RxJava2Debug.enableRxJava2AssemblyTracking(packages)
Realm.init(this)
Realm.setDefaultConfiguration(RealmConfiguration.Builder()
.compactOnLaunch()
.migration(QkRealmMigration())
.schemaVersion(QkRealmMigration.SCHEMA_VERSION)
.build())
AppComponentManager.init(this)
appComponent.inject(this)
nightModeManager.updateCurrentTheme()
val fontRequest = FontRequest(
"com.google.android.gms.fonts",
"com.google.android.gms",
"Noto Color Emoji Compat",
R.array.com_google_android_gms_fonts_certs)
EmojiCompat.init(FontRequestEmojiCompatConfig(this, fontRequest))
Timber.plant(Timber.DebugTree(), BugsnagTree())
}
override fun activityInjector(): AndroidInjector<Activity> {
return dispatchingActivityInjector
}
override fun broadcastReceiverInjector(): AndroidInjector<BroadcastReceiver> {
return dispatchingBroadcastReceiverInjector
}
override fun serviceInjector(): AndroidInjector<Service> {
return dispatchingServiceInjector
}
}
@@ -0,0 +1,50 @@
package com.moez.QKSMS.common
import android.app.Activity
import android.content.Context
import android.support.annotation.StringRes
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.moez.QKSMS.common.util.extensions.dpToPx
import com.moez.QKSMS.common.util.extensions.setPadding
import com.moez.QKSMS.injection.appComponent
import javax.inject.Inject
/**
* Wrapper around AlertDialog which makes it easier to display lists that use our UI
*/
class QkDialog @Inject constructor(private val context: Context, val adapter: MenuItemAdapter) {
var title: String? = null
init {
appComponent.inject(this)
}
fun show(activity: Activity) {
val recyclerView = RecyclerView(activity)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = adapter
recyclerView.setPadding(top = 8.dpToPx(context), bottom = 8.dpToPx(context))
val dialog = AlertDialog.Builder(activity)
.setTitle(title)
.setView(recyclerView)
.create()
val clicks = adapter.menuItemClicks
.subscribe { dialog.dismiss() }
dialog.setOnDismissListener {
clicks.dispose()
}
dialog.show()
}
fun setTitle(@StringRes title: Int) {
this.title = context.getString(title)
}
}
@@ -0,0 +1,12 @@
package com.moez.QKSMS.common
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import javax.inject.Inject
import javax.inject.Provider
class ViewModelFactory @Inject constructor(private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T = viewModels[modelClass]?.get() as T
}
@@ -0,0 +1,81 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.base
import android.support.annotation.CallSuper
import android.support.v7.widget.RecyclerView
import io.reactivex.Flowable
import io.reactivex.disposables.Disposable
/**
* Base RecyclerView.Adapter that provides some convenience when creating a new Adapter, such as
* data list handing and item animations
*/
abstract class FlowableAdapter<T> : QkAdapter<T>() {
var flowable: Flowable<List<T>>? = null
set(value) {
if (field === value) return
field = value
// Stop listening for updates on the old flowable
dispose()
// If we're attached to any RecyclerViews, then subscribe to updates
if (recyclerViews.isNotEmpty()) {
subscribe()
}
}
private val recyclerViews = ArrayList<RecyclerView>()
private var disposable: Disposable? = null
@CallSuper
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
// If this is the first RecyclerView to be attached, then start listening to updates
if (recyclerViews.isEmpty() || disposable == null) {
subscribe()
}
recyclerViews.add(recyclerView)
}
@CallSuper
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
recyclerViews.remove(recyclerView)
// If no more RecyclerViews are attached, stop listening to updates
if (recyclerViews.isEmpty()) {
dispose()
}
}
private fun subscribe() {
disposable = flowable?.subscribe {
data = it
}
}
private fun dispose() {
disposable?.dispose()
}
}
@@ -0,0 +1,77 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.base
import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.toolbar.*
abstract class QkActivity : AppCompatActivity() {
protected val menu: Subject<Menu> = BehaviorSubject.create()
@SuppressLint("InlinedApi")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
onNewIntent(intent)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun setContentView(layoutResID: Int) {
super.setContentView(layoutResID)
setSupportActionBar(toolbar)
title = title // The title may have been set before layout inflation
}
override fun setTitle(titleId: Int) {
title = getString(titleId)
}
override fun setTitle(title: CharSequence?) {
super.setTitle(title)
toolbarTitle?.text = title
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val result = super.onCreateOptionsMenu(menu)
if (menu != null) {
this.menu.onNext(menu)
}
return result
}
protected open fun showBackButton(show: Boolean) {
supportActionBar?.setDisplayHomeAsUpEnabled(show)
}
}
@@ -0,0 +1,124 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.base
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import android.view.View
import com.moez.QKSMS.common.util.extensions.setVisible
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
/**
* Base RecyclerView.Adapter that provides some convenience when creating a new Adapter, such as
* data list handing and item animations
*/
abstract class QkAdapter<T> : RecyclerView.Adapter<QkViewHolder>() {
var data: List<T> = ArrayList()
set(value) {
if (field === value) return
val diff = DiffUtil.calculateDiff(getDiffUtilCallback(field, value))
field = value
diff.dispatchUpdatesTo(this)
onDatasetChanged()
emptyView?.setVisible(value.isEmpty())
}
/**
* This view can be set, and the adapter will automatically control the visibility of this view
* based on the data
*/
var emptyView: View? = null
set(value) {
field = value
value?.setVisible(false)
}
val selectionChanges: Subject<List<Long>> = BehaviorSubject.create()
private val selection = mutableListOf<Long>()
/**
* Toggles the selected state for a particular view
*
* If we are currently in selection mode (we have an active selection), then the state will
* toggle. If we are not in selection mode, then we will only toggle if [force]
*/
protected fun toggleSelection(id: Long, force: Boolean = true): Boolean {
if (!force && selection.isEmpty()) return false
when (selection.contains(id)) {
true -> selection.remove(id)
false -> selection.add(id)
}
selectionChanges.onNext(selection)
return true
}
protected fun isSelected(id: Long): Boolean {
return selection.contains(id)
}
fun clearSelection() {
selection.clear()
selectionChanges.onNext(selection)
notifyDataSetChanged()
}
fun getItem(position: Int): T {
return data[position]
}
override fun getItemCount(): Int {
return data.size
}
open fun onDatasetChanged() {}
/**
* Allows the adapter implementation to provide a custom DiffUtil.Callback
* If not, then the abstract implementation will be used
*/
private fun getDiffUtilCallback(oldData: List<T>, newData: List<T>): DiffUtil.Callback {
return object : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
areItemsTheSame(oldData[oldItemPosition], newData[newItemPosition])
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
areContentsTheSame(oldData[oldItemPosition], newData[newItemPosition])
override fun getOldListSize() = oldData.size
override fun getNewListSize() = newData.size
}
}
protected open fun areItemsTheSame(old: T, new: T): Boolean {
return old == new
}
protected open fun areContentsTheSame(old: T, new: T): Boolean {
return old == new
}
}
@@ -0,0 +1,93 @@
package com.moez.QKSMS.common.base
import android.support.v7.widget.RecyclerView
import android.view.View
import com.moez.QKSMS.common.util.extensions.setVisible
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import io.realm.OrderedRealmCollection
import io.realm.RealmList
import io.realm.RealmModel
import io.realm.RealmRecyclerViewAdapter
import io.realm.RealmResults
abstract class QkRealmAdapter<T : RealmModel> : RealmRecyclerViewAdapter<T, QkViewHolder>(null, true) {
/**
* This view can be set, and the adapter will automatically control the visibility of this view
* based on the data
*/
var emptyView: View? = null
private val emptyListener: (OrderedRealmCollection<T>) -> Unit = { data ->
emptyView?.setVisible(data.isLoaded && data.isEmpty())
}
val selectionChanges: Subject<List<Long>> = BehaviorSubject.create()
private val selection = mutableListOf<Long>()
/**
* Toggles the selected state for a particular view
*
* If we are currently in selection mode (we have an active selection), then the state will
* toggle. If we are not in selection mode, then we will only toggle if [force]
*/
protected fun toggleSelection(id: Long, force: Boolean = true): Boolean {
if (!force && selection.isEmpty()) return false
when (selection.contains(id)) {
true -> selection.remove(id)
false -> selection.add(id)
}
selectionChanges.onNext(selection)
return true
}
protected fun isSelected(id: Long): Boolean {
return selection.contains(id)
}
fun clearSelection() {
selection.clear()
selectionChanges.onNext(selection)
notifyDataSetChanged()
}
override fun updateData(data: OrderedRealmCollection<T>?) {
if (getData() === data) return
removeListener(getData())
addListener(data)
data?.run(emptyListener)
super.updateData(data)
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
addListener(data)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
removeListener(data)
}
private fun addListener(data: OrderedRealmCollection<T>?) {
when (data) {
is RealmResults<T> -> data.addChangeListener(emptyListener)
is RealmList<T> -> data.addChangeListener(emptyListener)
}
}
private fun removeListener(data: OrderedRealmCollection<T>?) {
when (data) {
is RealmResults<T> -> data.removeChangeListener(emptyListener)
is RealmList<T> -> data.removeChangeListener(emptyListener)
}
}
}
@@ -0,0 +1,141 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.base
import android.annotation.SuppressLint
import android.app.ActivityManager
import android.arch.lifecycle.Lifecycle
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.view.View
import com.moez.QKSMS.R
import com.moez.QKSMS.common.util.Colors
import com.moez.QKSMS.common.util.extensions.resolveThemeColor
import com.moez.QKSMS.util.Preferences
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import io.reactivex.Observable
import io.reactivex.rxkotlin.Observables
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.toolbar.*
import javax.inject.Inject
/**
* Base activity that automatically applies any necessary theme theme settings and colors
*
* In most cases, this should be used instead of the base QkActivity, except for when
* an activity does not depend on the theme
*/
abstract class QkThemedActivity : QkActivity() {
@Inject lateinit var colors: Colors
@Inject lateinit var prefs: Preferences
/**
* In case the activity should be themed for a specific conversation, the selected conversation
* can be changed by pushing the threadId to this subject
*/
protected val threadId: Subject<Long> = BehaviorSubject.createDefault(0)
/**
* Switch the theme if the threadId changes
*/
protected val theme = threadId
.distinctUntilChanged()
.switchMap { threadId -> colors.themeObservable(threadId) }
@SuppressLint("InlinedApi")
override fun onCreate(savedInstanceState: Bundle?) {
val night = prefs.night.get()
val black = prefs.black.get()
setTheme(getActivityThemeRes(night, black))
super.onCreate(savedInstanceState)
// When certain preferences change, we need to recreate the activity
Observable.merge(
listOf(prefs.night, prefs.black, prefs.textSize, prefs.systemFont).map { it.asObservable().skip(1) })
.autoDisposable(scope())
.subscribe { recreate() }
// Set the color for the status bar icons
// If night mode, or no dark icons supported, use light icons
// If night mode and only dark status icons supported, use dark status icons
// If night mode and all dark icons supported, use all dark icons
window.decorView.systemUiVisibility = when {
night || Build.VERSION.SDK_INT < Build.VERSION_CODES.M -> 0
Build.VERSION.SDK_INT < Build.VERSION_CODES.O -> View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
else -> View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
}
// Some devices don't let you modify android.R.attr.navigationBarColor
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
window.navigationBarColor = resolveThemeColor(android.R.attr.windowBackground)
}
// Set the color for the overflow and navigation icon
val textTertiary = resolveThemeColor(android.R.attr.textColorTertiary)
toolbar?.overflowIcon = toolbar?.overflowIcon?.apply { setTint(textTertiary) }
toolbar?.navigationIcon = toolbar?.navigationIcon?.apply { setTint(textTertiary) }
// Set the color for the recent apps title
val toolbarColor = resolveThemeColor(R.attr.colorPrimary)
val icon = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
val taskDesc = ActivityManager.TaskDescription(getString(R.string.app_name), icon, toolbarColor)
setTaskDescription(taskDesc)
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
// Update the colours of the menu items
Observables.combineLatest(menu, theme, { menu, theme ->
val text = resolveThemeColor(android.R.attr.textColorSecondary)
(0 until menu.size())
.map { position -> menu.getItem(position) }
.forEach { menuItem ->
menuItem?.icon?.run {
setTint(when (menuItem.itemId) {
in getColoredMenuItems() -> theme.theme
else -> text
})
menuItem.icon = this
}
}
}).autoDisposable(scope(Lifecycle.Event.ON_DESTROY)).subscribe()
}
open fun getColoredMenuItems(): List<Int> {
return listOf()
}
/**
* This can be overridden in case an activity does not want to use the default themes
*/
open fun getActivityThemeRes(night: Boolean, black: Boolean) = when {
night && black -> R.style.AppThemeBlack
night && !black -> R.style.AppThemeDark
else -> R.style.AppThemeLight
}
}
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.base
import android.arch.lifecycle.LifecycleOwner
interface QkView<in State> : LifecycleOwner {
fun render(state: State)
}
@@ -0,0 +1,24 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.base
import android.support.v7.widget.RecyclerView
import android.view.View
class QkViewHolder(view: View) : RecyclerView.ViewHolder(view)
@@ -0,0 +1,52 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.base
import android.arch.lifecycle.ViewModel
import android.support.annotation.CallSuper
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.BehaviorSubject
abstract class QkViewModel<in View : QkView<State>, State>(initialState: State) : ViewModel() {
protected val state: BehaviorSubject<State> = BehaviorSubject.createDefault(initialState)
protected val disposables = CompositeDisposable()
@CallSuper
open fun bindView(view: View) {
state
.observeOn(AndroidSchedulers.mainThread())
.autoDisposable(view.scope())
.subscribe { view.render(it) }
}
protected fun newState(reducer: State.() -> State) {
state.value?.let { state.onNext(reducer(it)) }
}
override fun onCleared() {
super.onCleared()
disposables.dispose()
}
}
@@ -0,0 +1,129 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util
import android.app.Activity
import android.content.Context
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClient.BillingResponse
import com.android.billingclient.api.BillingClient.SkuType
import com.android.billingclient.api.BillingClientStateListener
import com.android.billingclient.api.BillingFlowParams
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.PurchasesUpdatedListener
import com.android.billingclient.api.SkuDetails
import com.android.billingclient.api.SkuDetailsParams
import com.moez.QKSMS.BuildConfig
import com.moez.QKSMS.manager.AnalyticsManager
import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import javax.inject.Inject
class BillingManager @Inject constructor(
context: Context,
private val analyticsManager: AnalyticsManager
) : PurchasesUpdatedListener {
companion object {
const val SKU_PLUS = "remove_ads"
const val SKU_PLUS_DONATE = "qksms_plus_donate"
}
val products: Observable<List<SkuDetails>> = BehaviorSubject.create()
val upgradeStatus: Observable<Boolean>
private val skus = listOf(SKU_PLUS, SKU_PLUS_DONATE)
private val purchaseListObservable = BehaviorSubject.createDefault<List<Purchase>>(listOf())
private val billingClient: BillingClient = BillingClient.newBuilder(context).setListener(this).build()
private var isServiceConnected = false
init {
startServiceConnection {
queryPurchases()
querySkuDetailsAsync()
}
upgradeStatus = when (BuildConfig.FLAVOR) {
"noAnalytics" -> BehaviorSubject.createDefault(true)
else -> purchaseListObservable
.map { purchases -> purchases.any { it.sku == SKU_PLUS } || purchases.any { it.sku == SKU_PLUS_DONATE } }
.doOnNext { upgraded -> analyticsManager.setUserProperty("Upgraded", upgraded) }
}
}
private fun queryPurchases() {
executeServiceRequest {
val purchasesResult = billingClient.queryPurchases(SkuType.INAPP)
// Handle purchase result
purchaseListObservable.onNext(purchasesResult.purchasesList.orEmpty())
}
}
private fun startServiceConnection(onSuccess: () -> Unit) {
billingClient.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(@BillingResponse billingResponseCode: Int) {
if (billingResponseCode == BillingResponse.OK) {
isServiceConnected = true
onSuccess()
}
}
override fun onBillingServiceDisconnected() {
isServiceConnected = false
}
})
}
private fun querySkuDetailsAsync() {
executeServiceRequest {
val subParams = SkuDetailsParams.newBuilder().setSkusList(skus).setType(BillingClient.SkuType.INAPP)
billingClient.querySkuDetailsAsync(subParams.build()) { responseCode, skuDetailsList ->
if (responseCode == BillingResponse.OK) {
(products as Subject).onNext(skuDetailsList)
}
}
}
}
fun initiatePurchaseFlow(activity: Activity, sku: String) {
executeServiceRequest {
val params = BillingFlowParams.newBuilder().setSku(sku).setType(SkuType.INAPP)
billingClient.launchBillingFlow(activity, params.build())
}
}
private fun executeServiceRequest(runnable: () -> Unit) {
when (isServiceConnected) {
true -> runnable()
false -> startServiceConnection(runnable)
}
}
override fun onPurchasesUpdated(resultCode: Int, purchases: List<Purchase>?) {
if (resultCode == BillingResponse.OK) {
purchaseListObservable.onNext(purchases.orEmpty())
}
}
}
@@ -0,0 +1,23 @@
package com.moez.QKSMS.common.util
import android.util.Log
import com.bugsnag.android.Bugsnag
import com.bugsnag.android.Severity
import timber.log.Timber
/**
* If an exception is logged with the [Log.WARN] or [Log.ERROR] priority, the exception will be
* sent to Bugsnag
*/
class BugsnagTree : Timber.Tree() {
override fun isLoggable(tag: String?, priority: Int): Boolean {
return priority == Log.WARN || priority == Log.ERROR
}
override fun log(priority: Int, tag: String?, message: String?, throwable: Throwable?) {
val severity = if (priority == Log.ERROR) Severity.ERROR else Severity.WARNING
throwable?.run { Bugsnag.notify(this, severity) }
}
}
@@ -0,0 +1,33 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
object ClipboardUtils {
fun copy(context: Context, string: String) {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("SMS", string)
clipboard.primaryClip = clip
}
}
@@ -0,0 +1,113 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util
import android.content.Context
import android.graphics.Color
import com.moez.QKSMS.R
import com.moez.QKSMS.common.util.extensions.getColorCompat
import com.moez.QKSMS.util.Preferences
import io.reactivex.Observable
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class Colors @Inject constructor(private val context: Context, private val prefs: Preferences) {
data class Theme(val theme: Int, private val colors: Colors) {
val highlight by lazy { colors.highlightColorForTheme(theme) }
val textPrimary by lazy { colors.textPrimaryOnThemeForColor(theme) }
val textSecondary by lazy { colors.textSecondaryOnThemeForColor(theme) }
val textTertiary by lazy { colors.textTertiaryOnThemeForColor(theme) }
}
val materialColors = listOf(
listOf(0xffffebee, 0xffffcdd2, 0xffef9a9a, 0xffe57373, 0xffef5350, 0xfff44336, 0xffe53935, 0xffd32f2f, 0xffc62828, 0xffb71c1c),
listOf(0xffFCE4EC, 0xffF8BBD0, 0xffF48FB1, 0xffF06292, 0xffEC407A, 0xffE91E63, 0xffD81B60, 0xffC2185B, 0xffAD1457, 0xff880E4F),
listOf(0xffF3E5F5, 0xffE1BEE7, 0xffCE93D8, 0xffBA68C8, 0xffAB47BC, 0xff9C27B0, 0xff8E24AA, 0xff7B1FA2, 0xff6A1B9A, 0xff4A148C),
listOf(0xffEDE7F6, 0xffD1C4E9, 0xffB39DDB, 0xff9575CD, 0xff7E57C2, 0xff673AB7, 0xff5E35B1, 0xff512DA8, 0xff4527A0, 0xff311B92),
listOf(0xffE8EAF6, 0xffC5CAE9, 0xff9FA8DA, 0xff7986CB, 0xff5C6BC0, 0xff3F51B5, 0xff3949AB, 0xff303F9F, 0xff283593, 0xff1A237E),
listOf(0xffE3F2FD, 0xffBBDEFB, 0xff90CAF9, 0xff64B5F6, 0xff42A5F5, 0xff2196F3, 0xff1E88E5, 0xff1976D2, 0xff1565C0, 0xff0D47A1),
listOf(0xffE1F5FE, 0xffB3E5FC, 0xff81D4FA, 0xff4FC3F7, 0xff29B6F6, 0xff03A9F4, 0xff039BE5, 0xff0288D1, 0xff0277BD, 0xff01579B),
listOf(0xffE0F7FA, 0xffB2EBF2, 0xff80DEEA, 0xff4DD0E1, 0xff26C6DA, 0xff00BCD4, 0xff00ACC1, 0xff0097A7, 0xff00838F, 0xff006064),
listOf(0xffE0F2F1, 0xffB2DFDB, 0xff80CBC4, 0xff4DB6AC, 0xff26A69A, 0xff009688, 0xff00897B, 0xff00796B, 0xff00695C, 0xff004D40),
listOf(0xffE8F5E9, 0xffC8E6C9, 0xffA5D6A7, 0xff81C784, 0xff66BB6A, 0xff4CAF50, 0xff43A047, 0xff388E3C, 0xff2E7D32, 0xff1B5E20),
listOf(0xffF1F8E9, 0xffDCEDC8, 0xffC5E1A5, 0xffAED581, 0xff9CCC65, 0xff8BC34A, 0xff7CB342, 0xff689F38, 0xff558B2F, 0xff33691E),
listOf(0xffF9FBE7, 0xffF0F4C3, 0xffE6EE9C, 0xffDCE775, 0xffD4E157, 0xffCDDC39, 0xffC0CA33, 0xffAFB42B, 0xff9E9D24, 0xff827717),
listOf(0xffFFFDE7, 0xffFFF9C4, 0xffFFF59D, 0xffFFF176, 0xffFFEE58, 0xffFFEB3B, 0xffFDD835, 0xffFBC02D, 0xffF9A825, 0xffF57F17),
listOf(0xffFFF8E1, 0xffFFECB3, 0xffFFE082, 0xffFFD54F, 0xffFFCA28, 0xffFFC107, 0xffFFB300, 0xffFFA000, 0xffFF8F00, 0xffFF6F00),
listOf(0xffFFF3E0, 0xffFFE0B2, 0xffFFCC80, 0xffFFB74D, 0xffFFA726, 0xffFF9800, 0xffFB8C00, 0xffF57C00, 0xffEF6C00, 0xffE65100),
listOf(0xffFBE9E7, 0xffFFCCBC, 0xffFFAB91, 0xffFF8A65, 0xffFF7043, 0xffFF5722, 0xffF4511E, 0xffE64A19, 0xffD84315, 0xffBF360C),
listOf(0xffEFEBE9, 0xffD7CCC8, 0xffBCAAA4, 0xffA1887F, 0xff8D6E63, 0xff795548, 0xff6D4C41, 0xff5D4037, 0xff4E342E, 0xff3E2723),
listOf(0xffFAFAFA, 0xffF5F5F5, 0xffEEEEEE, 0xffE0E0E0, 0xffBDBDBD, 0xff9E9E9E, 0xff757575, 0xff616161, 0xff424242, 0xff212121),
listOf(0xffECEFF1, 0xffCFD8DC, 0xffB0BEC5, 0xff90A4AE, 0xff78909C, 0xff607D8B, 0xff546E7A, 0xff455A64, 0xff37474F, 0xff263238))
.map { it.map { it.toInt() } }
private val minimumContrastRatio = 2
// Cache these values so they don't need to be recalculated
private val primaryTextLuminance = measureLuminance(context.getColorCompat(R.color.textPrimaryDark))
private val secondaryTextLuminance = measureLuminance(context.getColorCompat(R.color.textSecondaryDark))
private val tertiaryTextLuminance = measureLuminance(context.getColorCompat(R.color.textTertiaryDark))
fun theme(threadId: Long = 0): Theme = Theme(prefs.theme(threadId).get(), this)
fun themeObservable(threadId: Long = 0): Observable<Theme> {
return prefs.theme(threadId).asObservable()
.map { color -> Theme(color, this) }
}
fun highlightColorForTheme(theme: Int): Int = FloatArray(3)
.apply { Color.colorToHSV(theme, this) }
.let { hsv -> hsv.apply { set(2, 0.75f) } } // 75% value
.let { hsv -> Color.HSVToColor(85, hsv) } // 33% alpha
fun textPrimaryOnThemeForColor(color: Int): Int = color
.let { theme -> measureLuminance(theme) }
.let { themeLuminance -> primaryTextLuminance / themeLuminance }
.let { contrastRatio -> contrastRatio < minimumContrastRatio }
.let { contrastRatio -> if (contrastRatio) R.color.textPrimary else R.color.textPrimaryDark }
.let { res -> context.getColorCompat(res) }
fun textSecondaryOnThemeForColor(color: Int): Int = color
.let { theme -> measureLuminance(theme) }
.let { themeLuminance -> secondaryTextLuminance / themeLuminance }
.let { contrastRatio -> contrastRatio < minimumContrastRatio }
.let { contrastRatio -> if (contrastRatio) R.color.textSecondary else R.color.textSecondaryDark }
.let { res -> context.getColorCompat(res) }
fun textTertiaryOnThemeForColor(color: Int): Int = color
.let { theme -> measureLuminance(theme) }
.let { themeLuminance -> tertiaryTextLuminance / themeLuminance }
.let { contrastRatio -> contrastRatio < minimumContrastRatio }
.let { contrastRatio -> if (contrastRatio) R.color.textTertiary else R.color.textTertiaryDark }
.let { res -> context.getColorCompat(res) }
/**
* Measures the luminance value of a color to be able to measure the contrast ratio between two materialColors
* Based on https://stackoverflow.com/a/9733420
*/
private fun measureLuminance(color: Int): Double {
val array = intArrayOf(Color.red(color), Color.green(color), Color.blue(color))
.map { if (it < 0.03928) it / 12.92 else Math.pow((it + 0.055) / 1.055, 2.4) }
return 0.2126 * array[0] + 0.7152 * array[1] + 0.0722 * array[2] + 0.05
}
}
@@ -0,0 +1,88 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util
import android.content.Context
import android.provider.ContactsContract
import android.telephony.PhoneNumberUtils
import com.bumptech.glide.Priority
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.Key
import com.bumptech.glide.load.Options
import com.bumptech.glide.load.data.DataFetcher
import com.bumptech.glide.load.model.ModelLoader
import com.bumptech.glide.load.model.ModelLoaderFactory
import com.bumptech.glide.load.model.MultiModelLoaderFactory
import com.moez.QKSMS.injection.appComponent
import com.moez.QKSMS.repository.ContactRepository
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.io.InputStream
import java.security.MessageDigest
import javax.inject.Inject
class ContactImageLoader(val context: Context) : ModelLoader<String, InputStream> {
override fun handles(model: String?): Boolean {
return PhoneNumberUtils.isGlobalPhoneNumber(model)
}
override fun buildLoadData(model: String, width: Int, height: Int, options: Options?): ModelLoader.LoadData<InputStream> {
return ModelLoader.LoadData(ContactImageKey(model), ContactImageFetcher(context, model))
}
class Factory(val context: Context) : ModelLoaderFactory<String, InputStream> {
override fun build(multiFactory: MultiModelLoaderFactory) = ContactImageLoader(context)
override fun teardown() {} // nothing to do here
}
class ContactImageKey(private val address: String) : Key {
override fun updateDiskCacheKey(digest: MessageDigest) = digest.update(address.toByteArray())
}
class ContactImageFetcher(private val context: Context, private val address: String) : DataFetcher<InputStream> {
@Inject lateinit var contactRepo: ContactRepository
private var loadPhotoDisposable: Disposable? = null
init {
appComponent.inject(this)
}
override fun cleanup() {}
override fun getDataClass() = InputStream::class.java
override fun getDataSource() = DataSource.LOCAL
override fun loadData(priority: Priority?, callback: DataFetcher.DataCallback<in InputStream>) {
loadPhotoDisposable = contactRepo.findContactUri(address)
.map { uri -> ContactsContract.Contacts.openContactPhotoInputStream(context.contentResolver, uri) }
.subscribeOn(Schedulers.io())
.subscribe(
{ inputStream -> callback.onDataReady(inputStream) },
{ error -> callback.onLoadFailed(Exception(error)) })
}
override fun cancel() {
loadPhotoDisposable?.dispose()
}
}
}
@@ -0,0 +1,78 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util
import android.content.Context
import android.text.format.DateFormat
import com.moez.QKSMS.common.util.extensions.isSameDay
import com.moez.QKSMS.common.util.extensions.isSameWeek
import com.moez.QKSMS.common.util.extensions.isSameYear
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DateFormatter @Inject constructor(val context: Context) {
/**
* Replace 12 hour format with 24 hour format if necessary
*/
private fun getFormatter(pattern: String): SimpleDateFormat {
val isUsing24HourTime = DateFormat.is24HourFormat(context)
return if (isUsing24HourTime) SimpleDateFormat(pattern.replace("h", "HH").replace(" a".toRegex(), ""), Locale.getDefault())
else SimpleDateFormat(pattern, Locale.getDefault())
}
fun getDetailedTimestamp(date: Long): String {
return getFormatter("M/d/y, h:mm:ss a").format(date)
}
fun getTimestamp(date: Long): String {
return getFormatter("h:mm a").format(date)
}
fun getMessageTimestamp(date: Long): String {
val now = Calendar.getInstance()
val then = Calendar.getInstance()
then.timeInMillis = date
return when {
now.isSameDay(then) -> getFormatter("h:mm a")
now.isSameWeek(then) -> getFormatter("E h:mm a")
now.isSameYear(then) -> getFormatter("MMM d, h:mm a")
else -> getFormatter("MMM d yyyy, h:mm a")
}.format(date)
}
fun getConversationTimestamp(date: Long): String {
val now = Calendar.getInstance()
val then = Calendar.getInstance()
then.timeInMillis = date
return when {
now.isSameDay(then) -> getFormatter("h:mm a")
now.isSameWeek(then) -> getFormatter("E")
now.isSameYear(then) -> getFormatter("MMM d")
else -> getFormatter("d/MM/yy")
}.format(date)
}
}
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util
import android.content.Context
import android.graphics.Typeface
import android.support.v4.content.res.ResourcesCompat
import com.moez.QKSMS.R
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class FontProvider @Inject constructor(context: Context) {
private var lato: Typeface? = null
private val pendingCallbacks = ArrayList<(Typeface) -> Unit>()
init {
ResourcesCompat.getFont(context, R.font.lato, object : ResourcesCompat.FontCallback() {
override fun onFontRetrievalFailed(reason: Int) {
Timber.w("Font retrieval failed: $reason")
}
override fun onFontRetrieved(typeface: Typeface) {
lato = typeface
pendingCallbacks.forEach { lato?.run(it) }
pendingCallbacks.clear()
}
}, null)
}
fun getLato(callback: (Typeface) -> Unit) {
lato?.run(callback) ?: pendingCallbacks.add(callback)
}
}
@@ -0,0 +1,41 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util
import android.content.Context
import android.util.Log
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.module.AppGlideModule
import java.io.InputStream
@GlideModule
class GlideAppModule : AppGlideModule() {
override fun applyOptions(context: Context, builder: GlideBuilder) {
builder.setLogLevel(Log.ERROR)
}
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
registry.append(String::class.java, InputStream::class.java, ContactImageLoader.Factory(context))
}
}
@@ -0,0 +1,42 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util
import android.arch.lifecycle.LiveData
import io.realm.RealmChangeListener
import io.realm.RealmModel
import io.realm.RealmResults
class LiveRealmData<T : RealmModel>(private val results: RealmResults<T>) : LiveData<RealmResults<T>>() {
private val listener: RealmChangeListener<RealmResults<T>> = RealmChangeListener { results ->
value = results
}
override fun onActive() {
super.onActive()
results.addChangeListener(listener)
}
override fun onInactive() {
super.onInactive()
results.removeChangeListener(listener)
}
}
@@ -0,0 +1,87 @@
package com.moez.QKSMS.common.util
import android.content.Context
import com.google.android.mms.pdu_alt.EncodedStringValue
import com.google.android.mms.pdu_alt.MultimediaMessagePdu
import com.google.android.mms.pdu_alt.PduPersister
import com.moez.QKSMS.R
import com.moez.QKSMS.model.Message
import com.moez.QKSMS.util.tryOrNull
import javax.inject.Inject
class MessageDetailsFormatter @Inject constructor(
private val context: Context,
private val dateFormatter: DateFormatter
) {
fun format(message: Message): String {
val builder = StringBuilder()
message.type
.takeIf { it.isNotBlank() }
?.toUpperCase()
?.let { context.getString(R.string.compose_details_type, it) }
?.let(builder::appendln)
if (message.isSms()) {
message.address
.takeIf { it.isNotBlank() && !message.isMe() }
?.let { context.getString(R.string.compose_details_from, it) }
?.let(builder::appendln)
message.address
.takeIf { it.isNotBlank() && message.isMe() }
?.let { context.getString(R.string.compose_details_to, it) }
?.let(builder::appendln)
} else {
val pdu = tryOrNull {
PduPersister.getPduPersister(context)
.load(message.getUri())
as MultimediaMessagePdu
}
pdu?.from?.string
?.takeIf { it.isNotBlank() }
?.let { context.getString(R.string.compose_details_from, it) }
?.let(builder::appendln)
pdu?.to
?.let(EncodedStringValue::concat)
?.takeIf { it.isNotBlank() }
?.let { context.getString(R.string.compose_details_to, it) }
?.let(builder::appendln)
}
message.date
.takeIf { it > 0 && message.isMe() }
?.let(dateFormatter::getDetailedTimestamp)
?.let { context.getString(R.string.compose_details_sent, it) }
?.let(builder::appendln)
message.dateSent
.takeIf { it > 0 && !message.isMe() }
?.let(dateFormatter::getDetailedTimestamp)
?.let { context.getString(R.string.compose_details_sent, it) }
?.let(builder::appendln)
message.date
.takeIf { it > 0 && !message.isMe() }
?.let(dateFormatter::getDetailedTimestamp)
?.let { context.getString(R.string.compose_details_received, it) }
?.let(builder::appendln)
message.dateSent
.takeIf { it > 0 && message.isMe() }
?.let(dateFormatter::getDetailedTimestamp)
?.let { context.getString(R.string.compose_details_delivered, it) }
?.let(builder::appendln)
message.errorCode
.takeIf { it != 0 && message.isSms() }
?.let { context.getString(R.string.compose_details_error_code, it) }
?.let(builder::appendln)
return builder.toString().trim()
}
}
@@ -0,0 +1,335 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.support.v4.app.NotificationCompat
import android.support.v4.app.NotificationManagerCompat
import android.support.v4.app.RemoteInput
import android.support.v4.app.TaskStackBuilder
import android.telephony.PhoneNumberUtils
import com.moez.QKSMS.R
import com.moez.QKSMS.common.util.extensions.dpToPx
import com.moez.QKSMS.extensions.isImage
import com.moez.QKSMS.feature.compose.ComposeActivity
import com.moez.QKSMS.feature.qkreply.QkReplyActivity
import com.moez.QKSMS.mapper.CursorToPartImpl
import com.moez.QKSMS.receiver.MarkReadReceiver
import com.moez.QKSMS.receiver.MarkSeenReceiver
import com.moez.QKSMS.receiver.RemoteMessagingReceiver
import com.moez.QKSMS.repository.ConversationRepository
import com.moez.QKSMS.repository.MessageRepository
import com.moez.QKSMS.util.Preferences
import com.moez.QKSMS.util.tryOrNull
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class NotificationManagerImpl @Inject constructor(
private val context: Context,
private val colors: Colors,
private val conversationRepo: ConversationRepository,
private val prefs: Preferences,
private val messageRepo: MessageRepository
) : com.moez.QKSMS.manager.NotificationManager {
companion object {
const val DEFAULT_CHANNEL_ID = "notifications_default"
val VIBRATE_PATTERN = longArrayOf(0, 200, 0, 200)
}
private val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
init {
@SuppressLint("NewApi")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Default"
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(DEFAULT_CHANNEL_ID, name, importance).apply {
enableLights(true)
lightColor = Color.WHITE
enableVibration(true)
vibrationPattern = VIBRATE_PATTERN
}
notificationManager.createNotificationChannel(channel)
}
}
/**
* Updates the notification for a particular conversation
*/
override fun update(threadId: Long) {
// If notifications are disabled, don't do anything
if (!prefs.notifications(threadId).get()) {
return
}
val messages = messageRepo.getUnreadUnseenMessages(threadId)
// If there are no messages to be displayed, make sure that the notification is dismissed
if (messages.isEmpty()) {
notificationManager.cancel(threadId.toInt())
return
}
val conversation = conversationRepo.getConversation(threadId) ?: return
val contentIntent = Intent(context, ComposeActivity::class.java).putExtra("threadId", threadId)
val taskStackBuilder = TaskStackBuilder.create(context)
taskStackBuilder.addParentStack(ComposeActivity::class.java)
taskStackBuilder.addNextIntent(contentIntent)
val contentPI = taskStackBuilder.getPendingIntent(threadId.toInt() + 10000, PendingIntent.FLAG_UPDATE_CURRENT)
val seenIntent = Intent(context, MarkSeenReceiver::class.java).putExtra("threadId", threadId)
val seenPI = PendingIntent.getBroadcast(context, threadId.toInt() + 20000, seenIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val readIntent = Intent(context, MarkReadReceiver::class.java).putExtra("threadId", threadId)
val readPI = PendingIntent.getBroadcast(context, threadId.toInt() + 30000, readIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val readAction = NotificationCompat.Action(R.drawable.ic_check_white_24dp, context.getString(R.string.notification_read), readPI)
// We can't store a null preference, so map it to a null Uri if the pref string is empty
val ringtone = prefs.ringtone(threadId).get()
.takeIf { it.isNotEmpty() }
?.let(Uri::parse)
val notification = NotificationCompat.Builder(context, getChannelIdForNotification(threadId))
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setColor(colors.theme(threadId).theme)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setSmallIcon(R.drawable.ic_notification)
.setNumber(messages.size)
.setAutoCancel(true)
.setContentIntent(contentPI)
.setDeleteIntent(seenPI)
.addAction(readAction)
.setSound(ringtone)
.setLights(Color.WHITE, 500, 2000)
.setVibrate(if (prefs.vibration(threadId).get()) VIBRATE_PATTERN else longArrayOf(0))
val messagingStyle = NotificationCompat.MessagingStyle("Me")
if (conversation.recipients.size >= 2) {
messagingStyle.isGroupConversation = true
messagingStyle.conversationTitle = conversation.getTitle()
}
messages.forEach { message ->
val name = when {
message.isMe() -> null
conversation.recipients.size < 2 -> conversation.getTitle()
else -> conversation.recipients
.firstOrNull { PhoneNumberUtils.compare(it.address, message.address) }
?.getDisplayName()
?: message.address
}
NotificationCompat.MessagingStyle.Message(message.getSummary(), message.date, name).apply {
message.parts.firstOrNull { it.isImage() }?.let { part ->
setData(part.type, ContentUris.withAppendedId(CursorToPartImpl.CONTENT_URI, part.id))
}
messagingStyle.addMessage(this)
}
}
val avatar = conversation.recipients.takeIf { it.size == 1 }
?.first()?.address
?.let { address ->
GlideApp.with(context)
.asBitmap()
.circleCrop()
.load(PhoneNumberUtils.stripSeparators(address))
.submit(64.dpToPx(context), 64.dpToPx(context))
}
?.let { futureGet -> tryOrNull { futureGet.get() } }
when (prefs.notificationPreviews(threadId).get()) {
Preferences.NOTIFICATION_PREVIEWS_ALL -> {
notification
.setLargeIcon(avatar)
.setStyle(messagingStyle)
}
Preferences.NOTIFICATION_PREVIEWS_NAME -> {
notification
.setLargeIcon(avatar)
.setContentTitle(conversation.getTitle())
.setContentText(context.resources.getQuantityString(R.plurals.notification_new_messages, messages.size, messages.size))
}
Preferences.NOTIFICATION_PREVIEWS_NONE -> {
notification
.setContentTitle(context.getString(R.string.app_name))
.setContentText(context.resources.getQuantityString(R.plurals.notification_new_messages, messages.size, messages.size))
}
}
// Add all of the people from this conversation to the notification, so that the system can
// appropriately bypass DND mode
conversation.recipients
.mapNotNull { recipient -> recipient.contact?.lookupKey }
.forEach { uri -> notification.addPerson(uri) }
if (Build.VERSION.SDK_INT >= 24) {
notification.addAction(getReplyAction(threadId))
} else {
val replyIntent = Intent(context, QkReplyActivity::class.java).putExtra("threadId", threadId)
val replyPI = PendingIntent.getActivity(context, threadId.toInt() + 40000, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val replyAction = NotificationCompat.Action(R.drawable.ic_reply_white_24dp, context.getString(R.string.notification_reply), replyPI)
notification.addAction(replyAction)
}
if (prefs.qkreply.get()) {
notification.priority = NotificationCompat.PRIORITY_DEFAULT
val intent = Intent(context, QkReplyActivity::class.java)
.putExtra("threadId", threadId)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
notificationManager.notify(threadId.toInt(), notification.build())
}
override fun notifyFailed(msgId: Long) {
val message = messageRepo.getMessage(msgId)
if (message == null || !message.isFailedMessage()) {
return
}
val conversation = conversationRepo.getConversation(message.threadId) ?: return
val threadId = conversation.id
val contentIntent = Intent(context, ComposeActivity::class.java).putExtra("threadId", threadId)
val taskStackBuilder = TaskStackBuilder.create(context)
taskStackBuilder.addParentStack(ComposeActivity::class.java)
taskStackBuilder.addNextIntent(contentIntent)
val contentPI = taskStackBuilder.getPendingIntent(threadId.toInt() + 40000, PendingIntent.FLAG_UPDATE_CURRENT)
val notification = NotificationCompat.Builder(context, getChannelIdForNotification(threadId))
.setContentTitle(context.getString(R.string.notification_message_failed_title))
.setContentText(context.getString(R.string.notification_message_failed_text, conversation.getTitle()))
.setColor(colors.theme(threadId).theme)
.setPriority(NotificationManagerCompat.IMPORTANCE_MAX)
.setSmallIcon(R.drawable.ic_notification_failed)
.setAutoCancel(true)
.setContentIntent(contentPI)
.setSound(Uri.parse(prefs.ringtone(threadId).get()))
.setLights(Color.WHITE, 500, 2000)
.setVibrate(if (prefs.vibration(threadId).get()) VIBRATE_PATTERN else longArrayOf(0))
notificationManager.notify(threadId.toInt() + 50000, notification.build())
}
private fun getReplyAction(threadId: Long): NotificationCompat.Action {
val replyIntent = Intent(context, RemoteMessagingReceiver::class.java).putExtra("threadId", threadId)
val replyPI = PendingIntent.getBroadcast(context, threadId.toInt() + 40000, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val responseSet = context.resources.getStringArray(R.array.qk_responses)
val remoteInput = RemoteInput.Builder("body")
.setLabel(context.getString(R.string.notification_reply))
.setChoices(responseSet)
.build()
return NotificationCompat.Action.Builder(
R.drawable.ic_reply_white_24dp,
context.getString(R.string.notification_reply), replyPI)
.addRemoteInput(remoteInput)
.build()
}
/**
* Creates a notification channel for the given conversation
*/
override fun createNotificationChannel(threadId: Long) {
// Only proceed if the android version supports notification channels
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
conversationRepo.getConversation(threadId)?.let { conversation ->
val channelId = buildNotificationChannelId(threadId)
val name = conversation.getTitle()
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(channelId, name, importance).apply {
enableLights(true)
lightColor = Color.WHITE
enableVibration(true)
vibrationPattern = VIBRATE_PATTERN
}
notificationManager.createNotificationChannel(channel)
}
}
/**
* Returns the notification channel for the given conversation, or null if it doesn't exist
*/
private fun getNotificationChannel(threadId: Long): NotificationChannel? {
val channelId = buildNotificationChannelId(threadId)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return notificationManager
.notificationChannels
.firstOrNull { channel -> channel.id == channelId }
}
return null
}
/**
* Returns the channel id that should be used for a notification based on the threadId
*
* If a notification channel for the conversation exists, use the id for that. Otherwise return
* the default channel id
*/
private fun getChannelIdForNotification(threadId: Long): String {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = buildNotificationChannelId(threadId)
return notificationManager
.notificationChannels
.map { channel -> channel.id }
.firstOrNull { id -> id == channelId }
?: DEFAULT_CHANNEL_ID
}
return DEFAULT_CHANNEL_ID
}
/**
* Formats a notification channel id for a given thread id, whether the channel exists or not
*/
override fun buildNotificationChannelId(threadId: Long): String {
return when (threadId) {
0L -> DEFAULT_CHANNEL_ID
else -> "notifications_$threadId"
}
}
}
@@ -0,0 +1,183 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util
import android.graphics.Typeface
import android.util.AttributeSet
import android.widget.TextView
import com.moez.QKSMS.R
import com.moez.QKSMS.common.util.TextViewStyler.Companion.SIZE_PRIMARY
import com.moez.QKSMS.common.util.TextViewStyler.Companion.SIZE_SECONDARY
import com.moez.QKSMS.common.util.TextViewStyler.Companion.SIZE_TERTIARY
import com.moez.QKSMS.common.util.TextViewStyler.Companion.SIZE_TOOLBAR
import com.moez.QKSMS.common.util.extensions.getColorCompat
import com.moez.QKSMS.common.util.extensions.resolveThemeColor
import com.moez.QKSMS.common.widget.QkEditText
import com.moez.QKSMS.common.widget.QkTextView
import com.moez.QKSMS.util.Preferences
import javax.inject.Inject
class TextViewStyler @Inject constructor(
private val prefs: Preferences,
private val colors: Colors,
private val fontProvider: FontProvider
) {
companion object {
const val COLOR_PRIMARY = 0
const val COLOR_SECONDARY = 1
const val COLOR_TERTIARY = 2
const val COLOR_PRIMARY_ON_THEME = 3
const val COLOR_SECONDARY_ON_THEME = 4
const val COLOR_TERTIARY_ON_THEME = 5
const val COLOR_THEME = 6
const val SIZE_PRIMARY = 0
const val SIZE_SECONDARY = 1
const val SIZE_TERTIARY = 2
const val SIZE_TOOLBAR = 3
fun applyEditModeAttributes(textView: TextView, attrs: AttributeSet?) {
textView.run {
var colorAttr = 0
var textSizeAttr = 0
when (this) {
is QkTextView -> context.obtainStyledAttributes(attrs, R.styleable.QkTextView)?.run {
colorAttr = getInt(R.styleable.QkTextView_textColor, -1)
textSizeAttr = getInt(R.styleable.QkTextView_textSize, -1)
recycle()
}
is QkEditText -> context.obtainStyledAttributes(attrs, R.styleable.QkEditText)?.run {
colorAttr = getInt(R.styleable.QkEditText_textColor, -1)
textSizeAttr = getInt(R.styleable.QkEditText_textSize, -1)
recycle()
}
else -> return
}
setTextColor(when (colorAttr) {
COLOR_PRIMARY -> context.getColorCompat(R.color.textPrimary)
COLOR_SECONDARY -> context.getColorCompat(R.color.textSecondary)
COLOR_TERTIARY -> context.getColorCompat(R.color.textTertiary)
COLOR_PRIMARY_ON_THEME -> context.getColorCompat(R.color.textPrimaryDark)
COLOR_SECONDARY_ON_THEME -> context.getColorCompat(R.color.textSecondaryDark)
COLOR_TERTIARY_ON_THEME -> context.getColorCompat(R.color.textTertiaryDark)
COLOR_THEME -> context.getColorCompat(R.color.tools_theme)
else -> currentTextColor
})
textSize = when (textSizeAttr) {
SIZE_PRIMARY -> 16f
SIZE_SECONDARY -> 14f
SIZE_TERTIARY -> 12f
SIZE_TOOLBAR -> 20f
else -> textSize / paint.density
}
}
}
}
fun applyAttributes(textView: TextView, attrs: AttributeSet?) {
textView.run {
var colorAttr = 0
var textSizeAttr = 0
if (!prefs.systemFont.get()) {
fontProvider.getLato { lato ->
setTypeface(lato, typeface?.style ?: Typeface.NORMAL)
}
}
when (this) {
is QkTextView -> context.obtainStyledAttributes(attrs, R.styleable.QkTextView)?.run {
colorAttr = getInt(R.styleable.QkTextView_textColor, -1)
textSizeAttr = getInt(R.styleable.QkTextView_textSize, -1)
recycle()
}
is QkEditText -> context.obtainStyledAttributes(attrs, R.styleable.QkEditText)?.run {
colorAttr = getInt(R.styleable.QkEditText_textColor, -1)
textSizeAttr = getInt(R.styleable.QkEditText_textSize, -1)
recycle()
}
else -> return
}
setTextColor(when (colorAttr) {
COLOR_PRIMARY -> context.resolveThemeColor(android.R.attr.textColorPrimary)
COLOR_SECONDARY -> context.resolveThemeColor(android.R.attr.textColorSecondary)
COLOR_TERTIARY -> context.resolveThemeColor(android.R.attr.textColorTertiary)
COLOR_PRIMARY_ON_THEME -> colors.theme().textPrimary
COLOR_SECONDARY_ON_THEME -> colors.theme().textSecondary
COLOR_TERTIARY_ON_THEME -> colors.theme().textTertiary
COLOR_THEME -> colors.theme().theme
else -> currentTextColor
})
setTextSize(textView, textSizeAttr)
}
}
/**
* @see SIZE_PRIMARY
* @see SIZE_SECONDARY
* @see SIZE_TERTIARY
* @see SIZE_TOOLBAR
*/
fun setTextSize(textView: TextView, textSizeAttr: Int) {
val textSizePref = prefs.textSize.get()
when (textSizeAttr) {
SIZE_PRIMARY -> textView.textSize = when (textSizePref) {
Preferences.TEXT_SIZE_SMALL -> 14f
Preferences.TEXT_SIZE_NORMAL -> 16f
Preferences.TEXT_SIZE_LARGE -> 18f
Preferences.TEXT_SIZE_LARGER -> 20f
else -> 16f
}
SIZE_SECONDARY -> textView.textSize = when (textSizePref) {
Preferences.TEXT_SIZE_SMALL -> 12f
Preferences.TEXT_SIZE_NORMAL -> 14f
Preferences.TEXT_SIZE_LARGE -> 16f
Preferences.TEXT_SIZE_LARGER -> 18f
else -> 14f
}
SIZE_TERTIARY -> textView.textSize = when (textSizePref) {
Preferences.TEXT_SIZE_SMALL -> 10f
Preferences.TEXT_SIZE_NORMAL -> 12f
Preferences.TEXT_SIZE_LARGE -> 14f
Preferences.TEXT_SIZE_LARGER -> 16f
else -> 12f
}
SIZE_TOOLBAR -> textView.textSize = when (textSizePref) {
Preferences.TEXT_SIZE_SMALL -> 18f
Preferences.TEXT_SIZE_NORMAL -> 20f
Preferences.TEXT_SIZE_LARGE -> 22f
Preferences.TEXT_SIZE_LARGER -> 26f
else -> 20f
}
}
}
}
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util.extensions
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
fun RecyclerView.Adapter<*>.autoScrollToStart(recyclerView: RecyclerView) {
registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
val layoutManager = recyclerView.layoutManager as? LinearLayoutManager ?: return
if (layoutManager.stackFromEnd) {
if (positionStart > 0) {
notifyItemChanged(positionStart - 1)
}
val lastPosition = layoutManager.findLastVisibleItemPosition()
if (positionStart >= getItemCount() - 1 && lastPosition == positionStart - 1) {
recyclerView.scrollToPosition(positionStart)
}
} else {
val firstVisiblePosition = layoutManager.findFirstVisibleItemPosition()
if (firstVisiblePosition == 0) {
recyclerView.scrollToPosition(positionStart)
}
}
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
val layoutManager = recyclerView.layoutManager as? LinearLayoutManager ?: return
if (!layoutManager.stackFromEnd) {
onItemRangeInserted(positionStart, itemCount)
}
}
})
}
@@ -0,0 +1,33 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util.extensions
import java.util.*
fun Calendar.isSameDay(other: Calendar): Boolean {
return get(Calendar.YEAR) == other.get(Calendar.YEAR) && get(Calendar.DAY_OF_YEAR) == other.get(Calendar.DAY_OF_YEAR)
}
fun Calendar.isSameWeek(other: Calendar): Boolean {
return get(Calendar.YEAR) == other.get(Calendar.YEAR) && get(Calendar.WEEK_OF_YEAR) == other.get(Calendar.WEEK_OF_YEAR)
}
fun Calendar.isSameYear(other: Calendar): Boolean {
return get(Calendar.YEAR) == other.get(Calendar.YEAR)
}
@@ -0,0 +1,65 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util.extensions
import android.app.Activity
import android.content.Context
import android.support.annotation.StringRes
import android.support.v4.content.ContextCompat
import android.util.TypedValue
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
fun Context.getColorCompat(colorRes: Int): Int {
return ContextCompat.getColor(this, colorRes)
}
/**
* Tries to resolve a resource id from the current theme, based on the [attributeId]
*/
fun Context.resolveThemeAttribute(attributeId: Int, default: Int = 0): Int {
val outValue = TypedValue()
val wasResolved = theme.resolveAttribute(attributeId, outValue, true)
return if (wasResolved) outValue.resourceId else default
}
fun Context.resolveThemeColor(attributeId: Int, default: Int = 0): Int {
val outValue = TypedValue()
val wasResolved = theme.resolveAttribute(attributeId, outValue, true)
return if (wasResolved) getColorCompat(outValue.resourceId) else default
}
fun Context.makeToast(@StringRes res: Int, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, res, duration).show()
}
fun Context.makeToast(text: String, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, text, duration).show()
}
fun Activity.dismissKeyboard() {
window.currentFocus?.let { focus ->
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(focus.windowToken, 0)
focus.clearFocus()
}
}
@@ -0,0 +1,41 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util.extensions
import android.content.Context
import android.graphics.Color
import android.util.TypedValue
fun Int.dpToPx(context: Context): Int {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), context.resources.displayMetrics).toInt()
}
fun Int.withAlpha(alpha: Int): Int {
return Color.argb(alpha, Color.red(this), Color.green(this), Color.blue(this))
}
fun Int.forEach(action: (Int) -> Unit) {
for (index in 0 until this) {
action(index)
}
}
fun Float.within(min: Float, max: Float): Float {
return Math.min(max, Math.max(min, this))
}
@@ -0,0 +1,119 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util.extensions
import android.animation.LayoutTransition
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.os.Build
import android.support.v7.widget.RecyclerView
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.ProgressBar
var ViewGroup.animateLayoutChanges: Boolean
get() = layoutTransition != null
set(value) {
layoutTransition = if (value) LayoutTransition() else null
}
fun EditText.showKeyboard() {
requestFocus()
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, 0)
}
fun ImageView.setTint(color: Int) {
imageTintList = ColorStateList.valueOf(color)
}
fun ProgressBar.setTint(color: Int) {
indeterminateTintList = ColorStateList.valueOf(color)
progressTintList = ColorStateList.valueOf(color)
}
fun View.setBackgroundTint(color: Int) {
// API 21 doesn't support this
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
background?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
}
backgroundTintList = ColorStateList.valueOf(color)
}
fun View.setPadding(left: Int? = null, top: Int? = null, right: Int? = null, bottom: Int? = null) {
setPadding(left ?: paddingLeft, top ?: paddingTop, right ?: paddingRight, bottom ?: paddingBottom)
}
fun View.setVisible(visible: Boolean, invisible: Int = View.GONE) {
visibility = if (visible) View.VISIBLE else invisible
}
/**
* If a view captures clicks at all, then the parent won't ever receive touch events. This is a
* problem when we're trying to capture link clicks, but tapping or long pressing other areas of
* the view no longer work. Also problematic when we try to long press on an image in the message
* view
*/
fun View.forwardTouches(parent: View) {
var isLongClick = false
setOnLongClickListener {
isLongClick = true
true
}
setOnTouchListener { v, event ->
parent.onTouchEvent(event)
when {
event.action == MotionEvent.ACTION_UP && isLongClick -> {
isLongClick = true
true
}
event.action == MotionEvent.ACTION_DOWN -> {
isLongClick = false
v.onTouchEvent(event)
}
else -> v.onTouchEvent(event)
}
}
}
fun RecyclerView.scrapViews() {
val adapter = adapter
val layoutManager = layoutManager
this.adapter = null
this.layoutManager = null
this.adapter = adapter
this.layoutManager = layoutManager
adapter?.notifyDataSetChanged()
}
@@ -0,0 +1,131 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.widget
import android.content.Context
import android.net.Uri
import android.provider.ContactsContract
import android.telephony.PhoneNumberUtils
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import com.moez.QKSMS.R
import com.moez.QKSMS.common.Navigator
import com.moez.QKSMS.common.util.Colors
import com.moez.QKSMS.common.util.GlideApp
import com.moez.QKSMS.common.util.extensions.setBackgroundTint
import com.moez.QKSMS.common.util.extensions.setTint
import com.moez.QKSMS.injection.appComponent
import com.moez.QKSMS.model.Contact
import com.moez.QKSMS.model.Recipient
import kotlinx.android.synthetic.main.avatar_view.view.*
import javax.inject.Inject
class AvatarView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : FrameLayout(context, attrs) {
@Inject lateinit var colors: Colors
@Inject lateinit var navigator: Navigator
/**
* This value can be changes if we should use the theme from a particular conversation
*/
var threadId: Long = 0
set(value) {
if (field == value) return
field = value
applyTheme(value)
}
private var lookupKey: String? = null
private var name: String? = null
private var address: String? = null
init {
if (!isInEditMode) {
appComponent.inject(this)
}
View.inflate(context, R.layout.avatar_view, this)
setBackgroundResource(R.drawable.circle)
clipToOutline = true
setOnClickListener {
if (lookupKey.isNullOrEmpty()) {
address?.let { address -> navigator.addContact(address) }
} else {
val uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey)
ContactsContract.QuickContact.showQuickContact(context, this@AvatarView, uri,
ContactsContract.QuickContact.MODE_MEDIUM, null)
}
}
}
fun setContact(recipient: Recipient?) {
// If the recipient has a contact, just use that and return
recipient?.contact?.let { contact ->
setContact(contact)
return
}
lookupKey = null
name = null
address = recipient?.address
updateView()
}
fun setContact(contact: Contact?) {
lookupKey = contact?.lookupKey
name = contact?.name
address = contact?.numbers?.firstOrNull()?.address
updateView()
}
override fun onFinishInflate() {
super.onFinishInflate()
if (!isInEditMode) {
applyTheme(threadId)
updateView()
}
}
fun applyTheme(threadId: Long) {
colors.theme(threadId).run {
setBackgroundTint(theme)
initial.setTextColor(textPrimary)
icon.setTint(textPrimary)
}
}
private fun updateView() {
if (name?.isNotEmpty() == true) {
initial.text = name?.substring(0, 1)
icon.visibility = GONE
} else {
initial.text = null
icon.visibility = VISIBLE
}
photo.setImageDrawable(null)
address?.let { address ->
GlideApp.with(photo).load(PhoneNumberUtils.stripSeparators(address)).into(photo)
}
}
}
@@ -0,0 +1,110 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import android.widget.ImageView
import com.moez.QKSMS.common.util.extensions.dpToPx
class BubbleImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ImageView(context, attrs) {
enum class Style(val topLeft: Boolean, val topRight: Boolean, val bottomRight: Boolean, val bottomLeft: Boolean) {
ONLY(true, true, true, true),
IN_FIRST(true, true, true, false),
IN_MIDDLE(false, true, true, false),
IN_LAST(false, true, true, true),
OUT_FIRST(true, true, false, true),
OUT_MIDDLE(true, false, false, true),
OUT_LAST(true, false, true, true)
}
var bubbleStyle = Style.ONLY
set(value) {
field = value
setPath()
invalidate()
}
private val path = Path()
private val radiusSmall = 4.dpToPx(context).toFloat()
private val radiusLarge = 18.dpToPx(context).toFloat()
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
setPath()
}
override fun onDraw(canvas: Canvas) {
if (!path.isEmpty) {
canvas.clipPath(path)
}
super.onDraw(canvas)
}
private fun setPath() {
path.rewind()
val width = width.toFloat()
val height = height.toFloat()
val cornerRectSmall = RectF().apply { set(-radiusSmall, -radiusSmall, radiusSmall, radiusSmall) }
val cornerRectLarge = RectF().apply { set(-radiusLarge, -radiusLarge, radiusLarge, radiusLarge) }
if (bubbleStyle.topLeft) {
cornerRectLarge.offsetTo(0f, 0f)
path.arcTo(cornerRectLarge, 180f, 90f)
} else {
cornerRectSmall.offsetTo(0f, 0f)
path.arcTo(cornerRectSmall, 180f, 90f)
}
if (bubbleStyle.topRight) {
cornerRectLarge.offsetTo(width - radiusLarge * 2, 0f)
path.arcTo(cornerRectLarge, 270f, 90f)
} else {
cornerRectSmall.offsetTo(width - radiusSmall * 2, 0f)
path.arcTo(cornerRectSmall, 270f, 90f)
}
if (bubbleStyle.bottomRight) {
cornerRectLarge.offsetTo(width - radiusLarge * 2, height - radiusLarge * 2)
path.arcTo(cornerRectLarge, 0f, 90f)
} else {
cornerRectSmall.offsetTo(width - radiusSmall * 2, height - radiusSmall * 2)
path.arcTo(cornerRectSmall, 0f, 90f)
}
if (bubbleStyle.bottomLeft) {
cornerRectLarge.offsetTo(0f, height - radiusLarge * 2)
path.arcTo(cornerRectLarge, 90f, 90f)
} else {
cornerRectSmall.offsetTo(0f, height - radiusSmall * 2)
path.arcTo(cornerRectSmall, 90f, 90f)
}
path.close()
}
}
@@ -0,0 +1,70 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.widget
import android.content.Context
import android.os.Build
import android.support.constraint.ConstraintLayout
import android.util.AttributeSet
import android.view.View
import com.moez.QKSMS.R
import com.moez.QKSMS.model.Recipient
import kotlinx.android.synthetic.main.group_avatar_view.view.*
class GroupAvatarView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ConstraintLayout(context, attrs) {
var contacts: List<Recipient> = ArrayList()
set(value) {
field = value
updateView()
}
private val avatars by lazy { listOf(avatar1, avatar2, avatar3) }
init {
View.inflate(context, R.layout.group_avatar_view, this)
setBackgroundResource(R.drawable.circle)
clipToOutline = true
}
override fun onFinishInflate() {
super.onFinishInflate()
avatars.forEach { avatar ->
avatar.setBackgroundResource(R.drawable.rectangle)
// If we're on API 21 we need to reapply the tint after changing the background
if (Build.VERSION.SDK_INT < 22) {
avatar.applyTheme(0)
}
}
if (!isInEditMode) {
updateView()
}
}
private fun updateView() {
avatars.forEachIndexed { index, avatar ->
avatar.visibility = if (contacts.size > index) View.VISIBLE else View.GONE
avatar.setContact(contacts.getOrNull(index))
}
}
}
@@ -0,0 +1,108 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.widget
import android.content.Context
import android.content.res.ColorStateList
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.TextView
import com.moez.QKSMS.R
import com.moez.QKSMS.common.util.Colors
import com.moez.QKSMS.common.util.extensions.forEach
import com.moez.QKSMS.common.util.extensions.resolveThemeColor
import com.moez.QKSMS.injection.appComponent
import com.uber.autodispose.android.scope
import com.uber.autodispose.kotlin.autoDisposable
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.tab_view.view.*
import javax.inject.Inject
class PagerTitleView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : LinearLayout(context, attrs) {
@Inject lateinit var colors: Colors
private val threadId: Subject<Long> = BehaviorSubject.create()
var pager: ViewPager? = null
set(value) {
if (field !== value) {
field = value
recreate()
}
}
init {
if (!isInEditMode) appComponent.inject(this)
}
fun setThreadId(id: Long) {
threadId.onNext(id)
}
private fun recreate() {
removeAllViews()
pager?.adapter?.count?.forEach { position ->
val view = LayoutInflater.from(context).inflate(R.layout.tab_view, this, false)
view.label.text = pager?.adapter?.getPageTitle(position)
view.setOnClickListener { pager?.currentItem = position }
addView(view)
}
childCount.forEach { index ->
getChildAt(index).isSelected = index == pager?.currentItem
}
pager?.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
childCount.forEach { index ->
getChildAt(index).isSelected = index == position
}
}
})
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
val states = arrayOf(
intArrayOf(android.R.attr.state_selected),
intArrayOf(-android.R.attr.state_selected))
threadId
.distinctUntilChanged()
.switchMap { threadId -> colors.themeObservable(threadId) }
.map { theme ->
val textSecondary = context.resolveThemeColor(android.R.attr.textColorSecondary)
ColorStateList(states, intArrayOf(theme.theme, textSecondary))
}
.autoDisposable(scope())
.subscribe { colorStateList ->
childCount.forEach { index ->
(getChildAt(index) as? TextView)?.setTextColor(colorStateList)
}
}
}
}
@@ -0,0 +1,96 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.widget
import android.content.Context
import android.support.v7.widget.LinearLayoutCompat
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.widget.TextView
import com.moez.QKSMS.R
import com.moez.QKSMS.common.util.extensions.resolveThemeAttribute
import com.moez.QKSMS.common.util.extensions.resolveThemeColor
import com.moez.QKSMS.common.util.extensions.setTint
import com.moez.QKSMS.common.util.extensions.setVisible
import com.moez.QKSMS.injection.appComponent
import kotlinx.android.synthetic.main.preference_view.view.*
class PreferenceView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : LinearLayoutCompat(context, attrs) {
var title: String? = null
set(value) {
field = value
if (isInEditMode) {
findViewById<TextView>(R.id.titleView).text = value
} else {
titleView.text = value
}
}
var summary: String? = null
set(value) {
field = value
if (isInEditMode) {
findViewById<TextView>(R.id.summaryView).run {
text = value
setVisible(value?.isNotEmpty() == true)
}
} else {
summaryView.text = value
summaryView.setVisible(value?.isNotEmpty() == true)
}
}
init {
if (!isInEditMode) {
appComponent.inject(this)
}
View.inflate(context, R.layout.preference_view, this)
setBackgroundResource(context.resolveThemeAttribute(R.attr.selectableItemBackground))
orientation = HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
val textSecondary = context.resolveThemeColor(android.R.attr.textColorSecondary)
icon.setTint(textSecondary)
context.obtainStyledAttributes(attrs, R.styleable.PreferenceView)?.run {
title = getString(R.styleable.PreferenceView_title)
summary = getString(R.styleable.PreferenceView_summary)
// If there's a custom view used for the preference's widget, inflate it
getResourceId(R.styleable.PreferenceView_widget, -1).takeIf { it != -1 }?.let { id ->
View.inflate(context, id, widgetFrame)
}
// If an icon is being used, set up the icon view
getResourceId(R.styleable.PreferenceView_icon, -1).takeIf { it != -1 }?.let { id ->
icon.setVisible(true)
icon.setImageResource(id)
}
recycle()
}
}
}
@@ -0,0 +1,109 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.widget
import android.content.Context
import android.os.Build
import android.support.v13.view.inputmethod.EditorInfoCompat
import android.support.v13.view.inputmethod.InputConnectionCompat
import android.support.v13.view.inputmethod.InputContentInfoCompat
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputConnectionWrapper
import android.widget.EditText
import com.google.android.mms.ContentType
import com.moez.QKSMS.common.util.TextViewStyler
import com.moez.QKSMS.injection.appComponent
import com.moez.QKSMS.util.tryOrNull
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import javax.inject.Inject
/**
* Custom implementation of EditText to allow for dynamic text colors
*
* Beware of updating to extend AppCompatTextView, as this inexplicably breaks the view in
* the contacts chip view
*/
class QkEditText @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : EditText(context, attrs) {
@Inject lateinit var textViewStyler: TextViewStyler
val backspaces: Subject<Unit> = PublishSubject.create()
val inputContentSelected: Subject<InputContentInfoCompat> = PublishSubject.create()
var supportsInputContent: Boolean = false
init {
if (!isInEditMode) {
appComponent.inject(this)
textViewStyler.applyAttributes(this, attrs)
} else {
TextViewStyler.applyEditModeAttributes(this, attrs)
}
}
override fun onCreateInputConnection(editorInfo: EditorInfo): InputConnection {
val inputConnection = object : InputConnectionWrapper(super.onCreateInputConnection(editorInfo), true) {
override fun sendKeyEvent(event: KeyEvent): Boolean {
if (event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_DEL) {
backspaces.onNext(Unit)
}
return super.sendKeyEvent(event)
}
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
if (beforeLength == 1 && afterLength == 0) {
backspaces.onNext(Unit)
}
return super.deleteSurroundingText(beforeLength, afterLength)
}
}
if (supportsInputContent) {
EditorInfoCompat.setContentMimeTypes(editorInfo, arrayOf(
ContentType.IMAGE_JPEG,
ContentType.IMAGE_JPG,
ContentType.IMAGE_PNG,
ContentType.IMAGE_GIF))
}
val callback = InputConnectionCompat.OnCommitContentListener { inputContentInfo, flags, opts ->
val grantReadPermission = flags and InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION != 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 && grantReadPermission) {
return@OnCommitContentListener tryOrNull {
inputContentInfo.requestPermission()
inputContentSelected.onNext(inputContentInfo)
true
} ?: false
}
true
}
return InputConnectionCompat.createWrapper(inputConnection, editorInfo, callback)
}
}
@@ -0,0 +1,75 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.widget
import android.content.Context
import android.content.res.ColorStateList
import android.support.v7.widget.SwitchCompat
import android.util.AttributeSet
import com.moez.QKSMS.R
import com.moez.QKSMS.common.util.Colors
import com.moez.QKSMS.common.util.extensions.getColorCompat
import com.moez.QKSMS.common.util.extensions.withAlpha
import com.moez.QKSMS.injection.appComponent
import com.moez.QKSMS.util.Preferences
import javax.inject.Inject
class QkSwitch @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : SwitchCompat(context, attrs) {
@Inject lateinit var colors: Colors
@Inject lateinit var prefs: Preferences
init {
if (!isInEditMode) {
appComponent.inject(this)
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (!isInEditMode) {
val states = arrayOf(
intArrayOf(-android.R.attr.state_enabled),
intArrayOf(android.R.attr.state_checked),
intArrayOf())
val themeColor = colors.theme().theme
val switchThumbEnabled: Int = prefs.night.get()
.let { night -> if (night) R.color.switchThumbEnabledDark else R.color.switchThumbEnabledLight }
.let { res -> context.getColorCompat(res) }
val switchThumbDisabled: Int = prefs.night.get()
.let { night -> if (night) R.color.switchThumbDisabledDark else R.color.switchThumbDisabledLight }
.let { res -> context.getColorCompat(res) }
val switchTrackEnabled: Int = prefs.night.get()
.let { night -> if (night) R.color.switchTrackEnabledDark else R.color.switchTrackEnabledLight }
.let { res -> context.getColorCompat(res) }
val switchTrackDisabled: Int = prefs.night.get()
.let { night -> if (night) R.color.switchTrackDisabledDark else R.color.switchTrackDisabledLight }
.let { res -> context.getColorCompat(res) }
thumbTintList = ColorStateList(states, intArrayOf(switchThumbDisabled, themeColor, switchThumbEnabled))
trackTintList = ColorStateList(states, intArrayOf(switchTrackDisabled, themeColor.withAlpha(0x4D), switchTrackEnabled))
}
}
}
@@ -0,0 +1,47 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.widget
import android.content.Context
import android.support.text.emoji.widget.EmojiAppCompatTextView
import android.util.AttributeSet
import com.moez.QKSMS.common.util.TextViewStyler
import com.moez.QKSMS.injection.appComponent
import javax.inject.Inject
open class QkTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null)
: EmojiAppCompatTextView(context, attrs) {
@Inject lateinit var textViewStyler: TextViewStyler
init {
if (!isInEditMode) {
appComponent.inject(this)
textViewStyler.applyAttributes(this, attrs)
} else {
TextViewStyler.applyEditModeAttributes(this, attrs)
}
}
override fun setTextColor(color: Int) {
super.setTextColor(color)
setLinkTextColor(color)
}
}
@@ -0,0 +1,31 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.widget
import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView
class SquareImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ImageView(context, attrs) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec)
}
}
@@ -0,0 +1,41 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.widget
import android.content.Context
import android.util.AttributeSet
class TightTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : QkTextView(context, attrs) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
layout?.let {
val maxLineWidth = (0 until layout.lineCount)
.asSequence()
.map { layout.getLineMax(it) }
.max() ?: 0f
val width = (Math.ceil(maxLineWidth.toDouble()).toInt() + compoundPaddingLeft + compoundPaddingRight)
val height = measuredHeight
setMeasuredDimension(width, height)
}
}
}