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,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()
}