Split up app module into domain/data/presentation

This commit is contained in:
Moez Bhatti
2018-03-22 00:32:07 -04:00
parent 4ef97ab854
commit d7d202392c
282 changed files with 1153 additions and 482 deletions
+138
View File
@@ -0,0 +1,138 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.moez.QKSMS"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_MMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<application
android:name="common.QKApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppThemeLight">
<activity
android:name="presentation.feature.main.MainActivity"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="presentation.feature.compose.ComposeActivity"
android:parentActivityName="presentation.feature.main.MainActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SENDTO" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
<data android:scheme="mms" />
<data android:scheme="mmsto" />
<data android:scheme="sms_body" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
<activity android:name="presentation.feature.settings.SettingsActivity" />
<activity android:name="presentation.feature.setup.SetupActivity" />
<activity android:name="presentation.feature.themepicker.ThemePickerActivity" />
<activity android:name="presentation.feature.plus.PlusActivity" />
<activity
android:name="presentation.feature.gallery.GalleryActivity"
android:theme="@style/AppThemeBlack" />
<activity android:name="presentation.feature.conversationinfo.ConversationInfoActivity" />
<activity android:name="presentation.feature.notificationprefs.NotificationPrefsActivity" />
<activity android:name="presentation.feature.blocked.BlockedActivity" />
<receiver android:name="presentation.receiver.DefaultSmsChangedReceiver">
<intent-filter>
<action android:name="android.provider.action.DEFAULT_SMS_PACKAGE_CHANGED" />
</intent-filter>
</receiver>
<receiver
android:name="presentation.receiver.SmsReceiver"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_DELIVER" />
</intent-filter>
</receiver>
<receiver
android:name="presentation.receiver.MmsReceiver"
android:permission="android.permission.BROADCAST_WAP_PUSH">
<intent-filter>
<action android:name="android.provider.Telephony.WAP_PUSH_DELIVER" />
<data android:mimeType="application/vnd.wap.mms-message" />
</intent-filter>
</receiver>
<receiver
android:name="presentation.receiver.MmsSentReceiver"
android:taskAffinity="com.klinker.android.messaging.MMS_SENT" />
<receiver
android:name="presentation.receiver.MmsUpdatedReceiver"
android:taskAffinity="com.moez.QKSMS.MMS_UPDATED" />
<receiver
android:name="presentation.receiver.MmsReceivedReceiver"
android:taskAffinity="com.klinker.android.messaging.MMS_RECEIVED" />
<receiver
android:name="presentation.receiver.SmsSentReceiver"
android:taskAffinity="com.moez.QKSMS.SMS_SENT" />
<receiver
android:name="presentation.receiver.SmsDeliveredReceiver"
android:taskAffinity="com.moez.QKSMS.SMS_DELIVERED" />
<receiver android:name="presentation.receiver.MarkSeenReceiver" />
<receiver android:name="presentation.receiver.MarkReadReceiver" />
<receiver android:name="presentation.receiver.RemoteMessagingReceiver" />
<receiver android:name="presentation.receiver.NightModeReceiver" />
<receiver android:name="presentation.receiver.SmsProviderChangedReceiver">
<intent-filter>
<action android:name="android.provider.action.EXTERNAL_PROVIDER_CHANGE" />
</intent-filter>
</receiver>
<service android:name="com.android.mms.transaction.TransactionService" />
<service
android:name="presentation.service.HeadlessSmsSendService"
android:exported="true"
android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE">
<intent-filter>
<action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
<data android:scheme="mms" />
<data android:scheme="mmsto" />
</intent-filter>
</service>
<meta-data
android:name="preloaded_fonts"
android:resource="@array/preloaded_fonts" />
</application>
</manifest>
@@ -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 common
import android.app.Application
import android.support.text.emoji.EmojiCompat
import android.support.text.emoji.FontRequestEmojiCompatConfig
import android.support.v4.provider.FontRequest
import com.bugsnag.android.Bugsnag
import com.moez.QKSMS.BuildConfig
import com.moez.QKSMS.R
import common.di.AppComponentManager
import common.di.appComponent
import manager.AnalyticsManager
import io.realm.Realm
import io.realm.RealmConfiguration
import timber.log.Timber
import javax.inject.Inject
class QKApplication : Application() {
/**
* Inject this so that it is forced to initialize
*/
@Suppress("unused")
@Inject lateinit var analyticsManager: AnalyticsManager
override fun onCreate() {
super.onCreate()
Bugsnag.init(this, BuildConfig.BUGSNAG_API_KEY)
AppComponentManager.init(this)
appComponent.inject(this)
Realm.init(this)
Realm.setDefaultConfiguration(RealmConfiguration.Builder()
.compactOnLaunch()
.deleteRealmIfMigrationNeeded()
.build())
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())
}
}
@@ -0,0 +1,120 @@
/*
* 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 common.di
import common.QKApplication
import common.util.ContactImageLoader
import dagger.Component
import presentation.common.widget.AvatarView
import presentation.common.widget.MmsPreviewView
import presentation.common.widget.PagerTitleView
import presentation.common.widget.PreferenceView
import presentation.common.widget.QkEditText
import presentation.common.widget.QkSwitch
import presentation.common.widget.QkTextView
import presentation.common.widget.Separator
import presentation.feature.blocked.BlockedActivity
import presentation.feature.blocked.BlockedViewModel
import presentation.feature.compose.ComposeActivity
import presentation.feature.compose.ComposeViewModel
import presentation.feature.compose.DetailedChipView
import presentation.feature.conversationinfo.ConversationInfoActivity
import presentation.feature.conversationinfo.ConversationInfoViewModel
import presentation.feature.gallery.GalleryActivity
import presentation.feature.gallery.GalleryViewModel
import presentation.feature.main.MainActivity
import presentation.feature.main.MainViewModel
import presentation.feature.notificationprefs.NotificationPrefsActivity
import presentation.feature.notificationprefs.NotificationPrefsViewModel
import presentation.feature.plus.PlusActivity
import presentation.feature.plus.PlusViewModel
import presentation.feature.settings.SettingsActivity
import presentation.feature.settings.SettingsViewModel
import presentation.feature.setup.SetupActivity
import presentation.feature.setup.SetupViewModel
import presentation.feature.themepicker.ThemePickerActivity
import presentation.feature.themepicker.ThemePickerViewModel
import presentation.receiver.DefaultSmsChangedReceiver
import presentation.receiver.MarkReadReceiver
import presentation.receiver.MarkSeenReceiver
import presentation.receiver.MmsReceivedReceiver
import presentation.receiver.MmsSentReceiver
import presentation.receiver.MmsUpdatedReceiver
import presentation.receiver.NightModeReceiver
import presentation.receiver.RemoteMessagingReceiver
import presentation.receiver.SmsDeliveredReceiver
import presentation.receiver.SmsProviderChangedReceiver
import presentation.receiver.SmsReceiver
import presentation.receiver.SmsSentReceiver
import javax.inject.Singleton
@Singleton
@Component(modules = [(AppModule::class)])
interface AppComponent {
fun inject(application: QKApplication)
fun inject(activity: MainActivity)
fun inject(activity: SetupActivity)
fun inject(activity: BlockedActivity)
fun inject(activity: ComposeActivity)
fun inject(activity: ConversationInfoActivity)
fun inject(activity: GalleryActivity)
fun inject(activity: NotificationPrefsActivity)
fun inject(activity: PlusActivity)
fun inject(activity: SettingsActivity)
fun inject(activity: ThemePickerActivity)
fun inject(receiver: DefaultSmsChangedReceiver)
fun inject(receiver: SmsDeliveredReceiver)
fun inject(receiver: SmsSentReceiver)
fun inject(receiver: MarkSeenReceiver)
fun inject(receiver: MarkReadReceiver)
fun inject(receiver: MmsReceivedReceiver)
fun inject(receiver: MmsSentReceiver)
fun inject(receiver: MmsUpdatedReceiver)
fun inject(receiver: NightModeReceiver)
fun inject(receiver: RemoteMessagingReceiver)
fun inject(receiver: SmsProviderChangedReceiver)
fun inject(receiver: SmsReceiver)
fun inject(view: AvatarView)
fun inject(view: DetailedChipView)
fun inject(view: MmsPreviewView)
fun inject(view: PagerTitleView)
fun inject(view: PreferenceView)
fun inject(view: QkEditText)
fun inject(view: QkSwitch)
fun inject(view: QkTextView)
fun inject(view: Separator)
fun inject(viewModel: MainViewModel)
fun inject(viewModel: SetupViewModel)
fun inject(viewModel: BlockedViewModel)
fun inject(viewModel: ComposeViewModel)
fun inject(viewModel: ConversationInfoViewModel)
fun inject(viewModel: GalleryViewModel)
fun inject(viewModel: NotificationPrefsViewModel)
fun inject(viewModel: PlusViewModel)
fun inject(viewModel: SettingsViewModel)
fun inject(viewModel: ThemePickerViewModel)
fun inject(fetcher: ContactImageLoader.ContactImageFetcher)
}
@@ -0,0 +1,34 @@
/*
* 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 common.di
import common.QKApplication
internal lateinit var appComponent: AppComponent
private set
internal object AppComponentManager {
fun init(application: QKApplication) {
appComponent = DaggerAppComponent.builder()
.appModule(AppModule(application))
.build()
}
}
@@ -0,0 +1,118 @@
/*
* 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 common.di
import android.app.Application
import android.content.Context
import android.preference.PreferenceManager
import com.f2prateek.rx.preferences2.RxSharedPreferences
import common.util.AnalyticsManagerImpl
import common.util.NotificationManagerImpl
import dagger.Module
import dagger.Provides
import manager.AnalyticsManager
import manager.KeyManager
import manager.KeyManagerImpl
import manager.NotificationManager
import manager.PermissionManager
import manager.PermissionManagerImpl
import manager.WidgetManager
import manager.WidgetManagerImpl
import mapper.CursorToContact
import mapper.CursorToContactImpl
import mapper.CursorToConversation
import mapper.CursorToConversationImpl
import mapper.CursorToMessage
import mapper.CursorToMessageImpl
import mapper.CursorToPart
import mapper.CursorToPartImpl
import mapper.CursorToRecipienImpl
import mapper.CursorToRecipient
import repository.ContactRepository
import repository.ContactRepositoryImpl
import repository.MessageRepository
import repository.MessageRepositoryImpl
import repository.SyncRepository
import repository.SyncRepositoryImpl
import javax.inject.Singleton
@Module
class AppModule(private var application: Application) {
@Provides
@Singleton
fun provideContext(): Context {
return application
}
@Provides
@Singleton
fun provideRxPreferences(context: Context): RxSharedPreferences {
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
return RxSharedPreferences.create(preferences)
}
// Manager
@Provides
fun provideAnalyticsManager(manager: AnalyticsManagerImpl): AnalyticsManager = manager
@Provides
fun provideKeyManager(manager: KeyManagerImpl): KeyManager = manager
@Provides
fun provideNotificationsManager(manager: NotificationManagerImpl): NotificationManager = manager
@Provides
fun providePermissionsManager(manager: PermissionManagerImpl): PermissionManager = manager
@Provides
fun provideWidgetManager(manager: WidgetManagerImpl): WidgetManager = manager
// Mapper
@Provides
fun provideCursorToContact(mapper: CursorToContactImpl): CursorToContact = mapper
@Provides
fun provideCursorToConversation(mapper: CursorToConversationImpl): CursorToConversation = mapper
@Provides
fun provideCursorToMessage(mapper: CursorToMessageImpl): CursorToMessage = mapper
@Provides
fun provideCursorToPart(mapper: CursorToPartImpl): CursorToPart = mapper
@Provides
fun provideCursorToRecipient(mapper: CursorToRecipienImpl): CursorToRecipient = mapper
// Repository
@Provides
fun provideContactRepository(repository: ContactRepositoryImpl): ContactRepository = repository
@Provides
fun provideMessageRepository(repository: MessageRepositoryImpl): MessageRepository = repository
@Provides
fun provideSyncRepository(repository: SyncRepositoryImpl): SyncRepository = repository
}
@@ -0,0 +1,138 @@
/*
* 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 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 io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import javax.inject.Inject
class BillingManager @Inject constructor(context: Context) : PurchasesUpdatedListener {
enum class UpgradeStatus { REGULAR, UPGRADED }
companion object {
const val SKU_PLUS = "remove_ads"
const val SKU_PLUS_DONATE = "qksms_plus_donate"
}
val products: Observable<List<SkuDetails>> = BehaviorSubject.create()
val plusStatus: Observable<UpgradeStatus>
private val skus = listOf(SKU_PLUS, SKU_PLUS_DONATE)
private val purchaseList = mutableListOf<Purchase>()
private val purchaseListObservable: Observable<List<Purchase>> = BehaviorSubject.create()
private val billingClient: BillingClient = BillingClient.newBuilder(context).setListener(this).build()
private var isServiceConnected = false
init {
startServiceConnection {
queryPurchases()
querySkuDetailsAsync()
}
plusStatus = purchaseListObservable
.map { purchases ->
when {
purchases.any { it.sku == SKU_PLUS } -> UpgradeStatus.UPGRADED
purchases.any { it.sku == SKU_PLUS_DONATE } -> UpgradeStatus.UPGRADED
else -> UpgradeStatus.REGULAR
}
}
}
private fun queryPurchases() {
executeServiceRequest {
val purchasesResult = billingClient.queryPurchases(SkuType.INAPP)
// Handle purchase result
purchaseList.clear()
purchaseList.addAll(purchasesResult.purchasesList)
(this.purchaseListObservable as Subject).onNext(purchaseList)
}
}
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>?) {
when (resultCode) {
BillingResponse.OK -> {
purchaseList.clear()
purchases?.let { purchaseList.addAll(it) }
(this.purchaseListObservable as Subject).onNext(purchaseList)
}
else -> {
// Ignored
}
}
}
}
@@ -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 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,235 @@
/*
* 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 common.util
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.support.annotation.ColorRes
import android.view.View
import com.moez.QKSMS.R
import io.reactivex.Observable
import io.reactivex.rxkotlin.Observables
import util.Preferences
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class Colors @Inject constructor(private val context: Context, private val prefs: Preferences) {
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(getColor(R.color.textPrimaryDark))
private val secondaryTextLuminance = measureLuminance(getColor(R.color.textSecondaryDark))
private val tertiaryTextLuminance = measureLuminance(getColor(R.color.textTertiaryDark))
val theme = themeForConversation()
val appThemeResources = Observables.combineLatest(prefs.night.asObservable(), prefs.black.asObservable(),
{ night, black ->
when {
night && black -> R.style.AppThemeBlack
night && !black -> R.style.AppThemeDark
else -> R.style.AppThemeLight
}
})
val popupThemeResource = Observables.combineLatest(prefs.night.asObservable(), prefs.black.asObservable(),
{ night, black ->
when {
night && black -> R.style.PopupThemeBlack
night && !black -> R.style.PopupThemeDark
else -> R.style.PopupThemeLight
}
})
@SuppressLint("InlinedApi")
val statusBarIcons: Observable<Int> = prefs.night.asObservable()
.map { night -> night || Build.VERSION.SDK_INT < Build.VERSION_CODES.M }
.map { lightIcons -> if (lightIcons) 0 else View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR }
.distinctUntilChanged()
val statusBar: Observable<Int> = Observables.combineLatest(prefs.night.asObservable(), prefs.black.asObservable(),
{ night, black ->
when {
night && black -> R.color.black
night && !black -> R.color.statusBarDark
else -> R.color.statusBarLight
}
})
.map { res -> getColor(res) }
.distinctUntilChanged()
val toolbarColor: Observable<Int> = Observables.combineLatest(prefs.night.asObservable(), prefs.black.asObservable(),
{ night, black ->
when {
night && black -> R.color.black
night && !black -> R.color.toolbarDark
else -> R.color.toolbarLight
}
})
.map { res -> getColor(res) }
.distinctUntilChanged()
val background: Observable<Int> = Observables.combineLatest(prefs.night.asObservable(), prefs.black.asObservable(),
{ night, black ->
when {
night && black -> R.color.black
night && !black -> R.color.backgroundDark
else -> R.color.white
}
})
.map { res -> getColor(res) }
.distinctUntilChanged()
val field: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.fieldDark else R.color.fieldLight }
.map { res -> getColor(res) }
.distinctUntilChanged()
val composeBackground: Observable<Int> = Observables.combineLatest(prefs.night.asObservable(), prefs.black.asObservable(),
{ night, black ->
when {
night && black -> R.color.black
night && !black -> R.color.backgroundDark
else -> R.color.backgroundLight
}
})
.map { res -> getColor(res) }
.distinctUntilChanged()
val separator: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.separatorDark else R.color.separatorLight }
.map { res -> getColor(res) }
.distinctUntilChanged()
val textPrimary: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.textPrimaryDark else R.color.textPrimary }
.map { res -> getColor(res) }
.distinctUntilChanged()
val textSecondary: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.textSecondaryDark else R.color.textSecondary }
.map { res -> getColor(res) }
.distinctUntilChanged()
val textTertiary: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.textTertiaryDark else R.color.textTertiary }
.map { res -> getColor(res) }
.distinctUntilChanged()
val textPrimaryOnTheme = textPrimaryOnThemeForConversation()
val textSecondaryOnTheme = textSecondaryOnThemeForConversation()
val textTertiaryOnTheme = textTertiaryOnThemeForConversation()
val bubble: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.bubbleDark else R.color.bubbleLight }
.map { res -> getColor(res) }
.distinctUntilChanged()
val switchThumbEnabled: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.switchThumbEnabledDark else R.color.switchThumbEnabledLight }
.map { res -> getColor(res) }
.distinctUntilChanged()
val switchThumbDisabled: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.switchThumbDisabledDark else R.color.switchThumbDisabledLight }
.map { res -> getColor(res) }
.distinctUntilChanged()
val switchTrackEnabled: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.switchTrackEnabledDark else R.color.switchTrackEnabledLight }
.map { res -> getColor(res) }
.distinctUntilChanged()
val switchTrackDisabled: Observable<Int> = prefs.night.asObservable()
.map { night -> if (night) R.color.switchTrackDisabledDark else R.color.switchTrackDisabledLight }
.map { res -> getColor(res) }
.distinctUntilChanged()
fun themeForConversation(threadId: Long = 0): Observable<Int> = prefs.theme(threadId)
.asObservable()
.distinctUntilChanged()
fun textPrimaryOnThemeForConversation(threadId: Long = 0): Observable<Int> = themeForConversation(threadId)
.map { theme -> measureLuminance(theme) }
.map { themeLuminance -> primaryTextLuminance / themeLuminance }
.map { contrastRatio -> contrastRatio < minimumContrastRatio }
.map { contrastRatio -> if (contrastRatio) R.color.textPrimary else R.color.textPrimaryDark }
.map { res -> getColor(res) }
.distinctUntilChanged()
fun textSecondaryOnThemeForConversation(threadId: Long = 0): Observable<Int> = themeForConversation(threadId)
.map { theme -> measureLuminance(theme) }
.map { themeLuminance -> secondaryTextLuminance / themeLuminance }
.map { contrastRatio -> contrastRatio < minimumContrastRatio }
.map { contrastRatio -> if (contrastRatio) R.color.textSecondary else R.color.textSecondaryDark }
.map { res -> getColor(res) }
.distinctUntilChanged()
fun textTertiaryOnThemeForConversation(threadId: Long = 0): Observable<Int> = themeForConversation(threadId)
.map { theme -> measureLuminance(theme) }
.map { themeLuminance -> tertiaryTextLuminance / themeLuminance }
.map { contrastRatio -> contrastRatio < minimumContrastRatio }
.map { contrastRatio -> if (contrastRatio) R.color.textTertiary else R.color.textTertiaryDark }
.map { res -> getColor(res) }
.distinctUntilChanged()
private fun getColor(@ColorRes res: Int): Int {
return context.resources.getColor(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 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 common.di.appComponent
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import repository.ContactRepository
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,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 common.util
import android.content.Context
import android.text.format.DateFormat
import common.util.extensions.isSameDay
import common.util.extensions.isSameWeek
import 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', 'H').replace(" a".toRegex(), ""), Locale.US)
else SimpleDateFormat(pattern, Locale.US)
}
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)
}
fun formatTime(hour: Int, minute: Int): String {
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, hour)
calendar.set(Calendar.MINUTE, minute)
val simpleDateFormat = getFormatter("h:mm a")
return simpleDateFormat.format(calendar.time)
}
fun parseTime(time: String): Calendar {
val simpleDateFormat = if (time.contains(" ")) getFormatter("h:mm a") else SimpleDateFormat("H:mm", Locale.US)
return Calendar.getInstance().apply { this.time = simpleDateFormat.parse(time) }
}
}
@@ -0,0 +1,59 @@
/*
* 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 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)
if (lato == null) {
pendingCallbacks += 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 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 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,107 @@
/*
* 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 common.util
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import presentation.receiver.NightModeReceiver
import util.Preferences
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class NightModeManager @Inject constructor(
private val context: Context,
private val dateFormatter: DateFormatter,
private val prefs: Preferences) {
fun updateCurrentTheme() {
// If night mode is not on auto, then there's nothing to do here
if (prefs.nightMode.get() != Preferences.NIGHT_MODE_AUTO) {
return
}
val nightStartTime = getPreviousInstanceOfTime(prefs.nightStart.get())
val nightEndTime = getPreviousInstanceOfTime(prefs.nightEnd.get())
// If the last nightStart was more recent than the last nightEnd, then it's night time
prefs.night.set(nightStartTime > nightEndTime)
}
fun updateNightMode(mode: Int) {
prefs.nightMode.set(mode)
// If it's not on auto mode, set the appropriate night mode
if (mode != Preferences.NIGHT_MODE_AUTO) {
prefs.night.set(mode == Preferences.NIGHT_MODE_ON)
}
updateAlarms()
}
fun updateAlarms() {
val dayCalendar = createCalendar(prefs.nightEnd.get())
val day = Intent(context, NightModeReceiver::class.java)
val dayIntent = PendingIntent.getBroadcast(context, 0, day, 0)
val nightCalendar = createCalendar(prefs.nightStart.get())
val night = Intent(context, NightModeReceiver::class.java)
val nightIntent = PendingIntent.getBroadcast(context, 1, night, 0)
context.sendBroadcast(day)
context.sendBroadcast(night)
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
if (prefs.nightMode.get() == Preferences.NIGHT_MODE_AUTO) {
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, dayCalendar.timeInMillis, AlarmManager.INTERVAL_DAY, dayIntent)
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, nightCalendar.timeInMillis, AlarmManager.INTERVAL_DAY, nightIntent)
} else {
alarmManager.cancel(dayIntent)
alarmManager.cancel(nightIntent)
}
}
private fun createCalendar(time: String): Calendar {
val calendar = dateFormatter.parseTime(time)
return Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY))
set(Calendar.MINUTE, calendar.get(Calendar.MINUTE))
}
}
/**
* Returns a Calendar set to the most recent occurrence of this time
*/
private fun getPreviousInstanceOfTime(time: String): Calendar {
val currentTime = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(10)
val calendar = createCalendar(time)
while (calendar.timeInMillis > currentTime) {
calendar.add(Calendar.DAY_OF_YEAR, -1)
}
return calendar
}
}
@@ -0,0 +1,252 @@
/*
* 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 common.util
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
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 com.moez.QKSMS.R
import presentation.feature.compose.ComposeActivity
import presentation.receiver.MarkReadReceiver
import presentation.receiver.MarkSeenReceiver
import presentation.receiver.RemoteMessagingReceiver
import repository.MessageRepository
import util.Preferences
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class NotificationManagerImpl @Inject constructor(
private val context: Context,
private val prefs: Preferences,
private val colors: Colors,
private val messageRepo: MessageRepository
): 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 = messageRepo.getConversation(threadId) ?: return
val style = NotificationCompat.MessagingStyle("Me")
messages.forEach { message ->
val name = if (message.isMe()) null else conversation.getTitle()
style.addMessage(message.getSummary(), message.date, name)
}
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_done_black_24dp, context.getString(R.string.notification_read), readPI)
val notification = NotificationCompat.Builder(context, getChannelIdForNotification(threadId))
.setColor(colors.themeForConversation(threadId).blockingFirst())
.setPriority(NotificationManagerCompat.IMPORTANCE_MAX)
.setSmallIcon(R.drawable.ic_notification)
.setNumber(messages.size)
.setAutoCancel(true)
.setContentIntent(contentPI)
.setDeleteIntent(seenPI)
.addAction(readAction)
.setStyle(style)
.setSound(Uri.parse(prefs.ringtone(threadId).get()))
.setLights(Color.WHITE, 500, 2000)
.setVibrate(if (prefs.vibration(threadId).get()) VIBRATE_PATTERN else longArrayOf(0))
if (Build.VERSION.SDK_INT >= 24) {
notification.addAction(getReplyAction(conversation.recipients[0]?.address.orEmpty(), threadId))
}
notificationManager.notify(threadId.toInt(), notification.build())
}
override fun notifyFailed(msgId: Long) {
val message = messageRepo.getMessage(msgId)
if (message == null || !message.isFailedMessage()) {
return
}
val threadId = message.threadId
val conversation = messageRepo.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() + 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.themeForConversation(threadId).blockingFirst())
.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(address: String, threadId: Long): NotificationCompat.Action {
val replyIntent = Intent(context, RemoteMessagingReceiver::class.java)
.putExtra("address", address)
.putExtra("threadId", threadId)
val replyPI = PendingIntent.getBroadcast(context, threadId.toInt() + 40000, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val responseSet = arrayListOf("Hello", "Hey").toTypedArray().sortedArray()
val remoteInput = RemoteInput.Builder("body")
.setLabel(context.getString(R.string.notification_reply))
.setChoices(responseSet)
.build()
return NotificationCompat.Action.Builder(
R.drawable.ic_reply_black_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
messageRepo.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,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 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,36 @@
/*
* 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 common.util.extensions
import android.content.Context
import android.support.annotation.StringRes
import android.support.v4.content.ContextCompat
import android.widget.Toast
fun Context.getColorCompat(colorRes: Int): Int {
return ContextCompat.getColor(this, colorRes)
}
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()
}
@@ -0,0 +1,37 @@
/*
* 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 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)
}
}
@@ -0,0 +1,76 @@
/*
* 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 common.util.extensions
import android.content.Context
import android.content.res.ColorStateList
import android.support.v4.view.ViewPager
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import io.reactivex.Observable
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 View.setBackgroundTint(color: Int) {
backgroundTintList = ColorStateList.valueOf(color)
}
fun View.setMargins(left: Int? = null, top: Int? = null, right: Int? = null, bottom: Int? = null) {
val lp = layoutParams as? ViewGroup.MarginLayoutParams ?: return
lp.setMargins(
left ?: lp.leftMargin,
top ?: lp.topMargin,
right ?: lp.rightMargin,
bottom ?: lp.rightMargin)
layoutParams = lp
}
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
}
data class PageScroll(val position: Int, val offset: Float)
fun ViewPager.pageScrolled(): Observable<PageScroll> {
return Observable.create<PageScroll> { emitter ->
addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
emitter.onNext(PageScroll(position, positionOffset))
}
})
}
}
@@ -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 common.util.filter
import model.Contact
import javax.inject.Inject
class ContactFilter @Inject constructor(private val phoneNumberFilter: PhoneNumberFilter) : Filter<Contact>() {
override fun filter(item: Contact, query: CharSequence): Boolean {
return item.name.contains(query, true) || // Name
item.numbers.map { it.address }.any { address -> phoneNumberFilter.filter(address, query) } // Number
}
}
@@ -0,0 +1,30 @@
/*
* 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 common.util.filter
import model.Conversation
import javax.inject.Inject
class ConversationFilter @Inject constructor(private val recipientFilter: RecipientFilter) : Filter<Conversation>() {
override fun filter(item: Conversation, query: CharSequence): Boolean {
return item.recipients.any { recipient -> recipientFilter.filter(recipient, query) }
}
}
@@ -0,0 +1,25 @@
/*
* 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 common.util.filter
abstract class Filter<in T> {
abstract fun filter(item: T, query: CharSequence): Boolean
}
@@ -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 common.util.filter
import android.telephony.PhoneNumberUtils
import javax.inject.Inject
class PhoneNumberFilter @Inject constructor() : Filter<String>() {
override fun filter(item: String, query: CharSequence): Boolean {
val allCharactersDialable = query.all { PhoneNumberUtils.isReallyDialable(it) }
return allCharactersDialable && (PhoneNumberUtils.compare(item, query.toString()) ||
PhoneNumberUtils.stripSeparators(item).contains(PhoneNumberUtils.stripSeparators(query.toString())))
}
}
@@ -0,0 +1,35 @@
/*
* 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 common.util.filter
import model.Recipient
import javax.inject.Inject
class RecipientFilter @Inject constructor(
private val contactFilter: ContactFilter,
private val phoneNumberFilter: PhoneNumberFilter)
: Filter<Recipient>() {
override fun filter(item: Recipient, query: CharSequence) = when {
item.contact?.let { contactFilter.filter(it, query) } == true -> true
phoneNumberFilter.filter(item.address, query) -> true
else -> false
}
}
@@ -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 interactor
import com.f2prateek.rx.preferences2.RxSharedPreferences
import common.util.NightModeManager
import util.Preferences
import io.reactivex.Flowable
import javax.inject.Inject
/**
* When upgrading from 2.7.3 to 3.0, migrate the preferences
*/
class MigratePreferences @Inject constructor(
private val nightModeManager: NightModeManager,
private val prefs: Preferences,
private val rxPrefs: RxSharedPreferences
) : Interactor<Unit>() {
override fun buildObservable(params: Unit): Flowable<*> {
return Flowable.just(rxPrefs.getBoolean("pref_key_welcome_seen", false))
.filter { seen -> seen.get() } // Only proceed if this value is true. It will be set false at the end
.doOnNext {
// Theme
val defaultTheme = prefs.theme().get().toString()
val oldTheme = rxPrefs.getString("pref_key_theme", defaultTheme).get()
prefs.theme().set(Integer.parseInt(oldTheme))
}
.doOnNext {
// Night mode
val background = rxPrefs.getString("pref_key_background", "light").get()
val autoNight = rxPrefs.getBoolean("pref_key_night_auto", false).get()
when {
autoNight -> nightModeManager.updateNightMode(Preferences.NIGHT_MODE_AUTO)
background == "light" -> nightModeManager.updateNightMode(Preferences.NIGHT_MODE_OFF)
background == "grey" -> nightModeManager.updateNightMode(Preferences.NIGHT_MODE_ON)
background == "black" -> {
nightModeManager.updateNightMode(Preferences.NIGHT_MODE_ON)
prefs.black.set(true)
}
}
}
.doOnNext {
// Delivery
prefs.delivery.set(rxPrefs.getBoolean("pref_key_delivery", prefs.delivery.get()).get())
}
.doOnNext {
// Unicode
prefs.unicode.set(rxPrefs.getBoolean("pref_key_strip_unicode", prefs.unicode.get()).get())
}
.doOnNext { seen -> seen.delete() } // Clear this value so that we don't need to migrate again
}
}
@@ -0,0 +1,46 @@
/*
* 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 interactor
import android.net.Uri
import io.reactivex.Flowable
import manager.NotificationManager
import repository.MessageRepository
import repository.SyncRepository
import util.extensions.mapNotNull
import javax.inject.Inject
class ReceiveMms @Inject constructor(
private val syncManager: SyncRepository,
private val messageRepo: MessageRepository,
private val notificationManager: NotificationManager,
private val updateBadge: UpdateBadge
) : Interactor<Uri>() {
override fun buildObservable(params: Uri): Flowable<*> {
return Flowable.just(params)
.flatMap { uri -> syncManager.syncMessage(uri) } // Sync the message
.mapNotNull { message -> messageRepo.getOrCreateConversation(message.threadId) } // Map message to conversation
.filter { conversation -> !conversation.blocked } // Don't notify for blocked conversations
.doOnNext { conversation -> if (conversation.archived) messageRepo.markUnarchived(conversation.id) } // Unarchive conversation if necessary
.doOnNext { conversation -> notificationManager.update(conversation.id) } // Update the notification
.flatMap { updateBadge.buildObservable(Unit) } // Update the badge
}
}
@@ -0,0 +1,53 @@
/*
* 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 interactor
import android.telephony.SmsMessage
import io.reactivex.Flowable
import manager.NotificationManager
import repository.MessageRepository
import util.extensions.mapNotNull
import javax.inject.Inject
class ReceiveSms @Inject constructor(
private val messageRepo: MessageRepository,
private val notificationManager: NotificationManager,
private val updateBadge: UpdateBadge
) : Interactor<Array<SmsMessage>>() {
override fun buildObservable(params: Array<SmsMessage>): Flowable<*> {
return Flowable.just(params)
.filter { it.isNotEmpty() }
.map { messages ->
val address = messages[0].displayOriginatingAddress
val time = messages[0].timestampMillis
val body: String = messages
.map { message -> message.displayMessageBody }
.reduce { body, new -> body + new }
messageRepo.insertReceivedSms(address, body, time) // Add the message to the db
}
.mapNotNull { message -> messageRepo.getOrCreateConversation(message.threadId) } // Map message to conversation
.filter { conversation -> !conversation.blocked } // Don't notify for blocked conversations
.doOnNext { conversation -> if (conversation.archived) messageRepo.markUnarchived(conversation.id) } // Unarchive conversation if necessary
.doOnNext { conversation -> notificationManager.update(conversation.id) } // Update the notification
.flatMap { updateBadge.buildObservable(Unit) } // Update the badge
}
}
@@ -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 interactor
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import com.klinker.android.send_message.Message
import com.klinker.android.send_message.Settings
import com.klinker.android.send_message.Transaction
import com.mlsdev.rximagepicker.RxImageConverters
import io.reactivex.Flowable
import repository.MessageRepository
import util.Preferences
import java.io.ByteArrayOutputStream
import javax.inject.Inject
class SendMessage @Inject constructor(
private val context: Context,
private val prefs: Preferences,
private val messageRepo: MessageRepository
) : Interactor<SendMessage.Params>() {
data class Params(val threadId: Long, val addresses: List<String>, val body: String, val attachments: List<Uri> = listOf())
override fun buildObservable(params: Params): Flowable<Unit> {
return Flowable.just(Unit)
.filter { params.addresses.isNotEmpty() }
.doOnNext {
if (params.addresses.size == 1 && params.attachments.isEmpty()) {
messageRepo.sendSmsAndPersist(params.threadId, params.addresses.first(), params.body)
} else {
sendMms(params.threadId, params.addresses, params.body, params.attachments)
}
}
.doOnNext { messageRepo.markUnarchived(params.threadId) }
}
private fun sendMms(threadId: Long, addresses: List<String>, body: String, attachments: List<Uri>) {
val settings = Settings()
val message = Message(body, addresses.toTypedArray())
val bitmaps = attachments.map { uri -> RxImageConverters.uriToBitmap(context, uri).blockingFirst() }
val totalBytes = bitmaps.sumBy { it.allocationByteCount }
bitmaps
.map { bitmap ->
val byteRatio = bitmap.allocationByteCount / totalBytes.toFloat()
shrink(bitmap, (prefs.mmsSize.get() * 1024 * byteRatio).toInt())
}
.forEach { bitmap -> message.addMedia(bitmap, "image/jpeg") }
val transaction = Transaction(context, settings)
transaction.sendNewMessage(message, threadId)
}
private fun shrink(src: Bitmap, maxBytes: Int): ByteArray {
var step = 0.0
val factor = 0.5
val quality = 60
val height = src.height
val width = src.width
val stream = ByteArrayOutputStream()
src.compress(Bitmap.CompressFormat.JPEG, 100, stream)
while (maxBytes > 0 && stream.size() > maxBytes) {
step++
val scale = Math.pow(factor, step)
stream.reset()
Bitmap.createScaledBitmap(src, (width * scale).toInt(), (height * scale).toInt(), false)
.compress(Bitmap.CompressFormat.JPEG, quality, stream)
}
return stream.toByteArray()
}
}
@@ -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 presentation.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,90 @@
/*
* 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 presentation.common
import android.content.Context
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 common.util.Colors
import common.util.extensions.setTint
import common.util.extensions.setVisible
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.menu_list_item.view.*
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
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 view = LayoutInflater.from(context).inflate(R.layout.menu_list_item, parent, false)
disposables += colors.theme
.subscribe { view.check.setTint(it) }
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.setVisible(menuItem.actionId == selectedItem)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
disposables.clear()
}
}
@@ -0,0 +1,198 @@
/*
* 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 presentation.common
import android.app.Activity
import android.app.ActivityOptions
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
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 manager.NotificationManager
import presentation.feature.blocked.BlockedActivity
import presentation.feature.blocked.BlockedViewModel
import presentation.feature.compose.ComposeActivity
import presentation.feature.compose.ComposeViewModel
import presentation.feature.conversationinfo.ConversationInfoActivity
import presentation.feature.conversationinfo.ConversationInfoViewModel
import presentation.feature.gallery.GalleryActivity
import presentation.feature.gallery.GalleryViewModel
import presentation.feature.main.MainViewModel
import presentation.feature.notificationprefs.NotificationPrefsActivity
import presentation.feature.notificationprefs.NotificationPrefsViewModel
import presentation.feature.plus.PlusActivity
import presentation.feature.plus.PlusViewModel
import presentation.feature.settings.SettingsActivity
import presentation.feature.settings.SettingsViewModel
import presentation.feature.setup.SetupActivity
import presentation.feature.setup.SetupViewModel
import presentation.feature.themepicker.ThemePickerActivity
import presentation.feature.themepicker.ThemePickerViewModel
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 showSetupActivity() {
val intent = Intent(context, SetupActivity::class.java)
startActivity(intent)
}
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) {
val intent = Intent(context, ComposeActivity::class.java)
intent.putExtra(Intent.EXTRA_TEXT, body)
startActivity(intent)
}
fun showConversation(threadId: Long) {
val intent = Intent(context, ComposeActivity::class.java)
intent.putExtra("threadId", threadId)
startActivity(intent)
}
fun showConversationInfo(threadId: Long) {
val intent = Intent(context, ConversationInfoActivity::class.java)
intent.putExtra("threadId", threadId)
startActivity(intent)
}
fun showImage(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 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 showSupport() {
val intent = Intent(Intent.ACTION_SENDTO)
intent.data = Uri.parse("mailto:")
intent.putExtra(Intent.EXTRA_EMAIL, arrayOf("team@qklabs.com"))
startActivityExternal(intent)
}
fun addContact(address: String) {
val uri = Uri.parse("tel: $address")
val intent = Intent(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT, uri)
startActivityExternal(intent)
}
fun showNotificationSettings(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)
} else {
val intent = Intent(context, NotificationPrefsActivity::class.java)
intent.putExtra("threadId", threadId)
startActivity(intent)
}
}
class ViewModelFactory(private val intent: Intent) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return when (modelClass) {
MainViewModel::class.java -> MainViewModel()
PlusViewModel::class.java -> PlusViewModel()
SetupViewModel::class.java -> SetupViewModel()
ComposeViewModel::class.java -> ComposeViewModel(intent)
ConversationInfoViewModel::class.java -> ConversationInfoViewModel(intent)
GalleryViewModel::class.java -> GalleryViewModel(intent)
NotificationPrefsViewModel::class.java -> NotificationPrefsViewModel(intent)
SettingsViewModel::class.java -> SettingsViewModel()
BlockedViewModel::class.java -> BlockedViewModel()
ThemePickerViewModel::class.java -> ThemePickerViewModel(intent)
else -> throw IllegalArgumentException("Invalid ViewModel class. If this is a new ViewModel, please add it to Navigator.kt")
} as T
}
}
}
@@ -0,0 +1,79 @@
/*
* 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 presentation.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 presentation.common.base
import android.annotation.SuppressLint
import android.arch.lifecycle.ViewModelProviders
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.*
import presentation.common.Navigator
import kotlin.reflect.KClass
abstract class QkActivity<VM : QkViewModel<*, *>> : AppCompatActivity() {
protected abstract val viewModelClass: KClass<VM>
protected val viewModel: VM by lazy {
ViewModelProviders.of(this, Navigator.ViewModelFactory(intent))[viewModelClass.java]
}
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(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
}
}
@@ -0,0 +1,74 @@
/*
* 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 presentation.common.base
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
/**
* 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) {
val diff = DiffUtil.calculateDiff(getDiffUtilCallback(field, value))
field = value
diff.dispatchUpdatesTo(this)
onDatasetChanged()
}
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
}
}
open protected fun areItemsTheSame(old: T, new: T): Boolean {
return old == new
}
open protected fun areContentsTheSame(old: T, new: T): Boolean {
return old == new
}
}
@@ -0,0 +1,107 @@
/*
* 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 presentation.common.base
import android.annotation.SuppressLint
import android.arch.lifecycle.Lifecycle
import android.os.Bundle
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.util.Colors
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<VM : QkViewModel<*, *>> : QkActivity<VM>() {
@Inject lateinit var colors: Colors
/**
* 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.themeForConversation(threadId) }
@SuppressLint("InlinedApi")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
colors.appThemeResources
.autoDisposable(scope())
.subscribe { res -> setTheme(res) }
colors.statusBarIcons
.autoDisposable(scope())
.subscribe { systemUiVisibility -> window.decorView.systemUiVisibility = systemUiVisibility }
colors.statusBar
.autoDisposable(scope())
.subscribe { color -> window.statusBarColor = color }
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
// Update the colours of the menu items
Observables.combineLatest(menu, theme, colors.textTertiary, { menu, theme, textTertiary ->
(0 until menu.size())
.map { position -> menu.getItem(position) }
.forEach { menuItem ->
menuItem?.icon?.run {
setTint(when (menuItem.itemId) {
R.id.info -> textTertiary
else -> theme
})
menuItem.icon = this
}
}
}).autoDisposable(scope(Lifecycle.Event.ON_DESTROY)).subscribe()
colors.textTertiary
.doOnNext { color -> toolbar?.overflowIcon = toolbar?.overflowIcon?.apply { setTint(color) } }
.doOnNext { color -> toolbar?.navigationIcon = toolbar?.navigationIcon?.apply { setTint(color) } }
.autoDisposable(scope(Lifecycle.Event.ON_DESTROY))
.subscribe()
colors.popupThemeResource
.autoDisposable(scope(Lifecycle.Event.ON_DESTROY))
.subscribe { res -> toolbar?.popupTheme = res }
colors.toolbarColor
.autoDisposable(scope(Lifecycle.Event.ON_DESTROY))
.subscribe { color -> toolbar?.setBackgroundColor(color) }
}
}
@@ -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 presentation.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 presentation.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 presentation.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,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 presentation.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.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.uber.autodispose.android.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.Colors
import common.util.GlideApp
import common.util.extensions.setTint
import kotlinx.android.synthetic.main.avatar_view.view.*
import model.Contact
import presentation.common.Navigator
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
var contact: Contact? = null
set(value) {
field = value
updateView()
}
init {
if (!isInEditMode) {
appComponent.inject(this)
}
View.inflate(context, R.layout.avatar_view, this)
setBackgroundResource(R.drawable.circle)
clipToOutline = true
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (!isInEditMode) {
colors.themeForConversation(threadId)
.autoDisposable(scope())
.subscribe { color -> background.setTint(color) }
colors.textPrimaryOnTheme
.autoDisposable(scope())
.subscribe { color -> icon.setTint(color) }
clicks()
.autoDisposable(scope())
.subscribe {
if (contact?.lookupKey.isNullOrEmpty()) {
contact?.numbers?.firstOrNull()?.let { number ->
navigator.addContact(number.address)
}
} else {
val key = contact?.lookupKey
val uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, key)
ContactsContract.QuickContact.showQuickContact(context, this@AvatarView, uri,
ContactsContract.QuickContact.MODE_MEDIUM, null)
}
}
}
}
override fun onFinishInflate() {
super.onFinishInflate()
if (!isInEditMode) {
updateView()
}
}
private fun updateView() {
if (contact?.name.orEmpty().isNotEmpty()) {
initial.text = contact?.name?.substring(0, 1)
icon.visibility = GONE
} else {
initial.text = null
icon.visibility = VISIBLE
}
photo.setImageDrawable(null)
contact?.numbers?.firstOrNull()?.address?.let { address ->
GlideApp.with(photo).load(PhoneNumberUtils.stripSeparators(address)).into(photo)
}
}
}
@@ -0,0 +1,64 @@
/*
* 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 presentation.common.widget
import android.content.Context
import android.support.constraint.ConstraintLayout
import android.util.AttributeSet
import android.view.View
import com.moez.QKSMS.R
import kotlinx.android.synthetic.main.group_avatar_view.view.*
import model.Contact
class GroupAvatarView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ConstraintLayout(context, attrs) {
var contacts: List<Contact> = 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 (!isInEditMode) {
updateView()
}
}
private fun updateView() {
avatars.forEachIndexed { index, avatar ->
avatar.visibility = if (contacts.size > index) View.VISIBLE else View.GONE
avatar.contact = if (contacts.size > index) contacts[index] else null
}
}
}
@@ -0,0 +1,64 @@
/*
* 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 presentation.common.widget
import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView
import android.widget.LinearLayout
import common.di.appComponent
import common.util.GlideApp
import common.util.extensions.setVisible
import model.MmsPart
import presentation.common.Navigator
import javax.inject.Inject
class MmsPreviewView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : LinearLayout(context, attrs) {
@Inject lateinit var navigator: Navigator
var parts: List<MmsPart> = ArrayList()
set(value) {
field = value
updateView()
}
init {
appComponent.inject(this)
orientation = LinearLayout.VERTICAL
}
private fun updateView() {
val images = parts.filter { it.image != null }
setVisible(images.isNotEmpty())
if (childCount > 0) {
removeAllViews()
}
images.forEach { image ->
addView(ImageView(context).apply {
layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
GlideApp.with(context).load(image.image).fitCenter().into(this)
setOnClickListener { navigator.showImage(image.id) }
})
}
}
}
@@ -0,0 +1,97 @@
/*
* 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 presentation.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.uber.autodispose.android.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.Colors
import common.util.extensions.forEach
import io.reactivex.rxkotlin.Observables
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
var pager: ViewPager? = null
set(value) {
if (field !== value) {
field = value
recreate()
}
}
init {
if (!isInEditMode) appComponent.inject(this)
}
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)
}
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))
Observables
.combineLatest(colors.theme, colors.textSecondary, { theme, textSecondary ->
ColorStateList(states, intArrayOf(theme, textSecondary))
})
.autoDisposable(scope())
.subscribe { colorStateList ->
childCount.forEach { index ->
(getChildAt(index) as? TextView)?.setTextColor(colorStateList)
}
}
colors.toolbarColor
.autoDisposable(scope())
.subscribe { color -> setBackgroundColor(color) }
}
}
@@ -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 presentation.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.uber.autodispose.android.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.Colors
import common.util.extensions.getColorCompat
import common.util.extensions.setTint
import common.util.extensions.setVisible
import kotlinx.android.synthetic.main.preference_view.view.*
import javax.inject.Inject
class PreferenceView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : LinearLayoutCompat(context, attrs) {
@Inject lateinit var colors: Colors
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(R.drawable.ripple)
orientation = HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
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()
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (isInEditMode) {
icon.setTint(context.getColorCompat(R.color.textSecondary))
} else {
colors.textSecondary
.autoDisposable(scope())
.subscribe { icon.setTint(it) }
}
}
}
@@ -0,0 +1,84 @@
/*
* 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 presentation.common.widget
import android.content.Context
import android.graphics.Typeface
import android.util.AttributeSet
import android.widget.EditText
import com.moez.QKSMS.R
import com.uber.autodispose.android.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.Colors
import common.util.FontProvider
import io.reactivex.Observable
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 colors: Colors
@Inject lateinit var fontProvider: FontProvider
private var textColorObservable: Observable<Int>? = null
private var textColorHintObservable: Observable<Int>? = null
init {
appComponent.inject(this)
fontProvider.getLato { setTypeface(it, typeface?.style ?: Typeface.NORMAL) }
context.obtainStyledAttributes(attrs, R.styleable.QkEditText)?.run {
textColorObservable = when (getInt(R.styleable.QkEditText_textColor, -1)) {
0 -> colors.textPrimary
1 -> colors.textSecondary
2 -> colors.textTertiary
3 -> colors.textPrimaryOnTheme
4 -> colors.textSecondaryOnTheme
5 -> colors.textTertiaryOnTheme
else -> null
}
textColorHintObservable = when (getInt(R.styleable.QkEditText_textColorHint, -1)) {
0 -> colors.textPrimary
1 -> colors.textSecondary
2 -> colors.textTertiary
else -> null
}
recycle()
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
textColorObservable
?.autoDisposable(scope())
?.subscribe { color -> setTextColor(color) }
textColorHintObservable
?.autoDisposable(scope())
?.subscribe { color -> setHintTextColor(color) }
}
}
@@ -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 presentation.common.widget
import android.content.Context
import android.content.res.ColorStateList
import android.support.v7.widget.SwitchCompat
import android.util.AttributeSet
import com.uber.autodispose.android.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.Colors
import common.util.extensions.withAlpha
import io.reactivex.rxkotlin.Observables
import javax.inject.Inject
class QkSwitch @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : SwitchCompat(context, attrs) {
@Inject lateinit var colors: Colors
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())
Observables.combineLatest(colors.theme, colors.switchThumbEnabled, colors.switchThumbDisabled,
{ color, enabled, disabled -> intArrayOf(disabled, color, enabled) })
.map { values -> ColorStateList(states, values) }
.autoDisposable(scope())
.subscribe { tintList -> thumbTintList = tintList }
Observables.combineLatest(colors.theme, colors.switchTrackEnabled, colors.switchTrackDisabled,
{ color, enabled, disabled -> intArrayOf(disabled, color.withAlpha(0x4D), enabled) })
.map { values -> ColorStateList(states, values) }
.autoDisposable(scope())
.subscribe { tintList -> trackTintList = tintList }
}
}
}
@@ -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 presentation.common.widget
import android.content.Context
import android.graphics.Typeface
import android.support.text.emoji.widget.EmojiAppCompatTextView
import android.util.AttributeSet
import com.moez.QKSMS.R
import common.di.appComponent
import common.util.Colors
import common.util.FontProvider
import common.util.extensions.getColorCompat
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import javax.inject.Inject
open class QkTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null)
: EmojiAppCompatTextView(context, attrs) {
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
}
@Inject lateinit var colors: Colors
@Inject lateinit var fontProvider: FontProvider
var textColorObservable: Observable<Int>? = null
set(value) {
field = value
updateSubscription()
}
private var textColorDisposable: Disposable? = null
set(value) {
field?.dispose()
field = value
}
init {
if (!isInEditMode) {
appComponent.inject(this)
fontProvider.getLato { setTypeface(it, typeface?.style ?: Typeface.NORMAL) }
}
context.obtainStyledAttributes(attrs, R.styleable.QkTextView)?.run {
val colorAttr = getInt(R.styleable.QkTextView_textColor, -1)
if (isInEditMode) {
setTextColor(context.getColorCompat(when (colorAttr) {
COLOR_PRIMARY -> R.color.textPrimary
COLOR_SECONDARY -> R.color.textSecondary
COLOR_TERTIARY -> R.color.textTertiary
COLOR_PRIMARY_ON_THEME -> R.color.textPrimaryDark
COLOR_SECONDARY_ON_THEME -> R.color.textSecondaryDark
COLOR_TERTIARY_ON_THEME -> R.color.textTertiaryDark
else -> R.color.textPrimary
}))
} else {
textColorObservable = when (colorAttr) {
COLOR_PRIMARY -> colors.textPrimary
COLOR_SECONDARY -> colors.textSecondary
COLOR_TERTIARY -> colors.textTertiary
COLOR_PRIMARY_ON_THEME -> colors.textPrimaryOnTheme
COLOR_SECONDARY_ON_THEME -> colors.textSecondaryOnTheme
COLOR_TERTIARY_ON_THEME -> colors.textTertiaryOnTheme
else -> null
}
}
recycle()
}
}
private fun updateSubscription() {
if (isAttachedToWindow) {
textColorDisposable = textColorObservable?.subscribe { color ->
setTextColor(color)
setLinkTextColor(color)
}
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
updateSubscription()
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
textColorDisposable?.dispose()
}
}
@@ -0,0 +1,53 @@
/*
* 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 presentation.common.widget
import android.content.Context
import android.util.AttributeSet
import android.view.View
import com.moez.QKSMS.R
import com.uber.autodispose.android.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.Colors
import common.util.extensions.getColorCompat
import javax.inject.Inject
class Separator @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
@Inject lateinit var colors: Colors
init {
if (!isInEditMode) {
appComponent.inject(this)
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (isInEditMode) {
setBackgroundColor(context.getColorCompat(R.color.separatorLight))
} else {
colors.separator
.autoDisposable(scope())
.subscribe { color -> setBackgroundColor(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 presentation.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 presentation.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)
}
}
}
@@ -0,0 +1,74 @@
/*
* 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 presentation.feature.blocked
import android.app.AlertDialog
import android.os.Bundle
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.extensions.setVisible
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.blocked_activity.*
import presentation.common.base.QkThemedActivity
import javax.inject.Inject
class BlockedActivity : QkThemedActivity<BlockedViewModel>(), BlockedView {
@Inject lateinit var blockedAdapter: BlockedAdapter
override val viewModelClass = BlockedViewModel::class
override val unblockIntent by lazy { blockedAdapter.unblock }
override val confirmUnblockIntent: Subject<Unit> = PublishSubject.create()
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.blocked_activity)
setTitle(R.string.blocked_title)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
colors.background
.autoDisposable(scope())
.subscribe { color -> window.decorView.setBackgroundColor(color) }
conversations.adapter = blockedAdapter
}
override fun render(state: BlockedState) {
blockedAdapter.flowable = state.data
empty.setVisible(state.empty)
}
override fun showUnblockDialog() {
AlertDialog.Builder(this)
.setTitle(R.string.blocked_unblock_dialog_title)
.setMessage(R.string.blocked_unblock_dialog_message)
.setPositiveButton(R.string.button_unblock, { _, _ -> confirmUnblockIntent.onNext(Unit) })
.setNegativeButton(R.string.button_cancel, null)
.show()
}
}
@@ -0,0 +1,55 @@
/*
* 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 presentation.feature.blocked
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.moez.QKSMS.R
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.blocked_list_item.view.*
import model.Contact
import model.Conversation
import model.PhoneNumber
import presentation.common.base.FlowableAdapter
import presentation.common.base.QkViewHolder
import javax.inject.Inject
class BlockedAdapter @Inject constructor(private val context: Context) : FlowableAdapter<Conversation>() {
val unblock: PublishSubject<Long> = PublishSubject.create()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
return QkViewHolder(LayoutInflater.from(context).inflate(R.layout.blocked_list_item, parent, false))
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val conversation = getItem(position)
val view = holder.itemView
view.setOnClickListener { unblock.onNext(conversation.id) }
view.avatars.contacts = conversation.recipients.map { recipient ->
recipient.contact ?: Contact().apply { numbers.add(PhoneNumber().apply { address = recipient.address }) }
}
view.title.text = conversation.getTitle()
}
}
@@ -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 presentation.feature.blocked
import io.reactivex.Flowable
import model.Conversation
data class BlockedState(
val data: Flowable<List<Conversation>>? = null,
val empty: Boolean = false
)
@@ -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 presentation.feature.blocked
import io.reactivex.Observable
import presentation.common.base.QkView
interface BlockedView : QkView<BlockedState> {
val unblockIntent: Observable<Long>
val confirmUnblockIntent: Observable<Unit>
fun showUnblockDialog()
}
@@ -0,0 +1,59 @@
/*
* 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 presentation.feature.blocked
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import interactor.MarkUnblocked
import io.reactivex.rxkotlin.withLatestFrom
import presentation.common.base.QkViewModel
import repository.MessageRepository
import javax.inject.Inject
class BlockedViewModel : QkViewModel<BlockedView, BlockedState>(BlockedState()) {
@Inject lateinit var markUnblocked: MarkUnblocked
@Inject lateinit var messageRepo: MessageRepository
init {
appComponent.inject(this)
val conversations = messageRepo.getBlockedConversations()
.doOnNext { conversations -> newState { it.copy(empty = conversations.isEmpty()) } }
newState { it.copy(data = conversations) }
}
override fun bindView(view: BlockedView) {
super.bindView(view)
// Show confirm unblock conversation dialog
view.unblockIntent
.autoDisposable(view.scope())
.subscribe { view.showUnblockDialog() }
// Unblock conversation
view.confirmUnblockIntent
.withLatestFrom(view.unblockIntent, { _, threadId -> threadId })
.autoDisposable(view.scope())
.subscribe { threadId -> markUnblocked.execute(threadId) }
}
}
@@ -0,0 +1,80 @@
/*
* 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 presentation.feature.compose
import android.content.Context
import android.net.Uri
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import common.util.Colors
import common.util.extensions.setBackgroundTint
import common.util.extensions.setTint
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.attachment_list_item.view.*
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import javax.inject.Inject
class AttachmentAdapter @Inject constructor(
private val context: Context,
private val colors: Colors
) : QkAdapter<Uri>() {
val attachmentDeleted: Subject<Uri> = PublishSubject.create()
private val disposables = CompositeDisposable()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.attachment_list_item, parent, false)
view.thumbnailBounds.clipToOutline = true
disposables += colors.bubble
.subscribe { color -> view.detach.setBackgroundTint(color) }
disposables += colors.textSecondary
.subscribe { color -> view.detach.setTint(color) }
return QkViewHolder(view)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
disposables.clear()
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val uri = getItem(position)
val view = holder.itemView
view.clicks().subscribe {
attachmentDeleted.onNext(uri)
}
Glide.with(context).load(uri).into(view.thumbnail)
}
}
@@ -0,0 +1,140 @@
/*
* 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 presentation.feature.compose
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.RelativeLayout
import com.google.android.flexbox.FlexboxLayoutManager
import com.jakewharton.rxbinding2.view.keys
import com.jakewharton.rxbinding2.widget.editorActions
import com.jakewharton.rxbinding2.widget.textChanges
import com.moez.QKSMS.R
import common.util.Colors
import common.util.extensions.dpToPx
import common.util.extensions.setBackgroundTint
import common.util.extensions.showKeyboard
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.contact_chip.view.*
import model.Contact
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import javax.inject.Inject
class ChipsAdapter @Inject constructor(private val context: Context, private val colors: Colors) : QkAdapter<Contact>() {
companion object {
private const val TYPE_EDIT_TEXT = 0
private const val TYPE_ITEM = 1
}
private val hint: String = context.getString(R.string.title_compose)
private val editText = View.inflate(context, R.layout.chip_input_list_item, null) as EditText
var view: RecyclerView? = null
val chipDeleted: PublishSubject<Contact> = PublishSubject.create<Contact>()
val textChanges = editText.textChanges()
val keyEvents = editText.keys()
val actions = editText.editorActions()
init {
val wrap = ViewGroup.LayoutParams.WRAP_CONTENT
editText.layoutParams = FlexboxLayoutManager.LayoutParams(wrap, wrap).apply {
minWidth = 56.dpToPx(context)
flexGrow = 8f
}
editText.hint = hint
}
override fun onDatasetChanged() {
editText.text = null
editText.hint = if (itemCount == 1) hint else null
if (itemCount != 2) {
editText.showKeyboard()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = when (viewType) {
TYPE_EDIT_TEXT -> QkViewHolder(editText)
else -> {
val view = LayoutInflater.from(context).inflate(R.layout.contact_chip, parent, false)
colors.composeBackground.subscribe { color -> view.content.setBackgroundTint(color) }
QkViewHolder(view)
}
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
when (getItemViewType(position)) {
TYPE_ITEM -> {
val contact = getItem(position)
val view = holder.itemView
view.avatar.contact = contact
// If the contact's name is empty, try to display a phone number instead
// The contacts provided here should only have one number
view.name.text = if (contact.name.isNotBlank()) {
contact.name
} else {
contact.numbers.firstOrNull { it.address.isNotBlank() }?.address ?: ""
}
view.setOnClickListener { showDetailedChip(contact) }
}
}
}
override fun getItemCount() = super.getItemCount() + 1
override fun getItemViewType(position: Int) = if (position == itemCount - 1) TYPE_EDIT_TEXT else TYPE_ITEM
private fun showDetailedChip(contact: Contact) {
val detailedChipView = DetailedChipView(context)
detailedChipView.setContact(contact)
val rootView = view?.rootView as ViewGroup
val layoutParams = RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
layoutParams.topMargin = 24.dpToPx(context)
layoutParams.marginStart = 56.dpToPx(context)
rootView.addView(detailedChipView, layoutParams)
detailedChipView.show()
detailedChipView.setOnDeleteListener {
chipDeleted.onNext(contact)
detailedChipView.hide()
}
}
override fun areItemsTheSame(old: Contact, new: Contact): Boolean {
return old.lookupKey == new.lookupKey
}
}
@@ -0,0 +1,252 @@
/*
* 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 presentation.feature.compose
import android.app.AlertDialog
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.net.Uri
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import com.google.android.flexbox.FlexboxLayoutManager
import com.jakewharton.rxbinding2.view.clicks
import com.jakewharton.rxbinding2.widget.textChanges
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.extensions.setBackgroundTint
import common.util.extensions.setTint
import common.util.extensions.setVisible
import common.util.extensions.showKeyboard
import io.reactivex.Observable
import io.reactivex.rxkotlin.Observables
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.compose_activity.*
import model.Contact
import model.Message
import presentation.common.base.QkThemedActivity
import javax.inject.Inject
class ComposeActivity : QkThemedActivity<ComposeViewModel>(), ComposeView {
override val viewModelClass = ComposeViewModel::class
override val activityVisibleIntent: Subject<Boolean> = PublishSubject.create()
override val queryChangedIntent: Observable<CharSequence> by lazy { chipsAdapter.textChanges }
override val queryKeyEventIntent: Observable<KeyEvent> by lazy { chipsAdapter.keyEvents }
override val queryEditorActionIntent: Observable<Int> by lazy { chipsAdapter.actions }
override val chipSelectedIntent: Subject<Contact> by lazy { contactsAdapter.contactSelected }
override val chipDeletedIntent: Subject<Contact> by lazy { chipsAdapter.chipDeleted }
override val menuReadyIntent: Observable<Unit> = menu.map { Unit }
override val callIntent: Subject<Unit> = PublishSubject.create()
override val infoIntent: Subject<Unit> = PublishSubject.create()
override val copyTextIntent: Subject<Message> = PublishSubject.create()
override val forwardMessageIntent: Subject<Message> = PublishSubject.create()
override val deleteMessageIntent: Subject<Message> = PublishSubject.create()
override val messageClickIntent: Subject<Message> by lazy { messageAdapter.clicks }
override val attachmentDeletedIntent: Subject<Uri> by lazy { attachmentAdapter.attachmentDeleted }
override val textChangedIntent by lazy { message.textChanges() }
override val attachIntent by lazy { attach.clicks() }
override val sendIntent by lazy { send.clicks() }
@Inject lateinit var chipsAdapter: ChipsAdapter
@Inject lateinit var contactsAdapter: ContactAdapter
@Inject lateinit var messageAdapter: MessagesAdapter
@Inject lateinit var attachmentAdapter: AttachmentAdapter
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.compose_activity)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
chipsAdapter.view = chips
contacts.itemAnimator = null
chips.itemAnimator = null
chips.layoutManager = FlexboxLayoutManager(this)
val layoutManager = LinearLayoutManager(this).apply { stackFromEnd = true }
messageAdapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
if (positionStart > 0) {
messageAdapter.notifyItemChanged(positionStart - 1)
}
// If we're at the bottom, scroll down to show new messages
val lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition()
if (positionStart >= messageAdapter.itemCount - 1 && lastVisiblePosition == positionStart - 1) {
messageList.scrollToPosition(positionStart)
}
}
})
messageAdapter.longClicks.subscribe { message ->
AlertDialog.Builder(this)
.setItems(R.array.message_options, { _, row ->
when (row) {
0 -> copyTextIntent.onNext(message)
1 -> forwardMessageIntent.onNext(message)
2 -> deleteMessageIntent.onNext(message)
}
})
.show()
}
messageList.setHasFixedSize(true)
messageList.layoutManager = layoutManager
messageList.adapter = messageAdapter
attachments.adapter = attachmentAdapter
messageBackground.backgroundTintMode = PorterDuff.Mode.MULTIPLY
val states = arrayOf(
intArrayOf(android.R.attr.state_enabled),
intArrayOf(-android.R.attr.state_enabled))
val iconEnabled = threadId
.distinctUntilChanged()
.switchMap { threadId -> colors.textPrimaryOnThemeForConversation(threadId) }
val iconDisabled = threadId
.distinctUntilChanged()
.switchMap { threadId -> colors.textTertiaryOnThemeForConversation(threadId) }
Observables
.combineLatest(iconEnabled, iconDisabled, { primary, tertiary ->
ColorStateList(states, intArrayOf(primary, tertiary))
})
.autoDisposable(scope())
.subscribe { tintList -> send.imageTintList = tintList }
theme
.autoDisposable(scope())
.subscribe { color -> send.setBackgroundTint(color) }
colors.textSecondary
.autoDisposable(scope())
.subscribe { color -> attach.setTint(color) }
colors.bubble
.autoDisposable(scope())
.subscribe { color -> messageBackground.setBackgroundTint(color) }
colors.background
.autoDisposable(scope())
.subscribe { color -> contacts.setBackgroundColor(color) }
colors.composeBackground
.doOnNext { color -> composeBackground.setBackgroundTint(color) }
.doOnNext { color -> window.decorView.setBackgroundColor(color) }
.autoDisposable(scope())
.subscribe()
window.callback = ComposeWindowCallback(window.callback, this)
}
override fun onStart() {
super.onStart()
activityVisibleIntent.onNext(true)
}
override fun onPause() {
super.onPause()
activityVisibleIntent.onNext(false)
}
override fun render(state: ComposeState) {
if (state.hasError) {
finish()
return
}
threadId.onNext(state.selectedConversation)
toolbarTitle.setVisible(!state.editingMode)
chips.setVisible(state.editingMode)
contacts.setVisible(state.contactsVisible)
composeBar.setVisible(!state.contactsVisible)
// Don't set the adapters unless needed
if (state.editingMode && chips.adapter == null) chips.adapter = chipsAdapter
if (state.editingMode && contacts.adapter == null) contacts.adapter = contactsAdapter
toolbar.menu.findItem(R.id.call)?.isVisible = !state.editingMode
toolbar.menu.findItem(R.id.info)?.isVisible = !state.editingMode
if (chipsAdapter.data.isEmpty() && state.selectedContacts.isNotEmpty()) {
message.showKeyboard()
}
if (chipsAdapter.data !== state.selectedContacts) {
chipsAdapter.data = state.selectedContacts
}
if (contactsAdapter.data !== state.contacts) {
contactsAdapter.data = state.contacts
}
if (messageAdapter.data !== state.messages) {
messageAdapter.data = state.messages
}
attachments.setVisible(state.attachments.isNotEmpty())
if (attachmentAdapter.data !== state.attachments) {
attachmentAdapter.data = state.attachments
}
if (title != state.title) title = state.title
counter.text = state.remaining
counter.setVisible(counter.text.isNotBlank())
send.isEnabled = state.canSend
}
override fun setDraft(draft: String) {
message.setText(draft)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.compose, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.call -> callIntent.onNext(Unit)
R.id.info -> infoIntent.onNext(Unit)
else -> return super.onOptionsItemSelected(item)
}
return true
}
}
@@ -0,0 +1,40 @@
/*
* 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 presentation.feature.compose
import android.net.Uri
import io.realm.RealmResults
import model.Contact
import model.Conversation
import model.Message
data class ComposeState(
val hasError: Boolean = false,
val editingMode: Boolean = false,
val contacts: List<Contact> = ArrayList(),
val contactsVisible: Boolean = false,
val selectedConversation: Long = 0,
val selectedContacts: List<Contact> = ArrayList(),
val title: String = "",
val archived: Boolean = false,
val messages: Pair<Conversation, RealmResults<Message>>? = null,
val attachments: List<Uri> = ArrayList(),
val remaining: String = "",
val canSend: Boolean = false
)
@@ -0,0 +1,51 @@
/*
* 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 presentation.feature.compose
import android.net.Uri
import android.view.KeyEvent
import io.reactivex.Observable
import io.reactivex.subjects.Subject
import model.Contact
import model.Message
import presentation.common.base.QkView
interface ComposeView : QkView<ComposeState> {
val activityVisibleIntent: Observable<Boolean>
val queryChangedIntent: Observable<CharSequence>
val queryKeyEventIntent: Observable<KeyEvent>
val queryEditorActionIntent: Observable<Int>
val chipSelectedIntent: Subject<Contact>
val chipDeletedIntent: Subject<Contact>
val menuReadyIntent: Observable<Unit>
val callIntent: Subject<Unit>
val infoIntent: Subject<Unit>
val copyTextIntent: Subject<Message>
val forwardMessageIntent: Subject<Message>
val deleteMessageIntent: Subject<Message>
val messageClickIntent: Subject<Message>
val attachmentDeletedIntent: Subject<Uri>
val textChangedIntent: Observable<CharSequence>
val attachIntent: Observable<Unit>
val sendIntent: Observable<Unit>
fun setDraft(draft: String)
}
@@ -0,0 +1,411 @@
/*
* 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 presentation.feature.compose
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.telephony.PhoneNumberUtils
import android.telephony.SmsMessage
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import com.mlsdev.rximagepicker.RxImagePicker
import com.mlsdev.rximagepicker.Sources
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.ClipboardUtils
import common.util.extensions.makeToast
import common.util.filter.ContactFilter
import interactor.ContactSync
import interactor.DeleteMessage
import interactor.MarkRead
import interactor.RetrySending
import interactor.SendMessage
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.Observables
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.withLatestFrom
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import io.realm.RealmList
import model.Contact
import model.Conversation
import model.Message
import model.PhoneNumber
import presentation.common.Navigator
import presentation.common.base.QkViewModel
import repository.ContactRepository
import repository.MessageRepository
import util.extensions.asObservable
import java.net.URLDecoder
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class ComposeViewModel(intent: Intent) : QkViewModel<ComposeView, ComposeState>(ComposeState()) {
@Inject lateinit var context: Context
@Inject lateinit var contactFilter: ContactFilter
@Inject lateinit var contactsRepo: ContactRepository
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var navigator: Navigator
@Inject lateinit var syncContacts: ContactSync
@Inject lateinit var sendMessage: SendMessage
@Inject lateinit var retrySending: RetrySending
@Inject lateinit var markRead: MarkRead
@Inject lateinit var deleteMessage: DeleteMessage
private var sharedText: String = ""
private val attachments: Subject<List<Uri>> = BehaviorSubject.createDefault(ArrayList())
private val contacts: Observable<List<Contact>> by lazy { contactsRepo.getUnmanagedContacts().toObservable() }
private val contactsReducer: Subject<(List<Contact>) -> List<Contact>> = PublishSubject.create()
private val selectedContacts: Observable<List<Contact>>
private val conversation: Observable<Conversation>
private val messages: Observable<List<Message>>
init {
appComponent.inject(this)
sharedText = intent.extras?.getString(Intent.EXTRA_TEXT) ?: ""
// If there are any image attachments, we'll set those as the initial attachments for the
// conversation
val sharedImages = mutableListOf<Uri>()
intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)?.run { sharedImages += this }
intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)?.run { sharedImages += this }
attachments.onNext(sharedImages)
val threadId = intent.extras?.getLong("threadId") ?: 0L
var address = ""
intent.data?.let {
val data = it.toString()
address = when {
it.scheme.startsWith("smsto") -> data.replace("smsto:", "")
it.scheme.startsWith("mmsto") -> data.replace("mmsto:", "")
it.scheme.startsWith("sms") -> data.replace("sms:", "")
it.scheme.startsWith("mms") -> data.replace("mms:", "")
else -> ""
}
// The dialer app on Oreo sends a URL encoded string, make sure to decode it
if (address.contains('%')) address = URLDecoder.decode(address, "UTF-8")
}
val initialConversation: Observable<Conversation> = when {
threadId != 0L -> {
newState { it.copy(selectedConversation = threadId, editingMode = false) }
messageRepo.getConversationAsync(threadId).asObservable()
}
address.isNotBlank() -> {
newState { it.copy(editingMode = false) }
messageRepo.getOrCreateConversation(address).toObservable()
}
else -> {
newState { it.copy(editingMode = true) }
Observable.empty()
}
}
selectedContacts = contactsReducer
.scan(listOf<Contact>(), { previousState, reducer -> reducer(previousState) })
.doOnNext { contacts -> newState { it.copy(selectedContacts = contacts) } }
// Merges two potential conversation sources (threadId from constructor and contact selection) into a single
// stream of conversations. If the conversation was deleted, notify the activity to shut down
conversation = selectedContacts
.skipUntil(state.filter { state -> state.editingMode })
.takeUntil(state.filter { state -> !state.editingMode })
.map { contacts -> contacts.map { it.numbers.firstOrNull()?.address ?: "" } }
.flatMapMaybe { addresses -> messageRepo.getOrCreateConversation(addresses) }
.mergeWith(initialConversation)
.filter { conversation -> conversation.isLoaded }
.doOnNext { conversation ->
if (!conversation.isValid) {
newState { it.copy(hasError = true) }
}
}
.filter { conversation -> conversation.isValid }
.filter { conversation -> conversation.id != 0L }
.distinctUntilChanged()
// When the conversation changes, update the threadId and the messages for the adapter
messages = conversation
.distinctUntilChanged { conversation -> conversation.id }
.observeOn(AndroidSchedulers.mainThread())
.map { conversation ->
val messages = messageRepo.getMessages(conversation.id)
newState { it.copy(selectedConversation = conversation.id, messages = Pair(conversation, messages)) }
messages
}
.switchMap { messages -> messages.asObservable() }
disposables += sendMessage
disposables += markRead
disposables += conversation.subscribe()
disposables += messages.subscribe()
disposables += conversation
.distinctUntilChanged { conversation -> conversation.getTitle() }
.subscribe { conversation ->
newState { it.copy(title = conversation.getTitle()) }
}
disposables += conversation
.distinctUntilChanged { conversation -> conversation.archived }
.subscribe { conversation ->
newState { it.copy(archived = conversation.archived) }
}
disposables += attachments
.subscribe { attachments ->
newState { it.copy(attachments = attachments) }
}
if (threadId == 0L) {
syncContacts.execute(Unit)
}
}
override fun bindView(view: ComposeView) {
super.bindView(view)
// Set the contact suggestions list to visible at all times when in editing mode and there are no contacts
// selected yet, and also visible while in editing mode and there is text entered in the query field
Observables
.combineLatest(view.queryChangedIntent, selectedContacts, { query, selectedContacts ->
selectedContacts.isEmpty() || query.isNotEmpty()
})
.skipUntil(state.filter { state -> state.editingMode })
.takeUntil(state.filter { state -> !state.editingMode })
.distinctUntilChanged()
.autoDisposable(view.scope())
.subscribe { contactsVisible -> newState { it.copy(contactsVisible = contactsVisible && it.editingMode) } }
// Update the list of contact suggestions based on the query input, while also filtering out any contacts
// that have already been selected
Observables
.combineLatest(view.queryChangedIntent, contacts, selectedContacts, { query, contacts, selectedContacts ->
var filteredContacts = contacts
.filterNot { contact -> selectedContacts.contains(contact) }
.filter { contact -> contactFilter.filter(contact, query) }
if (PhoneNumberUtils.isWellFormedSmsAddress(query.toString())) {
filteredContacts = listOf(Contact(numbers = RealmList(PhoneNumber(address = query.toString())))) + filteredContacts
}
filteredContacts
})
.skipUntil(state.filter { state -> state.editingMode })
.takeUntil(state.filter { state -> !state.editingMode })
.subscribeOn(Schedulers.computation())
.autoDisposable(view.scope())
.subscribe { contacts -> newState { it.copy(contacts = contacts) } }
// Backspaces should delete the most recent contact if there's no text input
// Close the activity if user presses back
view.queryKeyEventIntent
.filter { event -> event.action == KeyEvent.ACTION_DOWN }
.withLatestFrom(selectedContacts, view.queryChangedIntent, { event, contacts, query ->
when (event.keyCode) {
KeyEvent.KEYCODE_DEL -> {
if (contacts.isNotEmpty() && query.isEmpty()) {
contactsReducer.onNext { it.dropLast(1) }
}
}
KeyEvent.KEYCODE_BACK -> {
newState { it.copy(hasError = true) }
}
}
})
.autoDisposable(view.scope())
.subscribe()
// Enter the first contact suggestion if the enter button is pressed
view.queryEditorActionIntent
.filter { actionId -> actionId == EditorInfo.IME_ACTION_DONE }
.withLatestFrom(state, { _, state -> state })
.autoDisposable(view.scope())
.subscribe { state ->
state.contacts.firstOrNull()?.let { contact ->
contactsReducer.onNext { contacts -> contacts + contact }
}
}
// Update the list of selected contacts when a new contact is selected or an existing one is deselected
Observable.merge(
view.chipDeletedIntent.doOnNext { contact ->
contactsReducer.onNext { contacts -> contacts.filterNot { it == contact } }
},
view.chipSelectedIntent.doOnNext { contact ->
contactsReducer.onNext { contacts -> contacts.toMutableList().apply { add(contact) } }
})
.skipUntil(state.filter { state -> state.editingMode })
.takeUntil(state.filter { state -> !state.editingMode })
.autoDisposable(view.scope())
.subscribe()
// When the menu is loaded, trigger a new state so that the menu options can be rendered correctly
view.menuReadyIntent
.autoDisposable(view.scope())
.subscribe { newState { it.copy() } }
// Open the phone dialer if the call button is clicked
view.callIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.map { conversation -> conversation.recipients.first() }
.map { recipient -> recipient.address }
.autoDisposable(view.scope())
.subscribe { address -> navigator.makePhoneCall(address) }
// Open the conversation settings if info button is clicked
view.infoIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.autoDisposable(view.scope())
.subscribe { conversation -> navigator.showConversationInfo(conversation.id) }
view.messageClickIntent
.filter { message -> message.isFailedMessage() }
.doOnNext { message -> retrySending.execute(message) }
.autoDisposable(view.scope())
.subscribe()
// Mark the conversation read, if in foreground
Observables.combineLatest(messages, view.activityVisibleIntent, { _, b -> b })
.withLatestFrom(conversation, { visible, conversation ->
if (visible && conversation.isValid) markRead.execute(conversation.id)
})
.autoDisposable(view.scope())
.subscribe()
// Attach a photo
view.attachIntent
.flatMap { RxImagePicker.with(context).requestImage(Sources.GALLERY) }
.withLatestFrom(attachments, { attachment, attachments -> attachments + attachment })
.autoDisposable(view.scope())
.subscribe { attachments.onNext(it) }
// Detach a photo
view.attachmentDeletedIntent
.withLatestFrom(attachments, { bitmap, attachments -> attachments.filter { it !== bitmap } })
.autoDisposable(view.scope())
.subscribe { attachments.onNext(it) }
conversation
.map { conversation -> conversation.draft }
.distinctUntilChanged()
.autoDisposable(view.scope())
.subscribe { draft ->
// If text was shared into the conversation, it should take priority over the
// existing draft
//
// TODO: Show dialog warning user about overwriting draft
if (sharedText.isNotBlank()) {
view.setDraft(sharedText)
} else {
view.setDraft(draft)
}
}
// Enable the send button when there is text input into the new message body or there's
// an attachment, disable otherwise
Observables
.combineLatest(view.textChangedIntent, attachments, { text, attachments ->
text.isNotBlank() || attachments.isNotEmpty()
})
.autoDisposable(view.scope())
.subscribe { canSend -> newState { it.copy(canSend = canSend) } }
// Show the remaining character counter when necessary
view.textChangedIntent
.observeOn(Schedulers.computation())
.map { draft -> SmsMessage.calculateLength(draft, false) }
.map { array ->
val messages = array[0]
val remaining = array[2]
when {
messages <= 1 && remaining > 10 -> ""
messages <= 1 && remaining <= 10 -> "$remaining"
else -> "$remaining / $messages"
}
}
.distinctUntilChanged()
.autoDisposable(view.scope())
.subscribe { remaining -> newState { it.copy(remaining = remaining) } }
// Update the draft whenever the text is changed
view.textChangedIntent
.debounce(100, TimeUnit.MILLISECONDS)
.map { draft -> draft.toString() }
.observeOn(Schedulers.io())
.withLatestFrom(conversation.map { it.id }, { draft, threadId ->
messageRepo.saveDraft(threadId, draft)
})
.autoDisposable(view.scope())
.subscribe()
// Send a message when the send button is clicked, and disable editing mode if it's enabled
view.sendIntent
.withLatestFrom(view.textChangedIntent, { _, body -> body })
.map { body -> body.toString() }
.withLatestFrom(attachments, conversation, { body, attachments, conversation ->
val threadId = conversation.id
val addresses = conversation.recipients.map { it.address }
sendMessage.execute(SendMessage.Params(threadId, addresses, body, attachments))
view.setDraft("")
this.attachments.onNext(ArrayList())
})
.withLatestFrom(state, { _, state ->
if (state.editingMode) {
newState { it.copy(editingMode = false) }
}
})
.autoDisposable(view.scope())
.subscribe()
// Copy the body of the selected message into the clipboard
view.copyTextIntent
.autoDisposable(view.scope())
.subscribe { message ->
ClipboardUtils.copy(context, message.body)
context.makeToast(R.string.toast_copied)
}
// Forward the message
view.forwardMessageIntent
.autoDisposable(view.scope())
.subscribe { message -> navigator.showCompose(message.body) }
// Delete the selected message
view.deleteMessageIntent
.autoDisposable(view.scope())
.subscribe { message -> deleteMessage.execute(message.id) }
}
}
@@ -0,0 +1,143 @@
/*
* 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 presentation.feature.compose
import android.app.Activity
import android.graphics.Rect
import android.os.Build
import android.support.annotation.RequiresApi
import android.view.ActionMode
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.MotionEvent
import android.view.SearchEvent
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
class ComposeWindowCallback(private val localCallback: Window.Callback, private val activity: Activity) : Window.Callback {
override fun dispatchKeyEvent(keyEvent: KeyEvent): Boolean {
return localCallback.dispatchKeyEvent(keyEvent)
}
override fun dispatchKeyShortcutEvent(keyEvent: KeyEvent): Boolean {
return localCallback.dispatchKeyShortcutEvent(keyEvent)
}
override fun dispatchTouchEvent(motionEvent: MotionEvent): Boolean {
if (motionEvent.action == MotionEvent.ACTION_DOWN) {
val v = activity.currentFocus
when (v) {
is DetailedChipView -> {
val rect = Rect().apply { v.getGlobalVisibleRect(this) }
if (!rect.contains(motionEvent.rawX.toInt(), motionEvent.rawY.toInt())) {
v.hide()
return true
}
}
}
}
return localCallback.dispatchTouchEvent(motionEvent)
}
override fun dispatchTrackballEvent(motionEvent: MotionEvent): Boolean {
return localCallback.dispatchTrackballEvent(motionEvent)
}
override fun dispatchGenericMotionEvent(motionEvent: MotionEvent): Boolean {
return localCallback.dispatchGenericMotionEvent(motionEvent)
}
override fun dispatchPopulateAccessibilityEvent(accessibilityEvent: AccessibilityEvent): Boolean {
return localCallback.dispatchPopulateAccessibilityEvent(accessibilityEvent)
}
override fun onCreatePanelView(i: Int): View? {
return localCallback.onCreatePanelView(i)
}
override fun onCreatePanelMenu(i: Int, menu: Menu): Boolean {
return localCallback.onCreatePanelMenu(i, menu)
}
override fun onPreparePanel(i: Int, view: View, menu: Menu): Boolean {
return localCallback.onPreparePanel(i, view, menu)
}
override fun onMenuOpened(i: Int, menu: Menu): Boolean {
return localCallback.onMenuOpened(i, menu)
}
override fun onMenuItemSelected(i: Int, menuItem: MenuItem): Boolean {
return localCallback.onMenuItemSelected(i, menuItem)
}
override fun onWindowAttributesChanged(layoutParams: WindowManager.LayoutParams) {
localCallback.onWindowAttributesChanged(layoutParams)
}
override fun onContentChanged() {
localCallback.onContentChanged()
}
override fun onWindowFocusChanged(b: Boolean) {
localCallback.onWindowFocusChanged(b)
}
override fun onAttachedToWindow() {
localCallback.onAttachedToWindow()
}
override fun onDetachedFromWindow() {
localCallback.onDetachedFromWindow()
}
override fun onPanelClosed(i: Int, menu: Menu) {
localCallback.onPanelClosed(i, menu)
}
override fun onSearchRequested(): Boolean {
return localCallback.onSearchRequested()
}
@RequiresApi(api = Build.VERSION_CODES.M)
override fun onSearchRequested(searchEvent: SearchEvent): Boolean {
return localCallback.onSearchRequested(searchEvent)
}
override fun onWindowStartingActionMode(callback: ActionMode.Callback): ActionMode? {
return localCallback.onWindowStartingActionMode(callback)
}
@RequiresApi(api = Build.VERSION_CODES.M)
override fun onWindowStartingActionMode(callback: ActionMode.Callback, i: Int): ActionMode? {
return localCallback.onWindowStartingActionMode(callback, i)
}
override fun onActionModeStarted(actionMode: ActionMode) {
localCallback.onActionModeStarted(actionMode)
}
override fun onActionModeFinished(actionMode: ActionMode) {
localCallback.onActionModeFinished(actionMode)
}
}
@@ -0,0 +1,86 @@
/*
* 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 presentation.feature.compose
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import common.util.extensions.setVisible
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.contact_list_item.view.*
import model.Contact
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import javax.inject.Inject
class ContactAdapter @Inject constructor(private val context: Context) : QkAdapter<Contact>() {
val contactSelected: Subject<Contact> = PublishSubject.create()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val layoutRes = R.layout.contact_list_item
val layoutInflater = LayoutInflater.from(context)
val view = layoutInflater.inflate(layoutRes, parent, false)
return QkViewHolder(view)
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val contact = getItem(position)
val view = holder.itemView
view.primary.clicks().subscribe { contactSelected.onNext(copyContact(contact, 0)) }
view.avatar.contact = contact
view.name.text = contact.name
view.name.setVisible(view.name.text.isNotEmpty())
view.address.text = contact.numbers.first()?.address ?: ""
view.type.text = contact.numbers.first()?.type ?: ""
view.addresses.removeAllViews()
contact.numbers.forEachIndexed { index, number ->
if (index != 0) {
val numberView = View.inflate(context, R.layout.contact_number_list_item, null)
numberView.clicks().subscribe { contactSelected.onNext(copyContact(contact, index)) }
numberView.address.text = number.address
numberView.type.text = number.type
view.addresses.addView(numberView)
}
}
}
/**
* Creates a copy of the contact with only one phone number, so that the chips
* view can still display the name/photo, and not get confused about which phone number to use
*/
private fun copyContact(contact: Contact, numberIndex: Int) = Contact().apply {
lookupKey = contact.lookupKey
name = contact.name
numbers.add(contact.numbers[numberIndex])
}
override fun areItemsTheSame(old: Contact, new: Contact): Boolean {
return old.lookupKey == new.lookupKey
}
}
@@ -0,0 +1,86 @@
/*
* 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 presentation.feature.compose
import android.content.Context
import android.view.View
import android.view.animation.AlphaAnimation
import android.widget.RelativeLayout
import com.moez.QKSMS.R
import com.uber.autodispose.android.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.Colors
import common.util.extensions.setBackgroundTint
import kotlinx.android.synthetic.main.contact_chip_detailed.view.*
import model.Contact
import javax.inject.Inject
class DetailedChipView(context: Context) : RelativeLayout(context) {
@Inject lateinit var colors: Colors
init {
View.inflate(context, R.layout.contact_chip_detailed, this)
appComponent.inject(this)
setOnClickListener { hide() }
visibility = View.GONE
isFocusable = true
isFocusableInTouchMode = true
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
colors.theme
.autoDisposable(scope())
.subscribe { color -> card.setBackgroundTint(color) }
}
fun setContact(contact: Contact) {
avatar.contact = contact
name.text = contact.name
info.text = contact.numbers.map { it.address }.toString()
}
fun show() {
startAnimation(AlphaAnimation(0f, 1f).apply { duration = 200 })
visibility = View.VISIBLE
requestFocus()
isClickable = true
}
fun hide() {
startAnimation(AlphaAnimation(1f, 0f).apply { duration = 200 })
visibility = View.GONE
clearFocus()
isClickable = false
}
fun setOnDeleteListener(listener: (View) -> Unit) {
delete.setOnClickListener(listener)
}
}
@@ -0,0 +1,256 @@
/*
* 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 presentation.feature.compose
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.telephony.PhoneNumberUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jakewharton.rxbinding2.view.RxView
import com.moez.QKSMS.R
import common.util.Colors
import common.util.DateFormatter
import common.util.extensions.dpToPx
import common.util.extensions.setBackgroundTint
import common.util.extensions.setPadding
import common.util.extensions.setVisible
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import io.realm.RealmList
import io.realm.RealmRecyclerViewAdapter
import io.realm.RealmResults
import kotlinx.android.synthetic.main.message_list_item_in.view.*
import model.Contact
import model.Conversation
import model.Message
import model.PhoneNumber
import presentation.common.base.QkViewHolder
import util.extensions.isImage
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class MessagesAdapter @Inject constructor(
private val context: Context,
private val colors: Colors,
private val dateFormatter: DateFormatter
) : RealmRecyclerViewAdapter<Message, QkViewHolder>(null, true) {
companion object {
private const val VIEW_TYPE_ME = 1
private const val TIMESTAMP_THRESHOLD = 10
}
val clicks: Subject<Message> = PublishSubject.create<Message>()
val longClicks: Subject<Message> = PublishSubject.create<Message>()
var data: Pair<Conversation, RealmResults<Message>>? = null
set(value) {
field = value
people.clear()
contactMap.clear()
// Update the theme
val threadId = value?.first?.id ?: 0
theme = colors.themeForConversation(threadId)
textPrimaryOnTheme = colors.textPrimaryOnThemeForConversation(threadId)
updateData(value?.second)
}
private val people = ArrayList<String>()
private val contactMap = HashMap<String, Contact>()
private val selected = HashMap<Long, Boolean>()
private val disposables = CompositeDisposable()
private var theme = colors.theme
private var textPrimaryOnTheme = colors.textPrimaryOnTheme
/**
* If the viewType is negative, then the viewHolder has an attachment. We'll consider
* this a unique viewType even though it uses the same view, so that regular messages
* don't need clipToOutline set to true, and they don't need to worry about images
*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val layoutInflater = LayoutInflater.from(context)
val view: View
val hasThumbnail = viewType < 0
val absViewType = Math.abs(viewType)
if (absViewType == VIEW_TYPE_ME) {
view = layoutInflater.inflate(R.layout.message_list_item_out, parent, false)
disposables += colors.bubble
.subscribe { color -> view.messageBackground.setBackgroundTint(color) }
} else {
view = layoutInflater.inflate(R.layout.message_list_item_in, parent, false)
view.subject.textColorObservable = textPrimaryOnTheme
view.body.textColorObservable = textPrimaryOnTheme
disposables += theme
.subscribe { color -> view.messageBackground.setBackgroundTint(color) }
}
if (hasThumbnail) {
view.messageBackground.clipToOutline = true
}
if (absViewType != VIEW_TYPE_ME) {
val address = people[absViewType - 2]
if (!contactMap.containsKey(address)) {
contactMap[address] = data?.first?.recipients?.mapNotNull { it.contact } // Map the conversation to its contacts
?.firstOrNull { it.numbers.any { PhoneNumberUtils.compare(it.address, address) } } // See if any of the phone numbers match
?: Contact(numbers = RealmList(PhoneNumber(address = address))) // Fallback to a fake contact
}
view.avatar.threadId = data?.first?.id ?: 0
view.avatar.contact = contactMap[address]
}
return QkViewHolder(view)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
disposables.clear()
}
override fun onBindViewHolder(viewHolder: QkViewHolder, position: Int) {
val message = getItem(position)!!
val view = viewHolder.itemView
RxView.clicks(view).subscribe {
clicks.onNext(message)
selected[message.id] = view.status.visibility != View.VISIBLE
notifyItemChanged(position)
}
RxView.longClicks(view).subscribe { longClicks.onNext(message) }
view.subject.text = message.getCleansedSubject()
view.subject.setVisible(view.subject.text.isNotBlank())
view.body.text = message.getText()
view.body.setVisible(message.isSms() || view.body.text.isNotEmpty() || message.parts.all { it.image == null })
view.timestamp.text = dateFormatter.getMessageTimestamp(message.date)
bindMmsPreview(view, position)
bindStatus(view, position)
bindGrouping(view, position)
}
private fun bindMmsPreview(view: View, position: Int) {
val message = getItem(position)!!
view.mmsPreview.parts = message.parts
}
private fun bindStatus(view: View, position: Int) {
val message = getItem(position)!!
val next = if (position == itemCount - 1) null else getItem(position + 1)
val age = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - message.date)
val timestamp = dateFormatter.getTimestamp(message.date)
view.status.text = when {
message.isSending() -> context.getString(R.string.message_status_sending)
message.isDelivered() -> context.getString(R.string.message_status_delivered, timestamp)
message.isFailedMessage() -> context.getString(R.string.message_status_failed)
!message.isMe() && data?.first?.recipients?.size ?: 0 > 1 -> "${contactMap[message.address]?.name} • $timestamp"
else -> timestamp
}
view.status.setVisible(when {
selected[message.id] == true -> true
message.isSending() -> true
message.isFailedMessage() -> true
selected[message.id] == false -> false
data?.first?.recipients?.size ?: 0 > 1 && !message.isMe() && next?.compareSender(message) != true -> true
message.isDelivered() && age <= TIMESTAMP_THRESHOLD -> true
else -> false
})
}
private fun bindGrouping(view: View, position: Int) {
val message = getItem(position)!!
val previous = if (position == 0) null else getItem(position - 1)
val next = if (position == itemCount - 1) null else getItem(position + 1)
val diff = TimeUnit.MILLISECONDS.toMinutes(message.date - (previous?.date ?: 0))
val sent = message.isMe()
val canGroupWithPrevious = canGroup(message, previous)
val canGroupWithNext = canGroup(message, next)
view.timestamp.visibility = if (diff < TIMESTAMP_THRESHOLD) View.GONE else View.VISIBLE
when {
!canGroupWithPrevious && canGroupWithNext -> {
view.setPadding(bottom = 2.dpToPx(context))
view.messageBackground.setBackgroundResource(if (sent) R.drawable.message_out_first else R.drawable.message_in_first)
view.avatar?.visibility = View.INVISIBLE
}
canGroupWithPrevious && canGroupWithNext -> {
view.setPadding(bottom = 2.dpToPx(context))
view.messageBackground.setBackgroundResource(if (sent) R.drawable.message_out_middle else R.drawable.message_in_middle)
view.avatar?.visibility = View.INVISIBLE
}
canGroupWithPrevious && !canGroupWithNext -> {
view.setPadding(bottom = 16.dpToPx(context))
view.messageBackground.setBackgroundResource(if (sent) R.drawable.message_out_last else R.drawable.message_in_last)
view.avatar?.visibility = View.VISIBLE
}
else -> {
view.setPadding(bottom = 16.dpToPx(context))
view.messageBackground.setBackgroundResource(R.drawable.message_only)
view.avatar?.visibility = View.VISIBLE
}
}
if (getItemViewType(position) < 0) view.messageBackground.setBackgroundResource(R.drawable.message_only)
}
private fun canGroup(message: Message, other: Message?): Boolean {
if (other == null) return false
val diff = TimeUnit.MILLISECONDS.toMinutes(Math.abs(message.date - other.date))
return message.compareSender(other) && diff < TIMESTAMP_THRESHOLD
}
override fun getItemViewType(position: Int): Int {
val message = getItem(position)!!
var index = if (message.isMe()) {
VIEW_TYPE_ME
} else {
if (!people.contains(message.address)) {
people.add(message.address)
}
2 + people.indexOf(message.address)
}
// If it contains a thumbnail, then use the negative viewtype
if (message.parts.filter { it.isImage() }.any()) {
index *= -1
}
return index
}
}
@@ -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 presentation.feature.conversationinfo
import android.os.Bundle
import android.support.v7.app.AlertDialog
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.extensions.setVisible
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.conversation_info_activity.*
import presentation.common.Navigator
import presentation.common.base.QkThemedActivity
import javax.inject.Inject
class ConversationInfoActivity : QkThemedActivity<ConversationInfoViewModel>(), ConversationInfoView {
override val viewModelClass = ConversationInfoViewModel::class
override val notificationsIntent by lazy { notifications.clicks() }
override val themeIntent by lazy { themePrefs.clicks() }
override val archiveIntent by lazy { archive.clicks() }
override val blockIntent by lazy { block.clicks() }
override val deleteIntent by lazy { delete.clicks() }
override val confirmDeleteIntent: PublishSubject<Unit> = PublishSubject.create()
@Inject lateinit var navigator: Navigator
@Inject lateinit var recipientAdapter: ConversationRecipientAdapter
@Inject lateinit var mediaAdapter: ConversationMediaAdapter
@Inject lateinit var itemDecoration: GridSpacingItemDecoration
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.conversation_info_activity)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
setTitle(R.string.info_title)
colors.background
.autoDisposable(scope())
.subscribe { color -> window.decorView.setBackgroundColor(color) }
mediaAdapter.thumbnailClicks
.autoDisposable(scope())
.subscribe { view -> navigator.showImageAnimated(this, view) }
recipients.adapter = recipientAdapter
media.adapter = mediaAdapter
media.addItemDecoration(itemDecoration)
}
override fun render(state: ConversationInfoState) {
if (state.hasError) {
finish()
return
}
recipientAdapter.data = state.recipients
recipientAdapter.threadId = state.threadId
notifications.setVisible(!state.blocked)
archive.setVisible(!state.blocked)
archive.title = getString(when (state.archived) {
true -> R.string.info_unarchive
false -> R.string.info_archive
})
block.title = getString(when (state.blocked) {
true -> R.string.info_unblock
false -> R.string.info_block
})
mediaAdapter.data = state.media
}
override fun showDeleteDialog() {
AlertDialog.Builder(this)
.setTitle(R.string.dialog_delete_title)
.setMessage(R.string.dialog_delete_message)
.setPositiveButton(R.string.button_delete, { _, _ -> confirmDeleteIntent.onNext(Unit) })
.setNegativeButton(R.string.button_cancel, null)
.show()
}
}
@@ -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 presentation.feature.conversationinfo
import model.MmsPart
import model.Recipient
data class ConversationInfoState(
val recipients: List<Recipient> = listOf(),
val threadId: Long = 0,
val archived: Boolean = false,
val blocked: Boolean = false,
val media: List<MmsPart> = ArrayList(),
val hasError: Boolean = false
)
@@ -0,0 +1,35 @@
/*
* 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 presentation.feature.conversationinfo
import io.reactivex.Observable
import presentation.common.base.QkView
interface ConversationInfoView : QkView<ConversationInfoState> {
val notificationsIntent: Observable<Unit>
val themeIntent: Observable<Unit>
val archiveIntent: Observable<Unit>
val blockIntent: Observable<Unit>
val deleteIntent: Observable<Unit>
val confirmDeleteIntent: Observable<Unit>
fun showDeleteDialog()
}
@@ -0,0 +1,153 @@
/*
* 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 presentation.feature.conversationinfo
import android.content.Context
import android.content.Intent
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import interactor.DeleteConversation
import interactor.MarkArchived
import interactor.MarkBlocked
import interactor.MarkUnarchived
import interactor.MarkUnblocked
import io.reactivex.Observable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.withLatestFrom
import model.Conversation
import presentation.common.Navigator
import presentation.common.base.QkViewModel
import repository.MessageRepository
import util.extensions.asObservable
import util.extensions.isImage
import javax.inject.Inject
class ConversationInfoViewModel(intent: Intent) : QkViewModel<ConversationInfoView,
ConversationInfoState>(ConversationInfoState()) {
@Inject lateinit var context: Context
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var markArchived: MarkArchived
@Inject lateinit var markUnarchived: MarkUnarchived
@Inject lateinit var markBlocked: MarkBlocked
@Inject lateinit var markUnblocked: MarkUnblocked
@Inject lateinit var navigator: Navigator
@Inject lateinit var deleteConversation: DeleteConversation
private val conversation: Observable<Conversation>
init {
appComponent.inject(this)
val threadId = intent.extras?.getLong("threadId") ?: 0L
newState { it.copy(threadId = threadId) }
conversation = messageRepo.getConversationAsync(threadId)
.asObservable<Conversation>()
.filter { conversation -> conversation.isLoaded }
.doOnNext { conversation ->
if (!conversation.isValid) {
newState { it.copy(hasError = true) }
}
}
.filter { conversation -> conversation.isValid }
.filter { conversation -> conversation.id != 0L }
disposables += markArchived
disposables += markUnarchived
disposables += markBlocked
disposables += markUnblocked
disposables += deleteConversation
// Update the recipients whenever they change
disposables += conversation
.map { conversation -> conversation.recipients }
.distinctUntilChanged()
.subscribe { recipients -> newState { it.copy(recipients = recipients) } }
// Update the view's archived state whenever it changes
disposables += conversation
.map { conversation -> conversation.archived }
.distinctUntilChanged()
.subscribe { archived -> newState { it.copy(archived = archived) } }
// Update the view's blocked state whenever it changes
disposables += conversation
.map { conversation -> conversation.blocked }
.distinctUntilChanged()
.subscribe { blocked -> newState { it.copy(blocked = blocked) } }
// Load the attachments from the conversation
disposables += messageRepo.getPartsForConversation(threadId)
.map { parts -> parts.filter { part -> part.isImage() } }
.map { parts -> parts.reversed() }
.subscribe { media -> newState { it.copy(media = media) } }
}
override fun bindView(view: ConversationInfoView) {
super.bindView(view)
// Show the notifications settings for the conversation
view.notificationsIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.autoDisposable(view.scope())
.subscribe { conversation -> navigator.showNotificationSettings(conversation.id) }
// Show the theme settings for the conversation
view.themeIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.autoDisposable(view.scope())
.subscribe { conversation -> navigator.showThemePicker(conversation.id) }
// Toggle the archived state of the conversation
view.archiveIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.autoDisposable(view.scope())
.subscribe { conversation ->
when (conversation.archived) {
true -> markUnarchived.execute(conversation.id)
false -> markArchived.execute(conversation.id)
}
}
// Toggle the blocked state of the conversation
view.blockIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.autoDisposable(view.scope())
.subscribe { conversation ->
when (conversation.blocked) {
true -> markUnblocked.execute(conversation.id)
false -> markBlocked.execute(conversation.id)
}
}
// Show the delete confirmation dialog
view.deleteIntent
.autoDisposable(view.scope())
.subscribe { view.showDeleteDialog() }
// Delete the conversation
view.confirmDeleteIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.autoDisposable(view.scope())
.subscribe { conversation -> deleteConversation.execute(conversation.id) }
}
}
@@ -0,0 +1,72 @@
/*
* 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 presentation.feature.conversationinfo
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.moez.QKSMS.R
import common.util.Colors
import common.util.GlideApp
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.conversation_media_list_item.view.*
import model.MmsPart
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import javax.inject.Inject
class ConversationMediaAdapter @Inject constructor(
private val context: Context,
private val colors: Colors
) : QkAdapter<MmsPart>() {
val thumbnailClicks: PublishSubject<View> = PublishSubject.create()
private val disposables = CompositeDisposable()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.conversation_media_list_item, parent, false)
disposables += colors.separator.subscribe { color -> view.setBackgroundColor(color) }
return QkViewHolder(view)
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val part = getItem(position)
val view = holder.itemView
GlideApp.with(context)
.load(part.image)
.fitCenter()
.into(view.thumbnail)
view.thumbnail.transitionName = part.id.toString()
view.thumbnail.setOnClickListener { thumbnailClicks.onNext(it) }
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
disposables.clear()
}
}
@@ -0,0 +1,86 @@
/*
* 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 presentation.feature.conversationinfo
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.moez.QKSMS.R
import common.util.Colors
import common.util.extensions.setTint
import common.util.extensions.setVisible
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import kotlinx.android.synthetic.main.conversation_recipient_list_item.view.*
import model.Recipient
import presentation.common.Navigator
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import javax.inject.Inject
class ConversationRecipientAdapter @Inject constructor(
private val context: Context,
private val colors: Colors,
private val navigator: Navigator
) : QkAdapter<Recipient>() {
var threadId: Long = 0L
private val disposables = CompositeDisposable()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val layoutInflater = LayoutInflater.from(context)
val view = layoutInflater.inflate(R.layout.conversation_recipient_list_item, parent, false)
disposables += colors.textSecondary
.subscribe { color -> view.add.setTint(color) }
return QkViewHolder(view)
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val recipient = getItem(position)
val view = holder.itemView
view.setOnClickListener {
if (recipient.contact == null) {
navigator.addContact(recipient.address)
} else {
view.avatar.callOnClick()
}
}
view.avatar.threadId = threadId
view.avatar.contact = recipient.contact
view.name.text = recipient.contact?.name ?: recipient.address
view.address.text = recipient.address
view.address.setVisible(recipient.contact != null)
view.add.setVisible(recipient.contact == null)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
disposables.clear()
}
}
@@ -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 presentation.feature.conversationinfo
import android.content.Context
import android.graphics.Rect
import android.support.v7.widget.RecyclerView
import android.view.View
import common.util.extensions.dpToPx
import javax.inject.Inject
class GridSpacingItemDecoration @Inject constructor(context: Context) : RecyclerView.ItemDecoration() {
private val spanCount = 3
private val spacing = 2.dpToPx(context)
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val position = parent.getChildAdapterPosition(view)
val column = position % spanCount
outRect.left = column * spacing / spanCount
outRect.right = spacing - (column + 1) * spacing / spanCount
if (position >= spanCount) {
outRect.top = spacing
}
}
}
@@ -0,0 +1,39 @@
/*
* 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 presentation.feature.conversations
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import javax.inject.Inject
class ConversationItemTouchCallback @Inject constructor() : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
val swipes: Subject<Int> = PublishSubject.create()
override fun onMove(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, target: RecyclerView.ViewHolder?): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
swipes.onNext(viewHolder.adapterPosition)
}
}
@@ -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 presentation.feature.conversations
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.jakewharton.rxbinding2.view.clicks
import com.jakewharton.rxbinding2.view.longClicks
import com.moez.QKSMS.R
import common.util.Colors
import common.util.DateFormatter
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.conversation_list_item.view.*
import model.Contact
import model.Conversation
import model.Message
import model.PhoneNumber
import presentation.common.Navigator
import presentation.common.base.FlowableAdapter
import presentation.common.base.QkViewHolder
import repository.MessageRepository
import javax.inject.Inject
class ConversationsAdapter @Inject constructor(
val context: Context,
val navigator: Navigator,
val messageRepo: MessageRepository,
val dateFormatter: DateFormatter,
val colors: Colors
) : FlowableAdapter<Pair<Conversation, Message>>() {
val clicks: Subject<Long> = PublishSubject.create()
val longClicks: Subject<Long> = PublishSubject.create()
private val disposables = CompositeDisposable()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val layoutRes = when (viewType) {
0 -> R.layout.conversation_list_item
else -> R.layout.conversation_list_item_unread
}
val layoutInflater = LayoutInflater.from(context)
val view = layoutInflater.inflate(layoutRes, parent, false)
if (viewType == 1) {
disposables += colors.theme
.subscribe { color -> view.date.setTextColor(color) }
}
return QkViewHolder(view)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
disposables.clear()
}
override fun onBindViewHolder(viewHolder: QkViewHolder, position: Int) {
val conversation = getItem(position).first
val message = getItem(position).second
val view = viewHolder.itemView
view.clicks().subscribe { clicks.onNext(conversation.id) }
view.longClicks().subscribe { longClicks.onNext(conversation.id) }
view.avatars.contacts = conversation.recipients.map { recipient ->
recipient.contact ?: Contact().apply { numbers.add(PhoneNumber().apply { address = recipient.address }) }
}
view.title.text = conversation.getTitle()
view.date.text = dateFormatter.getConversationTimestamp(message.date)
view.snippet.text = if (message.isMe()) "You: ${message.getSummary()}" else message.getSummary()
}
override fun getItemViewType(position: Int): Int {
return if (getItem(position).second.read) 0 else 1
}
override fun areItemsTheSame(old: Pair<Conversation, Message>, new: Pair<Conversation, Message>): Boolean {
return old.first.id == new.first.id
}
override fun areContentsTheSame(old: Pair<Conversation, Message>, new: Pair<Conversation, Message>): Boolean {
return old.second.id == new.second.id &&
old.second.read == new.second.read &&
old.first.recipients == new.first.recipients
}
}
@@ -0,0 +1,107 @@
/*
* 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 presentation.feature.gallery
import android.os.Bundle
import android.transition.ChangeBounds
import android.transition.ChangeImageTransform
import android.transition.TransitionSet
import android.view.Menu
import android.view.MenuItem
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import common.util.GlideApp
import common.util.extensions.setVisible
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.gallery_activity.*
import presentation.common.GlideCompletionListener
import presentation.common.base.QkActivity
class GalleryActivity : QkActivity<GalleryViewModel>(), GalleryView {
override val viewModelClass = GalleryViewModel::class
override val screenTouchedIntent by lazy { image.clicks() }
override val optionsItemSelectedIntent: Subject<Int> = PublishSubject.create()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.gallery_activity)
postponeEnterTransition()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
val transition = TransitionSet().apply {
duration = 100
addTransition(ChangeBounds())
addTransition(ChangeImageTransform())
}
window.sharedElementReturnTransition = transition
window.sharedElementEnterTransition = transition
image.transitionName = intent.getLongExtra("partId", 0L).toString()
// When calling the public setter, it doesn't allow the midscale to be the same as the
// maxscale or the minscale. We don't want 3 levels and we don't want to modify the library
// so let's celebrate the invention of reflection!
image.attacher.run {
javaClass.getDeclaredField("mMinScale").run {
isAccessible = true
setFloat(image.attacher, 1f)
}
javaClass.getDeclaredField("mMidScale").run {
isAccessible = true
setFloat(image.attacher, 1f)
}
javaClass.getDeclaredField("mMaxScale").run {
isAccessible = true
setFloat(image.attacher, 3f)
}
}
}
override fun render(state: GalleryState) {
toolbar.setVisible(state.navigationVisible)
title = state.title
if (image.drawable == null) {
GlideApp.with(this)
.load(state.imagePath)
.dontAnimate()
.listener(GlideCompletionListener {
startPostponedEnterTransition()
})
.into(image)
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.gallery, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
optionsItemSelectedIntent.onNext(item.itemId)
return true
}
}
@@ -0,0 +1,25 @@
/*
* 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 presentation.feature.gallery
data class GalleryState(
val navigationVisible: Boolean = true,
val title: String = "",
val imagePath: String = ""
)
@@ -0,0 +1,29 @@
/*
* 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 presentation.feature.gallery
import io.reactivex.Observable
import presentation.common.base.QkView
interface GalleryView : QkView<GalleryState> {
val screenTouchedIntent: Observable<Unit>
val optionsItemSelectedIntent: Observable<Int>
}
@@ -0,0 +1,79 @@
/*
* 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 presentation.feature.gallery
import android.content.Context
import android.content.Intent
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.extensions.makeToast
import interactor.SaveImage
import io.reactivex.Flowable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.withLatestFrom
import presentation.common.base.QkViewModel
import repository.MessageRepository
import util.extensions.mapNotNull
import javax.inject.Inject
class GalleryViewModel(intent: Intent) : QkViewModel<GalleryView, GalleryState>(GalleryState()) {
@Inject lateinit var context: Context
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var saveImage: SaveImage
private val partIdFlowable = Flowable.just(intent)
.map { it.getLongExtra("partId", 0L) }
.filter { partId -> partId != 0L }
init {
appComponent.inject(this)
disposables += partIdFlowable
.mapNotNull { partId -> messageRepo.getPart(partId) }
.mapNotNull { part -> part.image }
.subscribe { path -> newState { it.copy(imagePath = path) } }
disposables += partIdFlowable
.mapNotNull { partId -> messageRepo.getMessageForPart(partId) }
.mapNotNull { message -> messageRepo.getConversation(message.threadId) }
.subscribe { conversation -> newState { it.copy(title = conversation.getTitle()) } }
}
override fun bindView(view: GalleryView) {
super.bindView(view)
// When the screen is touched, toggle the visibility of the navigation UI
view.screenTouchedIntent
.withLatestFrom(state, { _, state -> state.navigationVisible })
.map { navigationVisible -> !navigationVisible }
.autoDisposable(view.scope())
.subscribe { navigationVisible -> newState { it.copy(navigationVisible = navigationVisible) } }
// Save image to device
view.optionsItemSelectedIntent
.filter { itemId -> itemId == R.id.save }
.withLatestFrom(partIdFlowable.toObservable(), { _, partId -> partId })
.autoDisposable(view.scope())
.subscribe { partId -> saveImage.execute(partId) { context.makeToast(R.string.gallery_toast_saved) } }
}
}
@@ -0,0 +1,283 @@
/*
* 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 presentation.feature.main
import android.app.AlertDialog
import android.content.res.ColorStateList
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.StateListDrawable
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import com.jakewharton.rxbinding2.support.v4.widget.drawerOpen
import com.jakewharton.rxbinding2.view.clicks
import com.jakewharton.rxbinding2.widget.textChanges
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.extensions.dpToPx
import common.util.extensions.setBackgroundTint
import common.util.extensions.setVisible
import io.reactivex.Observable
import io.reactivex.rxkotlin.Observables
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.drawer_view.*
import kotlinx.android.synthetic.main.main_activity.*
import presentation.common.MenuItemAdapter
import presentation.common.Navigator
import presentation.common.base.QkThemedActivity
import presentation.feature.conversations.ConversationItemTouchCallback
import presentation.feature.conversations.ConversationsAdapter
import javax.inject.Inject
class MainActivity : QkThemedActivity<MainViewModel>(), MainView {
@Inject lateinit var navigator: Navigator
@Inject lateinit var conversationsAdapter: ConversationsAdapter
@Inject lateinit var itemTouchCallback: ConversationItemTouchCallback
@Inject lateinit var menuItemAdapter: MenuItemAdapter
override val viewModelClass = MainViewModel::class
override val queryChangedIntent by lazy { toolbarSearch.textChanges() }
override val queryCancelledIntent: PublishSubject<Unit> = PublishSubject.create()
override val composeIntent by lazy { compose.clicks() }
override val drawerOpenIntent by lazy { drawerLayout.drawerOpen(Gravity.START) }
override val drawerItemIntent: Observable<DrawerItem> by lazy {
Observable.merge(listOf(
inbox.clicks().map { DrawerItem.INBOX },
archived.clicks().map { DrawerItem.ARCHIVED },
scheduled.clicks().map { DrawerItem.SCHEDULED },
settings.clicks().map { DrawerItem.SETTINGS },
plus.clicks().map { DrawerItem.PLUS },
help.clicks().map { DrawerItem.HELP }))
}
override val conversationClickIntent by lazy { conversationsAdapter.clicks }
override val conversationLongClickIntent by lazy { conversationsAdapter.longClicks }
override val conversationMenuItemIntent by lazy { menuItemAdapter.menuItemClicks }
override val confirmDeleteIntent: Subject<Unit> = PublishSubject.create()
override val swipeConversationIntent by lazy { itemTouchCallback.swipes }
override val undoSwipeConversationIntent: Subject<Unit> = PublishSubject.create()
private val itemTouchHelper by lazy { ItemTouchHelper(itemTouchCallback) }
private val archiveSnackbar by lazy {
Snackbar.make(drawerLayout, R.string.toast_archived, Snackbar.LENGTH_INDEFINITE).apply {
setAction(R.string.button_undo, { undoSwipeConversationIntent.onNext(Unit) })
}
}
private var conversationMenuDialog: AlertDialog? = null
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
viewModel.bindView(this)
toolbarSearch.setHint(R.string.title_conversations)
val toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, 0, 0).apply { syncState() }
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager = LinearLayoutManager(this)
// Don't allow clicks to pass through the drawer layout
drawer.clicks().subscribe()
scheduled.isEnabled = false
colors.background
.doOnNext { color -> window.decorView.setBackgroundColor(color) }
.doOnNext { color -> drawer.setBackgroundColor(color) }
.autoDisposable(scope())
.subscribe()
val states = arrayOf(
intArrayOf(android.R.attr.state_selected),
intArrayOf(-android.R.attr.state_selected))
val rowBackground = { separator: Int ->
StateListDrawable().apply {
addState(intArrayOf(android.R.attr.state_selected), ColorDrawable(separator))
addState(intArrayOf(-android.R.attr.state_selected), getDrawable(R.drawable.ripple))
mutate()
}
}
// Set the theme color tint to the progressbar and FAB
colors.theme
.doOnNext { color -> syncingProgress.indeterminateTintList = ColorStateList.valueOf(color) }
.doOnNext { color -> compose.setBackgroundTint(color) }
.autoDisposable(scope())
.subscribe()
// Set the hamburger icon color
colors.textSecondary
.autoDisposable(scope())
.subscribe { color -> toggle.drawerArrowDrawable.color = color }
// Set the color for the drawer icons
Observables
.combineLatest(colors.theme, colors.textSecondary, { theme, textSecondary ->
ColorStateList(states, intArrayOf(theme, textSecondary))
})
.doOnNext { tintList -> inboxIcon.imageTintList = tintList }
.doOnNext { tintList -> archivedIcon.imageTintList = tintList }
.doOnNext { tintList -> scheduledIcon.imageTintList = tintList }
.doOnNext { tintList -> settingsIcon.imageTintList = tintList }
.doOnNext { tintList -> plusIcon.imageTintList = tintList }
.doOnNext { tintList -> helpIcon.imageTintList = tintList }
.autoDisposable(scope())
.subscribe()
// Set the background highlight for the drawer options
colors.separator
.doOnNext { color -> inbox.background = rowBackground(color) }
.doOnNext { color -> archived.background = rowBackground(color) }
.doOnNext { color -> scheduled.background = rowBackground(color) }
.autoDisposable(scope())
.subscribe()
conversationsAdapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
// If we're at the top, scroll up to show new conversations
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
val firstVisiblePosition = layoutManager.findFirstCompletelyVisibleItemPosition()
if (firstVisiblePosition == 0) {
recyclerView.scrollToPosition(positionStart)
}
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
onItemRangeInserted(positionStart, itemCount)
}
})
}
override fun render(state: MainState) {
toolbarSearch.isEnabled = state.page is Inbox
toolbarSearch.textSize = if (state.page is Inbox) 16f else 20f
toolbar.menu.findItem(R.id.clear)?.run {
isVisible = state.page is Inbox && state.page.showClearButton
}
syncing.setVisible(state.syncing)
recyclerView.setVisible(!state.syncing)
when (state.page) {
is Inbox -> {
if (!inbox.isSelected) toolbarSearch.text = null
if (recyclerView.adapter !== conversationsAdapter) recyclerView.adapter = conversationsAdapter
conversationsAdapter.flowable = state.page.data
itemTouchHelper.attachToRecyclerView(recyclerView)
menuItemAdapter.data = state.page.menu
empty.setText(R.string.inbox_empty_text)
empty.setVisible(state.page.empty && !state.syncing)
compose.setVisible(true)
}
is Archived -> {
if (!archived.isSelected) toolbarSearch.setText(R.string.title_archived)
if (recyclerView.adapter !== conversationsAdapter) recyclerView.adapter = conversationsAdapter
conversationsAdapter.flowable = state.page.data
itemTouchHelper.attachToRecyclerView(null)
menuItemAdapter.data = state.page.menu
empty.setText(R.string.archived_empty_text)
empty.setVisible(state.page.empty && !state.syncing)
compose.setVisible(true)
}
is Scheduled -> {
if (!scheduled.isSelected) toolbarSearch.setText(R.string.title_scheduled)
recyclerView.adapter = null
itemTouchHelper.attachToRecyclerView(null)
menuItemAdapter.data = ArrayList()
empty.setText(R.string.scheduled_empty_text)
empty.setVisible(state.page.empty && !state.syncing)
compose.setVisible(false)
}
}
when (state.page is Inbox && state.page.showArchivedSnackbar) {
true -> archiveSnackbar.show()
false -> archiveSnackbar.dismiss()
}
inbox.isSelected = state.page is Inbox
inboxIcon.isSelected = state.page is Inbox
archived.isSelected = state.page is Archived
archivedIcon.isSelected = state.page is Archived
scheduled.isSelected = state.page is Scheduled
scheduledIcon.isSelected = state.page is Scheduled
if (drawerLayout.isDrawerOpen(Gravity.START) && !state.drawerOpen) drawerLayout.closeDrawer(Gravity.START)
else if (!drawerLayout.isDrawerVisible(Gravity.START) && state.drawerOpen) drawerLayout.openDrawer(Gravity.START)
if (conversationMenuDialog?.isShowing == true && menuItemAdapter.data.isEmpty()) {
conversationMenuDialog?.dismiss()
conversationMenuDialog = null
} else if (conversationMenuDialog?.isShowing != true && menuItemAdapter.data.isNotEmpty()) {
val recyclerView = RecyclerView(this)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = menuItemAdapter
recyclerView.setPadding(0, 8.dpToPx(this), 0, 8.dpToPx(this))
conversationMenuDialog = AlertDialog.Builder(this).setView(recyclerView).create().apply {
setOnDismissListener { conversationMenuItemIntent.onNext(-1) }
show()
}
}
}
override fun clearSearch() {
toolbarSearch.text = null
}
override fun showDeleteDialog() {
AlertDialog.Builder(this)
.setTitle(R.string.dialog_delete_title)
.setMessage(R.string.dialog_delete_message)
.setPositiveButton(R.string.button_delete, { _, _ -> confirmDeleteIntent.onNext(Unit) })
.setNegativeButton(R.string.button_cancel, null)
.show()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.clear -> queryCancelledIntent.onNext(Unit)
else -> return super.onOptionsItemSelected(item)
}
return true
}
}
@@ -0,0 +1,48 @@
/*
* 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 presentation.feature.main
import io.reactivex.Flowable
import model.Conversation
import model.Message
import presentation.common.MenuItem
data class MainState(
val page: MainPage = Inbox(),
val drawerOpen: Boolean = false,
val syncing: Boolean = false
)
sealed class MainPage
data class Inbox(
val showClearButton: Boolean = false,
val data: Flowable<List<Pair<Conversation, Message>>>? = null,
val empty: Boolean = false,
val menu: List<MenuItem> = ArrayList(),
val showArchivedSnackbar: Boolean = false) : MainPage()
data class Archived(
val data: Flowable<List<Pair<Conversation, Message>>>?,
val empty: Boolean = false,
val menu: List<MenuItem> = ArrayList()) : MainPage()
data class Scheduled(
val data: Any? = null,
val empty: Boolean = false) : MainPage()
@@ -0,0 +1,43 @@
/*
* 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 presentation.feature.main
import io.reactivex.Observable
import presentation.common.base.QkView
interface MainView : QkView<MainState> {
val queryChangedIntent: Observable<CharSequence>
val queryCancelledIntent: Observable<*>
val composeIntent: Observable<Unit>
val drawerOpenIntent: Observable<Boolean>
val drawerItemIntent: Observable<DrawerItem>
val conversationClickIntent: Observable<Long>
val conversationLongClickIntent: Observable<Long>
val conversationMenuItemIntent: Observable<Int>
val confirmDeleteIntent: Observable<Unit>
val swipeConversationIntent: Observable<Int>
val undoSwipeConversationIntent: Observable<Unit>
fun clearSearch()
fun showDeleteDialog()
}
enum class DrawerItem { INBOX, ARCHIVED, SCHEDULED, BLOCKED, SETTINGS, PLUS, HELP }
@@ -0,0 +1,264 @@
/*
* 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 presentation.feature.main
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.provider.Telephony
import android.support.v4.content.ContextCompat
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.filter.ConversationFilter
import interactor.DeleteConversation
import interactor.MarkAllSeen
import interactor.MarkArchived
import interactor.MarkUnarchived
import interactor.MigratePreferences
import interactor.PartialSync
import io.reactivex.Observable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.withLatestFrom
import io.realm.Realm
import model.SyncLog
import presentation.common.MenuItem
import presentation.common.Navigator
import presentation.common.base.QkViewModel
import repository.MessageRepository
import util.Preferences
import util.extensions.toFlowable
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class MainViewModel : QkViewModel<MainView, MainState>(MainState()) {
@Inject lateinit var context: Context
@Inject lateinit var navigator: Navigator
@Inject lateinit var conversationFilter: ConversationFilter
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var markAllSeen: MarkAllSeen
@Inject lateinit var deleteConversation: DeleteConversation
@Inject lateinit var markArchived: MarkArchived
@Inject lateinit var markUnarchived: MarkUnarchived
@Inject lateinit var migratePreferences: MigratePreferences
@Inject lateinit var partialSync: PartialSync
@Inject lateinit var prefs: Preferences
private val conversations by lazy {
messageRepo.getConversations()
.withLatestFrom(state.toFlowable(), { conversations, state ->
(state.page as? Inbox)?.let { page ->
newState { it.copy(page = page.copy(empty = conversations.isEmpty())) }
}
conversations
})
}
private val archivedConversations by lazy {
messageRepo.getConversations(true)
.withLatestFrom(state.toFlowable(), { conversations, state ->
(state.page as? Archived)?.let { page ->
newState { it.copy(page = page.copy(empty = conversations.isEmpty())) }
}
conversations
})
}
private val menuArchive by lazy { MenuItem(context.getString(R.string.menu_archive), 0) }
private val menuUnarchive by lazy { MenuItem(context.getString(R.string.menu_unarchive), 1) }
private val menuDelete by lazy { MenuItem(context.getString(R.string.menu_delete), 2) }
init {
appComponent.inject(this)
disposables += deleteConversation
disposables += markAllSeen
disposables += markArchived
disposables += markUnarchived
disposables += migratePreferences
disposables += partialSync
// If it's the first sync, reflect that in the ViewState
disposables += Realm.getDefaultInstance()
.where(SyncLog::class.java)
.findAll()
.asFlowable()
.filter { it.isLoaded }
.map { it.size == 0 }
.doOnNext { if (it) partialSync.execute(Unit) }
.distinctUntilChanged()
.subscribe { syncing -> newState { it.copy(syncing = syncing) } }
newState { it.copy(page = Inbox(data = conversations)) }
// Migrate the preferences from 2.7.3 if necessary
migratePreferences.execute(Unit)
val isNotDefaultSms = Telephony.Sms.getDefaultSmsPackage(context) != context.packageName
val hasSmsPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED
val hasContactPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
if (isNotDefaultSms) {
partialSync.execute(Unit)
}
if (isNotDefaultSms || !hasSmsPermission || !hasContactPermission) {
navigator.showSetupActivity()
}
markAllSeen.execute(Unit)
}
override fun bindView(view: MainView) {
super.bindView(view)
view.queryChangedIntent
.skip(1)
.debounce(200, TimeUnit.MILLISECONDS)
.withLatestFrom(state, { query, state ->
if (state.page is Inbox) {
val conversations = when {
query.isEmpty() -> conversations
else -> conversations.map { list -> list.filter { conversationFilter.filter(it.first, query) } }
}
val page = state.page.copy(showClearButton = query.isNotEmpty(), data = conversations)
newState { it.copy(page = page) }
}
})
.autoDisposable(view.scope())
.subscribe()
view.queryCancelledIntent
.autoDisposable(view.scope())
.subscribe { view.clearSearch() }
view.composeIntent
.autoDisposable(view.scope())
.subscribe { navigator.showCompose() }
view.drawerOpenIntent
.autoDisposable(view.scope())
.subscribe { open -> newState { it.copy(drawerOpen = open) } }
view.drawerItemIntent
.doOnNext { newState { it.copy(drawerOpen = false) } }
.doOnNext { if (it == DrawerItem.SETTINGS) navigator.showSettings() }
.doOnNext { if (it == DrawerItem.PLUS) navigator.showQksmsPlusActivity() }
.doOnNext { if (it == DrawerItem.HELP) navigator.showSupport() }
.distinctUntilChanged()
.doOnNext {
when (it) {
DrawerItem.INBOX -> newState { it.copy(page = Inbox(data = conversations)) }
DrawerItem.ARCHIVED -> newState { it.copy(page = Archived(archivedConversations)) }
DrawerItem.SCHEDULED -> newState { it.copy(page = Scheduled()) }
else -> {
} // Do nothing
}
}
.autoDisposable(view.scope())
.subscribe()
view.conversationClickIntent
.doOnNext { view.clearSearch() }
.doOnNext { threadId -> navigator.showConversation(threadId) }
.autoDisposable(view.scope())
.subscribe()
view.conversationLongClickIntent
.withLatestFrom(state, { _, mainState ->
when (mainState.page) {
is Inbox -> {
val page = mainState.page.copy(menu = listOf(menuArchive, menuDelete))
newState { it.copy(page = page) }
}
is Archived -> {
val page = mainState.page.copy(menu = listOf(menuUnarchive, menuDelete))
newState { it.copy(page = page) }
}
}
})
.autoDisposable(view.scope())
.subscribe()
view.conversationMenuItemIntent
.withLatestFrom(state, { actionId, mainState ->
when (mainState.page) {
is Inbox -> {
val page = mainState.page.copy(menu = ArrayList())
newState { it.copy(page = page) }
}
is Archived -> {
val page = mainState.page.copy(menu = ArrayList())
newState { it.copy(page = page) }
}
}
actionId
})
.withLatestFrom(view.conversationLongClickIntent, { actionId, threadId ->
when (actionId) {
menuArchive.actionId -> markArchived.execute(threadId)
menuUnarchive.actionId -> markUnarchived.execute(threadId)
menuDelete.actionId -> view.showDeleteDialog()
}
})
.autoDisposable(view.scope())
.subscribe()
// Delete the conversation
view.confirmDeleteIntent
.withLatestFrom(view.conversationLongClickIntent, { _, threadId -> threadId })
.autoDisposable(view.scope())
.subscribe { threadId -> deleteConversation.execute(threadId) }
val swipedConversation = view.swipeConversationIntent
.withLatestFrom(conversations.toObservable(), { position, conversations -> conversations[position] })
.map { pair -> pair.first }
.map { conversation -> conversation.id }
swipedConversation
.withLatestFrom(state, { threadId, state ->
markArchived.execute(threadId) {
if (state.page is Inbox) {
val page = state.page.copy(showArchivedSnackbar = true)
newState { it.copy(page = page) }
}
}
})
.switchMap { Observable.timer(2750, TimeUnit.MILLISECONDS) }
.withLatestFrom(state, { threadId, state ->
markArchived.execute(threadId) {
if (state.page is Inbox) {
val page = state.page.copy(showArchivedSnackbar = false)
newState { it.copy(page = page) }
}
}
})
.autoDisposable(view.scope())
.subscribe()
view.undoSwipeConversationIntent
.withLatestFrom(swipedConversation, { _, threadId -> threadId })
.autoDisposable(view.scope())
.subscribe { threadId -> markUnarchived.execute(threadId) }
}
}
@@ -0,0 +1,105 @@
/*
* 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 presentation.feature.notificationprefs
import android.app.Activity
import android.content.Intent
import android.media.RingtoneManager
import android.net.Uri
import android.os.Bundle
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.notification_prefs_activity.*
import kotlinx.android.synthetic.main.settings_switch_widget.view.*
import presentation.common.MenuItemAdapter
import presentation.common.base.QkThemedActivity
import presentation.common.widget.PreferenceView
import javax.inject.Inject
class NotificationPrefsActivity : QkThemedActivity<NotificationPrefsViewModel>(), NotificationPrefsView {
@Inject lateinit var nightModeAdapter: MenuItemAdapter
@Inject lateinit var mmsSizeAdapter: MenuItemAdapter
override val viewModelClass = NotificationPrefsViewModel::class
override val preferenceClickIntent: Subject<PreferenceView> = PublishSubject.create()
override val ringtoneSelectedIntent: Subject<String> = PublishSubject.create()
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.notification_prefs_activity)
setTitle(R.string.title_notification_prefs)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
nightModeAdapter.setData(R.array.night_modes)
mmsSizeAdapter.setData(R.array.mms_sizes, R.array.mms_sizes_ids)
colors.background
.autoDisposable(scope())
.subscribe { color -> window.decorView.setBackgroundColor(color) }
// Listen to clicks for all of the preferences
(0 until preferences.childCount)
.map { index -> preferences.getChildAt(index) }
.filter { view -> view is PreferenceView }
.forEach { preference ->
preference.clicks().subscribe {
preferenceClickIntent.onNext(preference as PreferenceView)
}
}
}
override fun render(state: NotificationPrefsState) {
if (state.conversationTitle.isNotEmpty()) {
title = state.conversationTitle
}
notifications.checkbox.isChecked = state.notificationsEnabled
vibration.checkbox.isChecked = state.vibrationEnabled
ringtone.summary = state.ringtoneName
}
override fun showRingtonePicker(default: Uri) {
val intent = Intent(RingtoneManager.ACTION_RINGTONE_PICKER)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, default)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION)
startActivityForResult(intent, 123)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 123 && resultCode == Activity.RESULT_OK) {
val uri: Uri? = data?.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI)
uri?.let { ringtoneSelectedIntent.onNext(uri.toString()) }
}
}
}
@@ -0,0 +1,26 @@
/*
* 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 presentation.feature.notificationprefs
data class NotificationPrefsState(
val conversationTitle: String = "",
val notificationsEnabled: Boolean = true,
val vibrationEnabled: Boolean = true,
val ringtoneName: String = ""
)
@@ -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 presentation.feature.notificationprefs
import android.net.Uri
import io.reactivex.Observable
import io.reactivex.subjects.Subject
import presentation.common.base.QkView
import presentation.common.widget.PreferenceView
interface NotificationPrefsView : QkView<NotificationPrefsState> {
val preferenceClickIntent: Subject<PreferenceView>
val ringtoneSelectedIntent: Observable<String>
fun showRingtonePicker(default: Uri)
}
@@ -0,0 +1,101 @@
/*
* 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 presentation.feature.notificationprefs
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.net.Uri
import androidx.net.toUri
import com.f2prateek.rx.preferences2.Preference
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import util.Preferences
import io.reactivex.Flowable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.schedulers.Schedulers
import presentation.common.Navigator
import presentation.common.base.QkViewModel
import repository.MessageRepository
import timber.log.Timber
import util.extensions.mapNotNull
import javax.inject.Inject
class NotificationPrefsViewModel(intent: Intent) : QkViewModel<NotificationPrefsView, NotificationPrefsState>(NotificationPrefsState()) {
@Inject lateinit var context: Context
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var navigator: Navigator
@Inject lateinit var prefs: Preferences
private val threadId = intent.extras?.getLong("threadId") ?: 0L
private val notifications: Preference<Boolean>
private val vibration: Preference<Boolean>
private val ringtone: Preference<String>
init {
appComponent.inject(this)
notifications = prefs.notifications(threadId)
vibration = prefs.vibration(threadId)
ringtone = prefs.ringtone(threadId)
disposables += Flowable.just(threadId)
.mapNotNull { threadId -> messageRepo.getConversation(threadId) }
.map { conversation -> conversation.getTitle() }
.subscribeOn(Schedulers.io())
.subscribe { title -> newState { it.copy(conversationTitle = title) } }
disposables += notifications.asObservable()
.subscribe { enabled -> newState { it.copy(notificationsEnabled = enabled) } }
disposables += vibration.asObservable()
.subscribe { enabled -> newState { it.copy(vibrationEnabled = enabled) } }
disposables += ringtone.asObservable()
.map { uri -> uri.toUri() }
.map { uri -> RingtoneManager.getRingtone(context, uri).getTitle(context) }
.subscribe { title -> newState { it.copy(ringtoneName = title) } }
}
override fun bindView(view: NotificationPrefsView) {
super.bindView(view)
view.preferenceClickIntent
.autoDisposable(view.scope())
.subscribe {
Timber.v("Preference click: ${context.resources.getResourceName(it.id)}")
when (it.id) {
R.id.notifications -> notifications.set(!notifications.get())
R.id.vibration -> vibration.set(!vibration.get())
R.id.ringtone -> view.showRingtonePicker(Uri.parse(ringtone.get()))
}
}
view.ringtoneSelectedIntent
.autoDisposable(view.scope())
.subscribe { ringtone -> this.ringtone.set(ringtone) }
}
}
@@ -0,0 +1,99 @@
/*
* 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 presentation.feature.plus
import android.graphics.Typeface
import android.os.Bundle
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.BillingManager
import common.util.FontProvider
import common.util.extensions.setBackgroundTint
import common.util.extensions.setTint
import common.util.extensions.setVisible
import kotlinx.android.synthetic.main.qksms_plus_activity.*
import presentation.common.base.QkThemedActivity
import javax.inject.Inject
class PlusActivity : QkThemedActivity<PlusViewModel>(), PlusView {
@Inject lateinit var fontProvider: FontProvider
override val viewModelClass = PlusViewModel::class
override val upgradeIntent by lazy { upgrade.clicks() }
override val upgradeDonateIntent by lazy { upgradeDonate.clicks() }
override fun onCreate(savedInstanceState: Bundle?) {
appComponent.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.qksms_plus_activity)
setTitle(R.string.title_qksms_plus)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
fontProvider.getLato {
val typeface = Typeface.create(it, Typeface.BOLD)
collapsingToolbar.setCollapsedTitleTypeface(typeface)
collapsingToolbar.setExpandedTitleTypeface(typeface)
}
colors.textPrimary
.autoDisposable(scope())
.subscribe { color ->
collapsingToolbar.setCollapsedTitleTextColor(color)
collapsingToolbar.setExpandedTitleColor(color)
}
colors.background
.autoDisposable(scope())
.subscribe { color -> window.decorView.setBackgroundColor(color) }
colors.separator
.autoDisposable(scope())
.subscribe { color ->
upgradeDonate.setBackgroundTint(color)
thanks.setBackgroundTint(color)
}
colors.theme
.autoDisposable(scope())
.subscribe { color ->
upgrade.setBackgroundTint(color)
thanksIcon.setTint(color)
}
}
override fun render(state: PlusState) {
description.text = getString(R.string.qksms_plus_description_summary, state.upgradePrice)
upgrade.text = getString(R.string.qksms_plus_upgrade, state.upgradePrice, state.currency)
upgradeDonate.text = getString(R.string.qksms_plus_upgrade_donate, state.upgradeDonatePrice, state.currency)
upgrade.setVisible(state.currentPlan == BillingManager.UpgradeStatus.REGULAR)
upgradeDonate.setVisible(state.currentPlan == BillingManager.UpgradeStatus.REGULAR)
thanks.setVisible(state.currentPlan != BillingManager.UpgradeStatus.REGULAR)
}
override fun initiatePurchaseFlow(billingManager: BillingManager, sku: String) {
billingManager.initiatePurchaseFlow(this, sku)
}
}
@@ -0,0 +1,28 @@
/*
* 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 presentation.feature.plus
import common.util.BillingManager
data class PlusState(
val currentPlan: BillingManager.UpgradeStatus = BillingManager.UpgradeStatus.REGULAR,
val upgradePrice: String = "",
val upgradeDonatePrice: String = "",
val currency: String = ""
)
@@ -0,0 +1,32 @@
/*
* 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 presentation.feature.plus
import common.util.BillingManager
import io.reactivex.Observable
import presentation.common.base.QkView
interface PlusView : QkView<PlusState> {
val upgradeIntent: Observable<Unit>
val upgradeDonateIntent: Observable<Unit>
fun initiatePurchaseFlow(billingManager: BillingManager, sku: String)
}
@@ -0,0 +1,63 @@
/*
* 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 presentation.feature.plus
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.BillingManager
import io.reactivex.Observable
import io.reactivex.rxkotlin.plusAssign
import presentation.common.base.QkViewModel
import javax.inject.Inject
class PlusViewModel : QkViewModel<PlusView, PlusState>(PlusState()) {
@Inject lateinit var billingManager: BillingManager
init {
appComponent.inject(this)
disposables += billingManager.plusStatus
.subscribe { plan ->
newState { it.copy(currentPlan = plan) }
}
disposables += billingManager.products
.subscribe { products ->
newState {
val upgrade = products.firstOrNull { it.sku == BillingManager.SKU_PLUS }
val upgradeDonate = products.firstOrNull { it.sku == BillingManager.SKU_PLUS_DONATE }
it.copy(upgradePrice = upgrade?.price ?: "", upgradeDonatePrice = upgradeDonate?.price ?: "",
currency = upgrade?.priceCurrencyCode ?: upgradeDonate?.priceCurrencyCode ?: "")
}
}
}
override fun bindView(view: PlusView) {
super.bindView(view)
Observable.merge(
view.upgradeIntent.map { BillingManager.SKU_PLUS },
view.upgradeDonateIntent.map { BillingManager.SKU_PLUS_DONATE })
.autoDisposable(view.scope())
.subscribe { sku -> view.initiatePurchaseFlow(billingManager, sku) }
}
}
@@ -0,0 +1,176 @@
/*
* 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 presentation.feature.settings
import android.app.AlertDialog
import android.app.ProgressDialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import util.Preferences
import common.util.extensions.dpToPx
import common.util.extensions.setVisible
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.settings_activity.*
import kotlinx.android.synthetic.main.settings_switch_widget.view.*
import presentation.common.MenuItemAdapter
import presentation.common.base.QkThemedActivity
import presentation.common.widget.PreferenceView
import javax.inject.Inject
class SettingsActivity : QkThemedActivity<SettingsViewModel>(), SettingsView {
@Inject lateinit var nightModeAdapter: MenuItemAdapter
@Inject lateinit var mmsSizeAdapter: MenuItemAdapter
override val viewModelClass = SettingsViewModel::class
override val preferenceClickIntent: Subject<PreferenceView> = PublishSubject.create()
override val nightModeSelectedIntent by lazy { nightModeAdapter.menuItemClicks }
override val viewQksmsPlusIntent: Subject<Unit> = PublishSubject.create()
override val startTimeSelectedIntent: Subject<Pair<Int, Int>> = PublishSubject.create()
override val endTimeSelectedIntent: Subject<Pair<Int, Int>> = PublishSubject.create()
override val mmsSizeSelectedIntent: Subject<Int> by lazy { mmsSizeAdapter.menuItemClicks }
// TODO remove this
private val progressDialog by lazy {
ProgressDialog(this).apply {
isIndeterminate = true
setCancelable(false)
setCanceledOnTouchOutside(false)
}
}
private var nightModeDialog: AlertDialog? = null
private var mmsSizeDialog: AlertDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
appComponent.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.settings_activity)
setTitle(R.string.title_settings)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
nightModeAdapter.setData(R.array.night_modes)
mmsSizeAdapter.setData(R.array.mms_sizes, R.array.mms_sizes_ids)
colors.background
.autoDisposable(scope())
.subscribe { color -> window.decorView.setBackgroundColor(color) }
// Listen to clicks for all of the preferences
(0 until preferences.childCount)
.map { index -> preferences.getChildAt(index) }
.filter { view -> view is PreferenceView }
.forEach { preference ->
preference.clicks().subscribe {
preferenceClickIntent.onNext(preference as PreferenceView)
}
}
}
override fun render(state: SettingsState) {
if (progressDialog.isShowing && !state.syncing) progressDialog.dismiss()
else if (!progressDialog.isShowing && state.syncing) progressDialog.show()
defaultSms.summary = getString(when (state.isDefaultSmsApp) {
true -> R.string.settings_default_sms_summary_true
else -> R.string.settings_default_sms_summary_false
})
night.summary = state.nightModeSummary
nightStart.setVisible(state.nightModeId == Preferences.NIGHT_MODE_AUTO)
nightStart.summary = state.nightStart
nightEnd.setVisible(state.nightModeId == Preferences.NIGHT_MODE_AUTO)
nightEnd.summary = state.nightEnd
black.setVisible(state.nightModeId != Preferences.NIGHT_MODE_OFF)
black.checkbox.isChecked = state.black
autoEmoji.checkbox.isChecked = state.autoEmojiEnabled
delivery.checkbox.isChecked = state.deliveryEnabled
unicode.checkbox.isChecked = state.stripUnicodeEnabled
mms.checkbox.isChecked = state.mmsEnabled
mmsSize.summary = state.maxMmsSizeSummary
mmsSizeAdapter.selectedItem = state.maxMmsSizeId
}
// TODO change this to a PopupWindow
override fun showNightModeDialog() {
val recyclerView = RecyclerView(this)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = nightModeAdapter
recyclerView.setPadding(0, 8.dpToPx(this), 0, 8.dpToPx(this))
nightModeDialog = AlertDialog.Builder(this)
.setTitle(R.string.settings_night_title)
.setView(recyclerView)
.create().apply { show() }
}
override fun dismissNightModeDialog() {
nightModeDialog?.dismiss()
nightModeDialog = null
}
override fun showQksmsPlusSnackbar() {
Snackbar.make(contentView, R.string.toast_qksms_plus, Snackbar.LENGTH_LONG).run {
setAction(R.string.button_more, { viewQksmsPlusIntent.onNext(Unit) })
show()
}
}
override fun showStartTimePicker(hour: Int, minute: Int) {
TimePickerDialog(this, TimePickerDialog.OnTimeSetListener { _, newHour, newMinute ->
startTimeSelectedIntent.onNext(Pair(newHour, newMinute))
}, hour, minute, false).show()
}
override fun showEndTimePicker(hour: Int, minute: Int) {
TimePickerDialog(this, TimePickerDialog.OnTimeSetListener { _, newHour, newMinute ->
endTimeSelectedIntent.onNext(Pair(newHour, newMinute))
}, hour, minute, false).show()
}
override fun showMmsSizePicker() {
val recyclerView = RecyclerView(this)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = mmsSizeAdapter
recyclerView.setPadding(0, 8.dpToPx(this), 0, 8.dpToPx(this))
mmsSizeDialog = AlertDialog.Builder(this)
.setTitle(R.string.settings_mms_size_title)
.setNegativeButton(R.string.button_cancel, null)
.setView(recyclerView)
.create().apply { show() }
}
override fun dismissMmsSizePicker() {
mmsSizeDialog?.dismiss()
mmsSizeDialog = null
}
}
@@ -0,0 +1,40 @@
/*
* 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 presentation.feature.settings
import util.Preferences
data class SettingsState(
val syncing: Boolean = false,
val isDefaultSmsApp: Boolean = false,
val nightModeSummary: String = "",
val nightModeId: Int = Preferences.NIGHT_MODE_OFF,
val nightStart: String = "",
val nightEnd: String = "",
val black: Boolean = false,
val autoEmojiEnabled: Boolean = true,
val notificationsEnabled: Boolean = true,
val deliveryEnabled: Boolean = false,
val splitSmsEnabled: Boolean = false,
val stripUnicodeEnabled: Boolean = false,
val mmsEnabled: Boolean = true,
val maxMmsSizeSummary: String = "100KB",
val maxMmsSizeId: Int = 100
)
@@ -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 presentation.feature.settings
import io.reactivex.Observable
import io.reactivex.subjects.Subject
import presentation.common.base.QkView
import presentation.common.widget.PreferenceView
interface SettingsView : QkView<SettingsState> {
val preferenceClickIntent: Subject<PreferenceView>
val nightModeSelectedIntent: Observable<Int>
val viewQksmsPlusIntent: Subject<Unit>
val startTimeSelectedIntent: Subject<Pair<Int, Int>>
val endTimeSelectedIntent: Subject<Pair<Int, Int>>
val mmsSizeSelectedIntent: Observable<Int>
fun showNightModeDialog()
fun dismissNightModeDialog()
fun showQksmsPlusSnackbar()
fun showStartTimePicker(hour: Int, minute: Int)
fun showEndTimePicker(hour: Int, minute: Int)
fun showMmsSizePicker()
fun dismissMmsSizePicker()
}
@@ -0,0 +1,182 @@
/*
* 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 presentation.feature.settings
import android.content.Context
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.BillingManager
import common.util.DateFormatter
import common.util.NightModeManager
import util.Preferences
import interactor.FullSync
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.withLatestFrom
import presentation.common.Navigator
import presentation.common.base.QkViewModel
import timber.log.Timber
import java.util.*
import javax.inject.Inject
class SettingsViewModel : QkViewModel<SettingsView, SettingsState>(SettingsState()) {
@Inject lateinit var context: Context
@Inject lateinit var billingManager: BillingManager
@Inject lateinit var dateFormatter: DateFormatter
@Inject lateinit var navigator: Navigator
@Inject lateinit var nightModeManager: NightModeManager
@Inject lateinit var prefs: Preferences
@Inject lateinit var fullSync: FullSync
init {
appComponent.inject(this)
disposables += prefs.defaultSms
.asObservable()
.subscribe { isDefaultSmsApp ->
newState { it.copy(isDefaultSmsApp = isDefaultSmsApp) }
}
val nightModeLabels = context.resources.getStringArray(R.array.night_modes)
disposables += prefs.nightMode.asObservable()
.subscribe { nightMode ->
newState { it.copy(nightModeSummary = nightModeLabels[nightMode], nightModeId = nightMode) }
}
disposables += prefs.nightStart.asObservable()
.subscribe { nightStart -> newState { it.copy(nightStart = nightStart) } }
disposables += prefs.nightEnd.asObservable()
.subscribe { nightEnd -> newState { it.copy(nightEnd = nightEnd) } }
disposables += prefs.black.asObservable()
.subscribe { black -> newState { it.copy(black = black) } }
disposables += prefs.autoEmoji.asObservable()
.subscribe { enabled -> newState { it.copy(autoEmojiEnabled = enabled) } }
disposables += prefs.notifications().asObservable()
.subscribe { enabled -> newState { it.copy(notificationsEnabled = enabled) } }
disposables += prefs.delivery.asObservable()
.subscribe { enabled -> newState { it.copy(deliveryEnabled = enabled) } }
disposables += prefs.unicode.asObservable()
.subscribe { enabled -> newState { it.copy(stripUnicodeEnabled = enabled) } }
disposables += prefs.mms.asObservable()
.subscribe { enabled -> newState { it.copy(mmsEnabled = enabled) } }
val mmsSizeLabels = context.resources.getStringArray(R.array.mms_sizes)
val mmsSizeIds = context.resources.getIntArray(R.array.mms_sizes_ids)
disposables += prefs.mmsSize.asObservable()
.subscribe { maxMmsSize ->
val index = mmsSizeIds.indexOf(maxMmsSize)
newState { it.copy(maxMmsSizeSummary = mmsSizeLabels[index], maxMmsSizeId = maxMmsSize) }
}
disposables += fullSync
}
override fun bindView(view: SettingsView) {
super.bindView(view)
view.preferenceClickIntent
.autoDisposable(view.scope())
.subscribe {
Timber.v("Preference click: ${context.resources.getResourceName(it.id)}")
when (it.id) {
R.id.defaultSms -> navigator.showDefaultSmsDialog()
R.id.theme -> navigator.showThemePicker()
R.id.night -> view.showNightModeDialog()
R.id.nightStart -> {
val date = dateFormatter.parseTime(prefs.nightStart.get())
view.showStartTimePicker(date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE))
}
R.id.nightEnd -> {
val date = dateFormatter.parseTime(prefs.nightEnd.get())
view.showEndTimePicker(date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE))
}
R.id.black -> prefs.black.set(!prefs.black.get())
R.id.autoEmoji -> prefs.autoEmoji.set(!prefs.autoEmoji.get())
R.id.notifications -> navigator.showNotificationSettings()
R.id.blocked -> navigator.showBlockedConversations()
R.id.delivery -> prefs.delivery.set(!prefs.delivery.get())
R.id.unicode -> prefs.unicode.set(!prefs.unicode.get())
R.id.mms -> prefs.mms.set(!prefs.mms.get())
R.id.mmsSize -> view.showMmsSizePicker()
R.id.sync -> {
newState { it.copy(syncing = true) }
fullSync.execute(Unit, {
newState { it.copy(syncing = false) }
})
}
}
}
view.nightModeSelectedIntent
.doOnNext { view.dismissNightModeDialog() }
.withLatestFrom(billingManager.plusStatus, { mode, plusStatus ->
if (plusStatus == BillingManager.UpgradeStatus.REGULAR && mode == Preferences.NIGHT_MODE_AUTO) {
view.showQksmsPlusSnackbar()
} else {
nightModeManager.updateNightMode(mode)
}
})
.autoDisposable(view.scope())
.subscribe()
view.viewQksmsPlusIntent
.autoDisposable(view.scope())
.subscribe { navigator.showQksmsPlusActivity() }
view.startTimeSelectedIntent
.doOnNext { nightModeManager.updateAlarms() }
.map { dateFormatter.formatTime(it.first, it.second) }
.autoDisposable(view.scope())
.subscribe { prefs.nightStart.set(it) }
view.endTimeSelectedIntent
.doOnNext { nightModeManager.updateAlarms() }
.map { dateFormatter.formatTime(it.first, it.second) }
.autoDisposable(view.scope())
.subscribe { prefs.nightEnd.set(it) }
view.mmsSizeSelectedIntent
.doOnNext { view.dismissMmsSizePicker() }
.autoDisposable(view.scope())
.subscribe { prefs.mmsSize.set(it) }
}
}
@@ -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 presentation.feature.setup
import android.Manifest
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.setup_activity.*
import presentation.common.Navigator
import presentation.common.base.QkThemedActivity
import javax.inject.Inject
class SetupActivity : QkThemedActivity<SetupViewModel>(), SetupView {
override val viewModelClass = SetupViewModel::class
override val activityResumedIntent: Subject<Unit> = PublishSubject.create()
override val skipIntent by lazy { skip.clicks() }
override val nextIntent by lazy { next.clicks() }
@Inject lateinit var navigator: Navigator
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.setup_activity)
viewModel.bindView(this)
colors.background
.autoDisposable(scope())
.subscribe { color -> window.decorView.setBackgroundColor(color) }
}
override fun onResume() {
super.onResume()
activityResumedIntent.onNext(Unit)
}
override fun render(state: SetupState) {
}
override fun requestDefaultSms() {
navigator.showDefaultSmsDialog()
}
override fun requestPermissions() {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CONTACTS, Manifest.permission.READ_SMS), 0)
}
}
@@ -0,0 +1,21 @@
/*
* 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 presentation.feature.setup
class SetupState
@@ -0,0 +1,34 @@
/*
* 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 presentation.feature.setup
import io.reactivex.Observable
import presentation.common.base.QkView
interface SetupView : QkView<SetupState> {
val activityResumedIntent: Observable<*>
val skipIntent: Observable<*>
val nextIntent: Observable<*>
fun requestDefaultSms()
fun requestPermissions()
fun finish()
}
@@ -0,0 +1,60 @@
/*
* 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 presentation.feature.setup
import android.content.Context
import android.provider.Telephony
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import manager.PermissionManager
import presentation.common.base.QkViewModel
import javax.inject.Inject
class SetupViewModel : QkViewModel<SetupView, SetupState>(SetupState()) {
@Inject lateinit var context: Context
@Inject lateinit var permissions: PermissionManager
init {
appComponent.inject(this)
}
override fun bindView(view: SetupView) {
super.bindView(view)
view.activityResumedIntent
.autoDisposable(view.scope())
.subscribe {
val isDefault = Telephony.Sms.getDefaultSmsPackage(context) == context.packageName
if (!permissions.hasSmsAndContacts()) view.requestPermissions()
else if (isDefault) view.finish()
}
view.skipIntent
.autoDisposable(view.scope())
.subscribe { view.finish() }
view.nextIntent
.autoDisposable(view.scope())
.subscribe { view.requestDefaultSms() }
}
}
@@ -0,0 +1,133 @@
/*
* 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 presentation.feature.themepicker
import android.content.Context
import android.content.res.Resources
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayout
import com.moez.QKSMS.R
import common.util.Colors
import common.util.extensions.dpToPx
import common.util.extensions.setBackgroundTint
import common.util.extensions.setTint
import common.util.extensions.setVisible
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.theme_list_item.view.*
import kotlinx.android.synthetic.main.theme_palette_list_item.view.*
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import javax.inject.Inject
class ThemeAdapter @Inject constructor(
private val context: Context,
private val colors: Colors
) : QkAdapter<List<Int>>() {
var threadId: Long = 0
set(value) {
field = value
threadIdChanged()
}
val colorSelected: Subject<Int> = PublishSubject.create()
var selectedColor: Int = -1
set(value) {
val oldPosition = data.indexOfFirst { it.contains(field) }
val newPosition = data.indexOfFirst { it.contains(value) }
field = value
oldPosition.takeIf { it != -1 }?.let { position -> notifyItemChanged(position) }
newPosition.takeIf { it != -1 }?.let { position -> notifyItemChanged(position) }
}
private var iconTint = 0
private val disposables = CompositeDisposable()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.theme_palette_list_item, parent, false)
view.palette.flexWrap = FlexWrap.WRAP
view.palette.flexDirection = FlexDirection.ROW
return QkViewHolder(view)
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val palette = getItem(position)
val view = holder.itemView
val screenWidth = Resources.getSystem().displayMetrics.widthPixels
val minPadding = (16 * 6).dpToPx(context)
val size = if (screenWidth - minPadding > (56 * 5).dpToPx(context)) {
56.dpToPx(context)
} else {
(screenWidth - minPadding) / 5
}
val swatchPadding = (screenWidth - size * 5) / 12
view.palette.removeAllViews()
view.palette.setPadding(swatchPadding, swatchPadding, swatchPadding, swatchPadding)
(palette.subList(0, 5) + palette.subList(5, 10).reversed())
.mapIndexed { index, color ->
LayoutInflater.from(context).inflate(R.layout.theme_list_item, view.palette, false).apply {
// Send clicks to the selected subject
setOnClickListener { colorSelected.onNext(color) }
// Apply the color to the view
theme.setBackgroundTint(color)
// Control the check visibility and tint
check.setVisible(color == selectedColor)
check.setTint(iconTint)
// Update the size so that the spacing is perfectly even
layoutParams = (layoutParams as FlexboxLayout.LayoutParams).apply {
height = size
width = size
isWrapBefore = index % 5 == 0
setMargins(swatchPadding, swatchPadding, swatchPadding, swatchPadding)
}
}
}
.forEach { theme -> view.palette.addView(theme) }
}
private fun threadIdChanged() {
disposables.clear()
disposables += colors.textPrimaryOnThemeForConversation(threadId)
.subscribe { color -> iconTint = color }
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
disposables.clear()
}
}
@@ -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 presentation.feature.themepicker
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.view.View
import android.view.ViewGroup
import com.moez.QKSMS.R
import javax.inject.Inject
class ThemePagerAdapter @Inject constructor(private val context: Context) : PagerAdapter() {
override fun instantiateItem(container: ViewGroup, position: Int): Any {
return when (position) {
1 -> container.findViewById(R.id.rgbPicker)
else -> container.findViewById(R.id.materialColors)
}
}
override fun getPageTitle(position: Int): CharSequence? {
return when (position) {
1 -> context.getString(R.string.theme_rgb)
else -> context.getString(R.string.theme_material)
}
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view == `object`
}
override fun getCount(): Int {
return 2
}
}
@@ -0,0 +1,74 @@
/*
* 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 presentation.feature.themepicker
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import common.di.appComponent
import common.util.extensions.pageScrolled
import kotlinx.android.synthetic.main.theme_picker_activity.*
import presentation.common.base.QkThemedActivity
import javax.inject.Inject
class ThemePickerActivity : QkThemedActivity<ThemePickerViewModel>(), ThemePickerView {
override val viewModelClass = ThemePickerViewModel::class
override val themeSelectedIntent by lazy { themeAdapter.colorSelected }
override val pageScrolledIntent by lazy { pager.pageScrolled() }
@Inject lateinit var themeAdapter: ThemeAdapter
@Inject lateinit var themePagerAdapter: ThemePagerAdapter
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.theme_picker_activity)
setTitle(R.string.title_theme)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
pager.offscreenPageLimit = 1
pager.adapter = themePagerAdapter
tabs.pager = pager
themeAdapter.data = colors.materialColors
materialColors.layoutManager = LinearLayoutManager(this)
materialColors.adapter = themeAdapter
colors.background
.autoDisposable(scope())
.subscribe { color -> window.decorView.setBackgroundColor(color) }
}
override fun render(state: ThemePickerState) {
rgbPicker.alpha = state.rgbAlpha
rgbPicker.setBackgroundColor(state.selectedColor)
themeAdapter.threadId = state.threadId
themeAdapter.selectedColor = state.selectedColor
}
}

Some files were not shown because too many files have changed in this diff Show More