Reorganize package structure to adhere to offical Kotlin style guide

This commit is contained in:
Moez Bhatti
2018-01-02 17:13:27 -05:00
parent 8cd5ec31c8
commit a5ce40a404
136 changed files with 429 additions and 431 deletions
@@ -0,0 +1,122 @@
/*
* 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
import android.annotation.TargetApi
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.Settings
import android.provider.Telephony
import common.util.NotificationManager
import presentation.compose.ComposeActivity
import presentation.compose.ComposeViewModel
import presentation.main.MainViewModel
import presentation.settings.SettingsActivity
import presentation.settings.SettingsViewModel
import presentation.setup.SetupActivity
import presentation.setup.SetupViewModel
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class Navigator @Inject constructor(val context: Context) {
private fun startActivity(intent: Intent) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
fun showSetupActivity() {
val intent = Intent(context, SetupActivity::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("body", body)
startActivity(intent)
}
fun showConversation(threadId: Long) {
val intent = Intent(context, ComposeActivity::class.java)
intent.putExtra("threadId", threadId)
startActivity(intent)
}
fun showSettings() {
val intent = Intent(context, SettingsActivity::class.java)
startActivity(intent)
}
fun makePhoneCall(address: String) {
val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$address"))
startActivity(intent)
}
@TargetApi(Build.VERSION_CODES.O)
fun showNotificationSettings() {
val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
intent.putExtra(Settings.EXTRA_CHANNEL_ID, NotificationManager.DEFAULT_CHANNEL_ID)
intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
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()
}
SetupViewModel::class.java -> {
SetupViewModel()
}
ComposeViewModel::class.java -> {
val threadId = intent.getLongExtra("threadId", 0)
val body = intent.getStringExtra("body") ?: ""
ComposeViewModel(threadId, body)
}
SettingsViewModel::class.java -> {
SettingsViewModel()
}
else -> throw IllegalArgumentException("Invalid ViewModel class. If this is a new ViewModel, please add it to Navigator.kt")
} as T
}
}
}
@@ -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.common
import android.content.Context
import android.view.View
import android.view.ViewGroup
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import data.model.MenuItem
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.menu_list_item.view.*
import javax.inject.Inject
class MenuItemAdapter @Inject constructor(private val context: Context): QkAdapter<MenuItem>() {
val menuItemClicks: Subject<Int> = PublishSubject.create()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
return QkViewHolder(View.inflate(context, R.layout.menu_list_item, null))
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val menuItem = getItem(position)
val view = holder.itemView
view.clicks().subscribe { menuItemClicks.onNext(menuItem.actionId) }
view.title.setText(menuItem.title)
}
}
@@ -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,126 @@
/*
* 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 common.util.Colors
import presentation.Navigator
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.Observables
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.toolbar.*
import javax.inject.Inject
import kotlin.reflect.KClass
abstract class QkActivity<VM : QkViewModel<*, *>> : AppCompatActivity() {
@Inject lateinit var colors: Colors
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()
protected var disposables = CompositeDisposable()
@SuppressLint("InlinedApi")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
onNewIntent(intent)
disposables += colors.appThemeResources
.subscribe { res -> setTheme(res) }
disposables += colors.statusBarIcons
.subscribe { systemUiVisibility -> window.decorView.systemUiVisibility = systemUiVisibility }
disposables += colors.statusBar
.subscribe { color -> window.statusBarColor = color }
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
// Update the colours of the menu items
disposables += Observables.combineLatest(menu, colors.theme, { menu, color ->
(0 until menu.size())
.map { position -> menu.getItem(position) }
.forEach { menuItem ->
menuItem?.icon?.run {
setTint(color)
menuItem.icon = this
}
}
}).subscribe()
disposables += colors.textTertiary
.doOnNext { color -> toolbar?.overflowIcon = toolbar?.overflowIcon?.apply { setTint(color) } }
.doOnNext { color -> toolbar?.navigationIcon = toolbar?.navigationIcon?.apply { setTint(color) } }
.subscribe()
disposables += colors.popupThemeResource
.subscribe { res -> toolbar?.popupTheme = res }
disposables += colors.toolbarColor
.subscribe { color -> toolbar?.setBackgroundColor(color) }
}
override fun onDestroy() {
super.onDestroy()
disposables.dispose()
}
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,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.common.base
interface QkView<in State> {
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,54 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.common.base
import android.arch.lifecycle.ViewModel
import android.support.annotation.CallSuper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
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()
protected val intents = CompositeDisposable()
@CallSuper
open fun bindView(view: View) {
intents.clear()
intents += state
.observeOn(AndroidSchedulers.mainThread())
.subscribe { view.render(it) }
}
protected fun newState(reducer: (State) -> State) {
state.value?.let { state.onNext(reducer(it)) }
}
override fun onCleared() {
super.onCleared()
disposables.dispose()
intents.dispose()
}
}
@@ -0,0 +1,106 @@
/*
* 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 common.di.appComponent
import common.util.Colors
import common.util.GlideApp
import common.util.extensions.setTint
import data.model.Contact
import presentation.Navigator
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import kotlinx.android.synthetic.main.avatar_view.view.*
import javax.inject.Inject
class AvatarView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : FrameLayout(context, attrs) {
@Inject lateinit var colors: Colors
@Inject lateinit var navigator: Navigator
private val disposables = CompositeDisposable()
var contact: Contact? = null
set(value) {
field = value
updateView()
}
init {
View.inflate(context, R.layout.avatar_view, this)
appComponent.inject(this)
setBackgroundResource(R.drawable.circle)
clipToOutline = true
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
disposables += colors.theme
.subscribe { color -> background.setTint(color) }
disposables += colors.textPrimaryOnTheme
.subscribe { color -> icon.setTint(color) }
disposables += clicks().subscribe {
contact?.lookupKey?.takeIf { it.isNotEmpty() }?.let { key ->
val uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, key)
ContactsContract.QuickContact.showQuickContact(context, this@AvatarView, uri,
ContactsContract.QuickContact.MODE_MEDIUM, null)
}
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
disposables.clear()
}
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 data.model.Contact
import kotlinx.android.synthetic.main.group_avatar_view.view.*
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,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.common.widget
import android.content.Context
import android.support.v7.widget.LinearLayoutCompat
import android.util.AttributeSet
import android.view.View
import com.moez.QKSMS.R
import common.util.extensions.setVisible
import kotlinx.android.synthetic.main.preference_view.view.*
class PreferenceView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : LinearLayoutCompat(context, attrs) {
var title: String? = null
set(value) {
field = value
titleView.text = value
}
var summary: String? = null
set(value) {
field = value
summaryView.text = value
summaryView.setVisible(value?.isNotEmpty() == true)
}
init {
View.inflate(context, R.layout.preference_view, this)
setBackgroundResource(R.drawable.ripple)
orientation = VERTICAL
context.obtainStyledAttributes(attrs, R.styleable.PreferenceView)?.run {
title = getString(R.styleable.PreferenceView_title)
summary = getString(R.styleable.PreferenceView_summary)
getResourceId(R.styleable.PreferenceView_widget, -1).takeIf { it != -1 }?.run {
View.inflate(context, this, widgetFrame)
}
recycle()
}
}
}
@@ -0,0 +1,81 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.common.widget
import android.content.Context
import android.util.AttributeSet
import android.widget.EditText
import com.moez.QKSMS.R
import common.di.appComponent
import common.util.Colors
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import javax.inject.Inject
open class QkEditText @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : EditText(context, attrs) {
@Inject lateinit var colors: Colors
private val disposables = CompositeDisposable()
private var textColorObservable: Observable<Int>? = null
private var textColorHintObservable: Observable<Int>? = null
init {
appComponent.inject(this)
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?.let { observable ->
disposables += observable.subscribe { color -> setTextColor(color) }
}
textColorHintObservable?.let { observable ->
disposables += observable.subscribe { color -> setHintTextColor(color) }
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
disposables.dispose()
}
}
@@ -0,0 +1,67 @@
/*
* 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 common.di.appComponent
import common.util.Colors
import common.util.extensions.withAlpha
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.Observables
import io.reactivex.rxkotlin.plusAssign
import javax.inject.Inject
class QkSwitch @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : SwitchCompat(context, attrs) {
@Inject lateinit var colors: Colors
private val disposables = CompositeDisposable()
init {
appComponent.inject(this)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
val states = arrayOf(
intArrayOf(-android.R.attr.state_enabled),
intArrayOf(android.R.attr.state_checked),
intArrayOf())
disposables += Observables.combineLatest(colors.theme, colors.switchThumbEnabled, colors.switchThumbDisabled,
{ color, enabled, disabled -> intArrayOf(disabled, color, enabled) })
.map { values -> ColorStateList(states, values) }
.subscribe { tintList -> thumbTintList = tintList }
disposables += Observables.combineLatest(colors.theme, colors.switchTrackEnabled, colors.switchTrackDisabled,
{ color, enabled, disabled -> intArrayOf(disabled, color.withAlpha(0x4D), enabled) })
.map { values -> ColorStateList(states, values) }
.subscribe { tintList -> trackTintList = tintList }
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
disposables.clear()
}
}
@@ -0,0 +1,73 @@
/*
* 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.TextView
import com.moez.QKSMS.R
import common.di.appComponent
import common.util.Colors
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import javax.inject.Inject
open class QkTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : TextView(context, attrs) {
@Inject lateinit var colors: Colors
private val disposables = CompositeDisposable()
private var textColorObservable: Observable<Int>? = null
init {
appComponent.inject(this)
context.obtainStyledAttributes(attrs, R.styleable.QkTextView)?.run {
textColorObservable = when (getInt(R.styleable.QkTextView_textColor, -1)) {
0 -> colors.textPrimary
1 -> colors.textSecondary
2 -> colors.textTertiary
3 -> colors.textPrimaryOnTheme
4 -> colors.textSecondaryOnTheme
5 -> colors.textTertiaryOnTheme
else -> null
}
recycle()
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
textColorObservable?.let { observable ->
disposables += observable.subscribe { color ->
setTextColor(color)
setLinkTextColor(color)
}
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
disposables.dispose()
}
}
@@ -0,0 +1,50 @@
/*
* 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 common.di.appComponent
import common.util.Colors
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import javax.inject.Inject
class Separator @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
@Inject lateinit var colors: Colors
private val disposables = CompositeDisposable()
init {
appComponent.inject(this)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
disposables += colors.separator.subscribe { color -> setBackgroundColor(color) }
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
disposables.dispose()
}
}
@@ -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)
}
}
}
+139
View File
@@ -0,0 +1,139 @@
/*
* 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.compose
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.KeyEvent
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.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 data.model.Contact
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.contact_chip.view.*
import javax.inject.Inject
class ChipsAdapter @Inject constructor(private val context: Context, private val colors: Colors) : QkAdapter<Contact>() {
companion object {
private val TYPE_EDIT_TEXT = 0
private 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()
init {
val wrap = ViewGroup.LayoutParams.WRAP_CONTENT
editText.layoutParams = FlexboxLayoutManager.LayoutParams(wrap, wrap).apply {
minWidth = 56.dpToPx(context)
flexGrow = 8f
}
editText.hint = hint
editText.keys()
.filter { event -> event.action == KeyEvent.ACTION_DOWN }
.filter { event -> event.keyCode == KeyEvent.KEYCODE_DEL }
.subscribe {
if (itemCount > 1 && editText.text.isEmpty()) {
chipDeleted.onNext(getItem(itemCount - 2))
}
}
}
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
view.name.text = contact.name
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,224 @@
/*
* 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.compose
import android.app.AlertDialog
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
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 common.di.appComponent
import common.util.extensions.setBackgroundTint
import common.util.extensions.setTint
import common.util.extensions.setVisible
import common.util.extensions.showKeyboard
import data.model.Contact
import data.model.Message
import presentation.common.base.QkActivity
import io.reactivex.Observable
import io.reactivex.rxkotlin.Observables
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.compose_activity.*
import kotlinx.android.synthetic.main.toolbar_chips.*
import javax.inject.Inject
class ComposeActivity : QkActivity<ComposeViewModel>(), ComposeView {
override val viewModelClass = ComposeViewModel::class
override val queryChangedIntent: Observable<CharSequence> by lazy { chipsAdapter.textChanges }
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 archiveIntent: Subject<Unit> = PublishSubject.create()
override val deleteIntent: 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 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
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
chips.itemAnimator = null
chips.layoutManager = FlexboxLayoutManager(this)
contacts.itemAnimator = null
contacts.layoutManager = LinearLayoutManager(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
messageBackground.backgroundTintMode = PorterDuff.Mode.MULTIPLY
val states = arrayOf(
intArrayOf(android.R.attr.state_enabled),
intArrayOf(-android.R.attr.state_enabled))
disposables += Observables
.combineLatest(colors.textPrimaryOnTheme, colors.textTertiaryOnTheme, { primary, tertiary ->
ColorStateList(states, intArrayOf(primary, tertiary))
})
.subscribe { tintList -> sendIcon.imageTintList = tintList }
disposables += colors.theme
.subscribe { color -> send.setBackgroundTint(color) }
disposables += colors.textSecondary
.subscribe { color -> attach.setTint(color) }
disposables += colors.bubble
.subscribe { color -> messageBackground.setBackgroundTint(color) }
disposables += colors.background
.subscribe { color -> contacts.setBackgroundColor(color) }
disposables += colors.composeBackground
.doOnNext { color -> composeBar.setBackgroundTint(color) }
.doOnNext { color -> window.decorView.setBackgroundColor(color) }
.subscribe()
window.callback = ComposeWindowCallback(window.callback, this)
}
override fun render(state: ComposeState) {
if (state.hasError) {
finish()
return
}
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)?.run {
isVisible = !state.editingMode
}
toolbar.menu.findItem(R.id.archive)?.run {
isVisible = !state.editingMode
setTitle(if (state.archived) R.string.menu_unarchive else R.string.menu_archive)
}
toolbar.menu.findItem(R.id.delete)?.run {
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.updateData(state.messages)
}
if (title != state.title) title = state.title
send.isEnabled = state.canSend
sendIcon.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.archive -> archiveIntent.onNext(Unit)
R.id.delete -> deleteIntent.onNext(Unit)
else -> return super.onOptionsItemSelected(item)
}
return true
}
}
@@ -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.compose
import data.model.Contact
import data.model.Message
import io.realm.RealmResults
data class ComposeState(
val hasError: Boolean = false,
val editingMode: Boolean = false,
val contacts: List<Contact> = ArrayList(),
val contactsVisible: Boolean = false,
val selectedContacts: List<Contact> = ArrayList(),
val title: String = "",
val archived: Boolean = false,
val messages: RealmResults<Message>? = null,
val canSend: Boolean = false
)
@@ -0,0 +1,45 @@
/*
* 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.compose
import data.model.Contact
import data.model.Message
import presentation.common.base.QkView
import io.reactivex.Observable
import io.reactivex.subjects.Subject
interface ComposeView : QkView<ComposeState> {
val queryChangedIntent: Observable<CharSequence>
val chipSelectedIntent: Subject<Contact>
val chipDeletedIntent: Subject<Contact>
val menuReadyIntent: Observable<Unit>
val callIntent: Subject<Unit>
val archiveIntent: Subject<Unit>
val deleteIntent: Subject<Unit>
val copyTextIntent: Subject<Message>
val forwardMessageIntent: Subject<Message>
val deleteMessageIntent: Subject<Message>
val textChangedIntent: Observable<CharSequence>
val attachIntent: Observable<Unit>
val sendIntent: Observable<Unit>
fun setDraft(draft: String)
}
@@ -0,0 +1,240 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.compose
import android.content.Context
import com.moez.QKSMS.R
import common.di.appComponent
import common.util.ClipboardUtils
import common.util.extensions.asObservable
import common.util.extensions.makeToast
import common.util.filter.ContactFilter
import data.model.Contact
import data.model.Conversation
import data.repository.ContactRepository
import data.repository.MessageRepository
import interactor.*
import presentation.Navigator
import presentation.common.base.QkViewModel
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.PublishSubject
import io.reactivex.subjects.Subject
import javax.inject.Inject
class ComposeViewModel(threadId: Long, var draft: String)
: QkViewModel<ComposeView, ComposeState>(ComposeState(editingMode = threadId == 0L)) {
@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 markArchived: MarkArchived
@Inject lateinit var markUnarchived: MarkUnarchived
@Inject lateinit var deleteConversation: DeleteConversation
@Inject lateinit var sendMessage: SendMessage
@Inject lateinit var markRead: MarkRead
@Inject lateinit var deleteMessage: DeleteMessage
private val contacts: List<Contact> by lazy { contactsRepo.getContacts() }
private val contactsReducer: Subject<(List<Contact>) -> List<Contact>> = PublishSubject.create()
private val selectedContacts: Observable<List<Contact>>
private val conversation: Observable<Conversation>
init {
appComponent.inject(this)
selectedContacts = contactsReducer
.scan(listOf<Contact>(), { previousState, reducer -> reducer(previousState) })
.doOnNext { contacts -> newState { it.copy(selectedContacts = contacts) } }
val initialConversation: Observable<Conversation> = when (threadId) {
0L -> Observable.empty()
else -> messageRepo.getConversationAsync(threadId).asObservable()
}
// Map the selected contacts to a conversation so that we can display the message history
val selectedConversation = selectedContacts
.map { contacts -> contacts.map { it.numbers.firstOrNull()?.address ?: "" } }
.flatMapMaybe { addresses -> messageRepo.getOrCreateConversation(addresses) }
// 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 = initialConversation
.filter { conversation -> conversation.isLoaded }
.doOnNext { conversation ->
if (!conversation.isValid) {
newState { it.copy(hasError = true) }
}
}
.mergeWith(selectedConversation)
.filter { conversation -> conversation.isValid }
.filter { conversation -> conversation.id != 0L }
.distinctUntilChanged()
.doOnNext { conversation ->
newState { it.copy(title = conversation.getTitle(), archived = conversation.archived) }
}
disposables += sendMessage
disposables += markRead
disposables += markArchived
disposables += markUnarchived
disposables += deleteConversation
disposables += conversation.subscribe()
// When the conversation changes, update the messages for the adapter
// When the message list changes, make sure to mark them read
disposables += conversation
.distinctUntilChanged()
.observeOn(AndroidSchedulers.mainThread())
.map { conversation -> messageRepo.getMessages(conversation.id) }
.doOnNext { messages -> newState { it.copy(messages = messages) } }
.flatMap { messages -> messages.asObservable() }
.withLatestFrom(conversation, { messages, conversation ->
markRead.execute(conversation.id)
messages
})
.subscribe()
if (threadId == 0L) {
syncContacts.execute(Unit)
}
}
override fun bindView(view: ComposeView) {
super.bindView(view)
if (draft.isNotEmpty()) {
view.setDraft(draft)
draft = ""
}
// 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
intents += Observables
.combineLatest(view.queryChangedIntent, selectedContacts, { query, selectedContacts ->
selectedContacts.isEmpty() || query.isNotEmpty()
})
.skipUntil(state.filter { state -> state.editingMode == true })
.takeUntil(state.filter { state -> state.editingMode == false })
.distinctUntilChanged()
.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
intents += Observables
.combineLatest(view.queryChangedIntent, selectedContacts, { query, selectedContacts ->
contacts
.filterNot { contact -> selectedContacts.contains(contact) }
.filter { contact -> contactFilter.filter(contact, query) }
})
.skipUntil(state.filter { state -> state.editingMode == true })
.takeUntil(state.filter { state -> state.editingMode == false })
.subscribeOn(Schedulers.computation())
.subscribe { contacts -> newState { it.copy(contacts = contacts) } }
// Update the list of selected contacts when a new contact is selected or an existing one is deselected
intents += 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 == true })
.takeUntil(state.filter { state -> state.editingMode == false })
.subscribe()
// When the menu is loaded, trigger a new state so that the menu options can be rendered correctly
intents += view.menuReadyIntent.subscribe {
newState { it.copy() }
}
// Open the phone dialer if the call button is clicked
intents += view.callIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.map { conversation -> conversation.recipients.first() }
.map { recipient -> recipient.address }
.subscribe { address -> navigator.makePhoneCall(address) }
// Toggle the archived state of the conversation
intents += view.archiveIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.subscribe { conversation ->
when (conversation.archived) {
true -> markUnarchived.execute(conversation.id, { context.makeToast(R.string.toast_unarchived) })
false -> markArchived.execute(conversation.id, { context.makeToast(R.string.toast_archived) })
}
}
// Delete the conversation
intents += view.deleteIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.subscribe { conversation -> deleteConversation.execute(conversation.id) }
// Add an attachment
intents += view.attachIntent
.subscribe { context.makeToast(R.string.compose_attach_unsupported) }
// Enable the send button when there is text input into the new message body, disable otherwise
intents += view.textChangedIntent.subscribe { text ->
newState { it.copy(canSend = text.isNotEmpty()) }
}
// Send a message when the send button is clicked, and disable editing mode if it's enabled
intents += view.sendIntent
.withLatestFrom(view.textChangedIntent, { _, body -> body })
.map { body -> body.toString() }
.withLatestFrom(conversation, { body, conversation ->
val threadId = conversation.id
val address = conversation.recipients.first()?.address.orEmpty()
sendMessage.execute(SendMessage.Params(threadId, address, body))
view.setDraft("")
})
.withLatestFrom(state, {_, state ->
if (state.editingMode) {
newState { it.copy(editingMode = false) }
}
})
.subscribe()
// Copy the body of the selected message into the clipboard
intents += view.copyTextIntent.subscribe { message ->
ClipboardUtils.copy(context, message.body)
context.makeToast(R.string.toast_copied)
}
// Forward the message
intents += view.forwardMessageIntent.subscribe { message ->
navigator.showCompose(message.body)
}
// Delete the selected message
intents += view.deleteMessageIntent.subscribe { message ->
deleteMessage.execute(message.id)
}
}
}
@@ -0,0 +1,135 @@
/*
* 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.compose
import android.app.Activity
import android.graphics.Rect
import android.os.Build
import android.support.annotation.RequiresApi
import android.view.*
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,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.compose
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import data.model.Contact
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.contact_list_item.view.*
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.clicks().subscribe { contactSelected.onNext(contact) }
view.avatar.contact = contact
view.name.text = contact.name
view.address.text = contact.numbers.map { it.address }.toString()
}
override fun areItemsTheSame(old: Contact, new: Contact): Boolean {
return old.lookupKey == new.lookupKey
}
}
@@ -0,0 +1,91 @@
/*
* 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.compose
import android.content.Context
import android.view.View
import android.view.animation.AlphaAnimation
import android.widget.RelativeLayout
import com.moez.QKSMS.R
import common.di.appComponent
import common.util.Colors
import common.util.extensions.setBackgroundTint
import data.model.Contact
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import kotlinx.android.synthetic.main.contact_chip_detailed.view.*
import javax.inject.Inject
class DetailedChipView(context: Context) : RelativeLayout(context) {
@Inject lateinit var colors: Colors
private val disposables = CompositeDisposable()
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()
disposables += colors.theme
.subscribe { color -> card.setBackgroundTint(color) }
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
disposables.clear()
}
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,173 @@
/*
* 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.compose
import android.content.Context
import android.support.v7.widget.RecyclerView
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 data.model.Contact
import data.model.Message
import data.model.PhoneNumber
import presentation.common.base.QkViewHolder
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import io.realm.RealmRecyclerViewAdapter
import kotlinx.android.synthetic.main.message_list_item_in.view.*
import timber.log.Timber
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 val VIEWTYPE_ME = -1
private val TIMESTAMP_THRESHOLD = 10
}
val longClicks: Subject<Message> = PublishSubject.create<Message>()
private val people = ArrayList<String>()
private val disposables = CompositeDisposable()
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): QkViewHolder {
val layoutInflater = LayoutInflater.from(context)
val view: View
when (viewType) {
VIEWTYPE_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)
disposables += colors.theme
.subscribe { color -> view.messageBackground.setBackgroundTint(color) }
}
}
if (viewType != VIEWTYPE_ME) {
view.avatar.contact = Contact().apply {
numbers.add(PhoneNumber().apply { address = people[viewType] })
}
}
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 { Timber.v(message.toString()) }
RxView.longClicks(view).subscribe { longClicks.onNext(message) }
bindGrouping(view, position)
val age = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - message.date)
view.status?.text = when {
message.isSending() -> context.getString(R.string.message_status_sending)
message.isDelivered() && age <= TIMESTAMP_THRESHOLD -> context.getString(R.string.message_status_delivered)
message.isFailedMessage() -> context.getString(R.string.message_status_failed)
else -> null
}
view.status?.setVisible(!view.status?.text.isNullOrBlank())
view.body.text = message.body
view.timestamp.text = dateFormatter.getMessageTimestamp(message.date)
}
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
}
}
}
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.isMe() == other.isMe() && diff < TIMESTAMP_THRESHOLD
}
override fun getItemViewType(position: Int): Int {
val message = getItem(position)!!
if (message.isMe()) {
return VIEWTYPE_ME
}
if (!people.contains(message.address)) {
people.add(message.address)
}
return people.indexOf(message.address)
}
}
@@ -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.main
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.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,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.main
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 data.model.Contact
import data.model.InboxItem
import data.model.PhoneNumber
import data.repository.MessageRepository
import presentation.Navigator
import presentation.common.base.FlowableAdapter
import presentation.common.base.QkViewHolder
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 javax.inject.Inject
class ConversationsAdapter @Inject constructor(
val context: Context,
val navigator: Navigator,
val messageRepo: MessageRepository,
val dateFormatter: DateFormatter,
val colors: Colors
) : FlowableAdapter<InboxItem>() {
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).conversation
val message = getItem(position).message
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 = message.body
}
override fun getItemViewType(position: Int): Int {
return if (getItem(position).message.read) 0 else 1
}
override fun areItemsTheSame(old: InboxItem, new: InboxItem): Boolean {
return old.conversation.id == new.conversation.id
}
override fun areContentsTheSame(old: InboxItem, new: InboxItem): Boolean {
return old.message.id == new.message.id &&
old.message.read == new.message.read
}
}
@@ -0,0 +1,267 @@
/*
* 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.main
import android.app.AlertDialog
import android.content.Intent
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 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.rxkotlin.plusAssign
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 kotlinx.android.synthetic.main.toolbar_search.*
import presentation.Navigator
import presentation.common.MenuItemAdapter
import presentation.common.base.QkActivity
import javax.inject.Inject
class MainActivity : QkActivity<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 },
blocked.clicks().map { DrawerItem.BLOCKED },
settings.clicks().map { DrawerItem.SETTINGS }))
}
override val conversationClickIntent by lazy { conversationsAdapter.clicks }
override val conversationLongClickIntent by lazy { conversationsAdapter.longClicks }
override val conversationMenuItemIntent by lazy { menuItemAdapter.menuItemClicks }
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 val conversationMenuDialog by lazy {
val recyclerView = RecyclerView(this)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = menuItemAdapter
recyclerView.setPadding(0, 8.dpToPx(this), 0, 8.dpToPx(this))
AlertDialog.Builder(this).setView(recyclerView).create().apply {
setOnDismissListener { conversationMenuItemIntent.onNext(-1) }
}
}
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
blocked.isEnabled = false
disposables += colors.background
.doOnNext { color -> window.decorView.setBackgroundColor(color) }
.doOnNext { color -> drawer.setBackgroundColor(color) }
.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()
}
}
disposables += colors.theme
.doOnNext { color -> syncingProgress.indeterminateTintList = ColorStateList.valueOf(color) }
.doOnNext { color -> compose.setBackgroundTint(color) }
.subscribe()
disposables += colors.textSecondary
.subscribe { color -> toggle.drawerArrowDrawable.color = color }
disposables += 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 -> blockedIcon.imageTintList = tintList }
.doOnNext { tintList -> settingsIcon.imageTintList = tintList }
.subscribe()
disposables += colors.separator
.doOnNext { color -> inbox.background = rowBackground(color) }
.doOnNext { color -> archived.background = rowBackground(color) }
.doOnNext { color -> scheduled.background = rowBackground(color) }
.doOnNext { color -> blocked.background = rowBackground(color) }
.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 onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
intent?.getLongExtra("threadId", 0)
?.takeIf { threadId -> threadId > 0 }
?.let { threadId -> navigator.showConversation(threadId) }
}
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
if (conversationsAdapter.flowable != state.page.data) conversationsAdapter.flowable = state.page.data
itemTouchHelper.attachToRecyclerView(recyclerView)
menuItemAdapter.data = state.page.menu
}
is Archived -> {
if (!archived.isSelected) toolbarSearch.setText(R.string.title_archived)
if (recyclerView.adapter != conversationsAdapter) recyclerView.adapter = conversationsAdapter
if (conversationsAdapter.flowable != state.page.data) conversationsAdapter.flowable = state.page.data
itemTouchHelper.attachToRecyclerView(null)
menuItemAdapter.data = state.page.menu
}
is Scheduled -> {
if (!scheduled.isSelected) toolbarSearch.setText(R.string.title_scheduled)
recyclerView.adapter = null
itemTouchHelper.attachToRecyclerView(null)
menuItemAdapter.data = ArrayList()
}
is Blocked -> {
if (!blocked.isSelected) toolbarSearch.setText(R.string.title_blocked)
recyclerView.adapter = null
itemTouchHelper.attachToRecyclerView(null)
menuItemAdapter.data = ArrayList()
}
}
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
blocked.isSelected = state.page is Blocked
blockedIcon.isSelected = state.page is Blocked
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 && menuItemAdapter.data.isEmpty()) conversationMenuDialog.dismiss()
else if (!conversationMenuDialog.isShowing && menuItemAdapter.data.isNotEmpty()) conversationMenuDialog.show()
}
override fun clearSearch() {
toolbarSearch.text = null
}
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,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.main
import data.model.InboxItem
import data.model.MenuItem
import io.reactivex.Flowable
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<InboxItem>>? = null,
val menu: List<MenuItem> = ArrayList(),
val showArchivedSnackbar: Boolean = false) : MainPage()
data class Archived(
val data: Flowable<List<InboxItem>>?,
val menu: List<MenuItem> = ArrayList()) : MainPage()
data class Scheduled(
val data: Any? = null) : MainPage()
data class Blocked(
val data: Any? = null) : MainPage()
@@ -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.main
import presentation.common.base.QkView
import io.reactivex.Observable
import io.reactivex.subjects.Subject
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: Subject<Int>
val swipeConversationIntent: Observable<Int>
val undoSwipeConversationIntent: Subject<Unit>
fun clearSearch()
}
enum class DrawerItem { INBOX, ARCHIVED, SCHEDULED, BLOCKED, SETTINGS }
@@ -0,0 +1,212 @@
/*
* 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.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 common.di.appComponent
import common.util.filter.ConversationFilter
import data.model.MenuItem
import data.model.SyncLog
import data.repository.MessageRepository
import interactor.*
import presentation.Navigator
import presentation.common.base.QkViewModel
import io.reactivex.Observable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.withLatestFrom
import io.realm.Realm
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 partialSync: PartialSync
private val conversations by lazy { messageRepo.getConversations() }
private val menuArchive = MenuItem(R.string.menu_archive, 0)
private val menuUnarchive = MenuItem(R.string.menu_unarchive, 1)
private val menuDelete = MenuItem(R.string.menu_delete, 2)
init {
appComponent.inject(this)
disposables += markAllSeen
disposables += markArchived
disposables += markUnarchived
disposables += deleteConversation
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 = messageRepo.getConversations())) }
val isDefaultSms = 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 (isDefaultSms) {
partialSync.execute(Unit)
}
if (isDefaultSms || !hasSmsPermission || !hasContactPermission) {
navigator.showSetupActivity()
}
markAllSeen.execute(Unit)
}
override fun bindView(view: MainView) {
super.bindView(view)
intents += 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.conversation, query) } }
}
val page = state.page.copy(showClearButton = query.isNotEmpty(), data = conversations)
newState { it.copy(page = page) }
}
})
.subscribe()
intents += view.queryCancelledIntent
.subscribe { view.clearSearch() }
intents += view.composeIntent
.subscribe { navigator.showCompose() }
intents += view.drawerOpenIntent
.subscribe { open -> newState { it.copy(drawerOpen = open) } }
intents += view.drawerItemIntent
.doOnNext { newState { it.copy(drawerOpen = false) } }
.doOnNext { if (it == DrawerItem.SETTINGS) navigator.showSettings() }
.distinctUntilChanged()
.doOnNext {
when (it) {
DrawerItem.INBOX -> newState { it.copy(page = Inbox(data = conversations)) }
DrawerItem.ARCHIVED -> newState { it.copy(page = Archived(messageRepo.getConversations(true))) }
DrawerItem.SCHEDULED -> newState { it.copy(page = Scheduled()) }
DrawerItem.BLOCKED -> newState { it.copy(page = Blocked()) }
}
}
.subscribe()
intents += view.conversationClickIntent
.doOnNext { view.clearSearch() }
.doOnNext { threadId -> navigator.showConversation(threadId) }
.subscribe()
intents += view.conversationLongClickIntent
.withLatestFrom(state, { l, 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) }
}
}
})
.subscribe()
intents += 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 -> deleteConversation.execute(threadId)
}
})
.subscribe()
val swipedConversation = view.swipeConversationIntent
.withLatestFrom(conversations.toObservable(), { position, conversations -> conversations[position] })
.map { pair -> pair.conversation }
.map { conversation -> conversation.id }
intents += 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) }
}
}
})
.flatMap { 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) }
}
}
})
.subscribe()
intents += view.undoSwipeConversationIntent
.withLatestFrom(swipedConversation, { _, threadId -> threadId })
.subscribe { threadId -> markUnarchived.execute(threadId) }
}
}
@@ -0,0 +1,159 @@
/*
* 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.settings
import android.app.AlertDialog
import android.app.ProgressDialog
import android.os.Build
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import com.google.android.flexbox.FlexboxLayoutManager
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import common.di.appComponent
import common.util.extensions.dpToPx
import common.util.extensions.setVisible
import presentation.common.base.QkActivity
import presentation.common.widget.PreferenceView
import io.reactivex.Observable
import io.reactivex.rxkotlin.plusAssign
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.*
class SettingsActivity : QkActivity<SettingsViewModel>(), SettingsView {
override val viewModelClass = SettingsViewModel::class
override val preferenceClickIntent: Subject<PreferenceView> = PublishSubject.create()
override val themeSelectedIntent: Observable<Int> by lazy { themeAdapter.colorSelected }
// TODO remove this
private val progressDialog by lazy {
ProgressDialog(this).apply {
isIndeterminate = true
setCancelable(false)
setCanceledOnTouchOutside(false)
}
}
private val themeDialog by lazy {
AlertDialog.Builder(this)
.setTitle(R.string.settings_dialog_theme_title)
.setView(themeRecyclerView)
.setCancelable(false)
.create()
}
private val themeRecyclerView by lazy {
RecyclerView(this).apply {
val padding = 8.dpToPx(context)
setPadding(padding, padding, padding, padding)
adapter = themeAdapter
clipToPadding = false
clipChildren = false
layoutManager = FlexboxLayoutManager(this@SettingsActivity)
}
}
private val themeAdapter by lazy {
ThemeAdapter(this@SettingsActivity).apply {
data = listOf(
-0x21f24, -0x64245, -0x96678, -0xc93a0, -0x17b1c0, -0x1ae3dd, -0x22e6e3, -0x2fe8ea, -0x3bebef, -0x4fedf6,
-0x31b14, -0x74430, -0xb704f, -0xf9d6e, -0x13bf86, -0x16e19d, -0x27e4a0, -0x3de7a5, -0x52eba9, -0x77f1b1,
-0xc1a0b, -0x1e4119, -0x316c28, -0x459738, -0x54b844, -0x63d850, -0x71db56, -0x84e05e, -0x95e466, -0xb5eb74,
-0x12180a, -0x2e3b17, -0x4c6225, -0x6a8a33, -0x81a83e, -0x98c549, -0xa1ca4f, -0xaed258, -0xbad860, -0xcee46e,
-0x17150a, -0x3a3517, -0x605726, -0x867935, -0xa39440, -0xc0ae4b, -0xc6b655, -0xcfc061, -0xd7ca6d, -0xe5dc82,
-0x181603, -0x2f2601, -0x504001, -0x6e5801, -0x8c7002, -0xa98804, -0xb19311, -0xbaa122, -0xc4af32, -0xd5c94f,
-0x1e0a02, -0x4c1a04, -0x7e2b06, -0xb03c09, -0xd6490a, -0xfc560c, -0xfc641b, -0xfd772f, -0xfd8843, -0xfea865,
-0x1f0806, -0x4d140e, -0x7f2116, -0xb22f1f, -0xd93926, -0xff432c, -0xff533f, -0xff6859, -0xff7c71, -0xff9f9c,
-0x1f0d0f, -0x4d2025, -0x7f343c, -0xb24954, -0xd95966, -0xff6978, -0xff7685, -0xff8695, -0xff96a4, -0xffb2c0,
-0x2f0732, -0x5c165c, -0x8d2a8e, -0xbd42bf, -0xd450d5, -0xda64dc, -0xf570f8, -0xf581f9, -0xfa9100, -0xf2acfe,
-0xe0717, -0x231238, -0x3a1e5b, -0x512a7f, -0x63339b, -0x743cb6, -0x834cbe, -0x9760c8, -0xaa74d1, -0xcc96e2,
-0x60419, -0xf0b3d, -0x191164, -0x23188b, -0x2b1ea9, -0x3223c7, -0x3f35cd, -0x504bd5, -0x6162dc, -0x7d88e9,
-0x219, -0x63c, -0xa63, -0xe8a, -0x11a8, -0x14c5, -0x227cb, -0x43fd3, -0x657db, -0xa80e9,
-0x71f, -0x134d, -0x1f7e, -0x2ab1, -0x35d8, -0x3ef9, -0x4d00, -0x6000, -0x7100, -0x9100,
-0xc20, -0x1f4e, -0x3380, -0x48b3, -0x58da, -0x6800, -0x47400, -0xa8400, -0x109400, -0x19af00,
-0x41619, -0x3344, -0x546f, -0x759b, -0x8fbd, -0xa8de, -0xbaee2, -0x19b5e7, -0x27bceb, -0x40c9f4,
-0x101417, -0x283338, -0x43555c, -0x5e7781, -0x72919d, -0x86aab8, -0x92b3bf, -0xa2bfc9, -0xb1cbd2,
-0x50506, -0xa0a0b, -0x111112, -0x1f1f20, -0x424243, -0x616162, -0x8a8a8b, -0x9e9e9f, -0xbdbdbe, -0xdededf, -0x1000000, -0x1,
-0x13100f, -0x13100f, -0x4f413b, -0x6f5b52, -0x876f64, -0x9f8275, -0xab9186, -0xbaa59c, -0xc8b8b1, -0xd9cdc8)
}
}
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)
val supportsNotificationChannels = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
notificationsO.setVisible(supportsNotificationChannels)
notifications.setVisible(!supportsNotificationChannels)
vibration.setVisible(!supportsNotificationChannels)
ringtone.setVisible(!supportsNotificationChannels)
disposables += colors.background
.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 (themeDialog.isShowing && !state.selectingTheme) themeDialog.dismiss()
else if (!themeDialog.isShowing && state.selectingTheme) themeDialog.show()
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
})
dark.checkbox.isChecked = state.darkModeEnabled
autoEmoji.checkbox.isChecked = state.autoEmojiEnabled
notifications.checkbox.isChecked = state.notificationsEnabled
vibration.checkbox.isChecked = state.vibrationEnabled
delivery.checkbox.isChecked = state.deliveryEnabled
split.checkbox.isChecked = state.splitSmsEnabled
unicode.checkbox.isChecked = state.stripUnicodeEnabled
mms.checkbox.isChecked = state.mmsEnabled
mmsSize.summary = state.maxMmsSize
}
}
@@ -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.settings
data class SettingsState(
val selectingTheme: Boolean = false,
val syncing: Boolean = false,
val isDefaultSmsApp: Boolean = false,
val darkModeEnabled: Boolean = false,
val autoEmojiEnabled: Boolean = true,
val notificationsEnabled: Boolean = true,
val vibrationEnabled: Boolean = true,
val deliveryEnabled: Boolean = false,
val splitSmsEnabled: Boolean = false,
val stripUnicodeEnabled: Boolean = false,
val mmsEnabled: Boolean = true,
val maxMmsSize: 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.settings
import presentation.common.base.QkView
import presentation.common.widget.PreferenceView
import io.reactivex.Observable
import io.reactivex.subjects.Subject
interface SettingsView : QkView<SettingsState> {
val preferenceClickIntent: Subject<PreferenceView>
val themeSelectedIntent: Observable<Int>
}
@@ -0,0 +1,139 @@
/*
* 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.settings
import android.content.Context
import com.moez.QKSMS.R
import common.di.appComponent
import common.util.Preferences
import interactor.FullSync
import presentation.Navigator
import presentation.common.base.QkViewModel
import io.reactivex.rxkotlin.plusAssign
import timber.log.Timber
import javax.inject.Inject
class SettingsViewModel : QkViewModel<SettingsView, SettingsState>(SettingsState()) {
@Inject lateinit var context: Context
@Inject lateinit var navigator: Navigator
@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) }
}
disposables += prefs.dark.asObservable().subscribe { darkModeEnabled ->
newState { it.copy(darkModeEnabled = darkModeEnabled) }
}
disposables += prefs.autoEmoji.asObservable().subscribe { autoEmojiEnabled ->
newState { it.copy(autoEmojiEnabled = autoEmojiEnabled) }
}
disposables += prefs.notifications.asObservable().subscribe { notificationsEnabled ->
newState { it.copy(notificationsEnabled = notificationsEnabled) }
}
disposables += prefs.vibration.asObservable().subscribe { vibrationEnabled ->
newState { it.copy(vibrationEnabled = vibrationEnabled) }
}
disposables += prefs.ringtone.asObservable().subscribe { ringtone ->
}
disposables += prefs.delivery.asObservable().subscribe { deliveryEnabled ->
newState { it.copy(deliveryEnabled = deliveryEnabled) }
}
disposables += prefs.split.asObservable().subscribe { splitSmsEnabled ->
newState { it.copy(splitSmsEnabled = splitSmsEnabled) }
}
disposables += prefs.unicode.asObservable().subscribe { stripUnicodeEnabled ->
newState { it.copy(stripUnicodeEnabled = stripUnicodeEnabled) }
}
disposables += prefs.mms.asObservable().subscribe { mmsEnabled ->
newState { it.copy(mmsEnabled = mmsEnabled) }
}
disposables += prefs.mmsSize.asObservable().subscribe { maxMmsSize ->
newState { it.copy(maxMmsSize = maxMmsSize.toString()) }
}
disposables += fullSync
}
override fun bindView(view: SettingsView) {
super.bindView(view)
intents += view.preferenceClickIntent.subscribe {
Timber.v("Preference click: ${context.resources.getResourceName(it.id)}")
when (it.id) {
R.id.defaultSms -> navigator.showDefaultSmsDialog()
R.id.theme -> newState { it.copy(selectingTheme = true) }
R.id.dark -> prefs.dark.set(!prefs.dark.get())
R.id.autoEmoji -> prefs.autoEmoji.set(!prefs.autoEmoji.get())
R.id.notificationsO -> navigator.showNotificationSettings()
R.id.notifications -> prefs.notifications.set(!prefs.notifications.get())
R.id.vibration -> prefs.vibration.set(!prefs.vibration.get())
R.id.ringtone -> {
}
R.id.delivery -> prefs.delivery.set(!prefs.delivery.get())
R.id.split -> prefs.split.set(!prefs.split.get())
R.id.unicode -> prefs.unicode.set(!prefs.unicode.get())
R.id.mms -> prefs.mms.set(!prefs.mms.get())
R.id.mmsSize -> {
}
R.id.sync -> {
newState { it.copy(syncing = true) }
fullSync.execute(Unit, {
newState { it.copy(syncing = false) }
})
}
}
}
intents += view.themeSelectedIntent.subscribe { color ->
prefs.theme.set(color)
newState { it.copy(selectingTheme = false) }
}
}
}
@@ -0,0 +1,50 @@
/*
* 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.settings
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.moez.QKSMS.R
import common.util.extensions.setBackgroundTint
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.theme_list_item.view.*
class ThemeAdapter(private val context: Context) : QkAdapter<Int>() {
val colorSelected: Subject<Int> = PublishSubject.create()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.theme_list_item, parent, false)
return QkViewHolder(view)
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val theme = getItem(position)
val view = holder.itemView
view.setOnClickListener { colorSelected.onNext(theme) }
view.theme.setBackgroundTint(theme)
}
}
@@ -0,0 +1,73 @@
/*
* 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.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 common.di.appComponent
import presentation.Navigator
import presentation.common.base.QkActivity
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.setup_activity.*
import javax.inject.Inject
class SetupActivity : QkActivity<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)
disposables += colors.background
.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.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.setup
import presentation.common.base.QkView
import io.reactivex.Observable
interface SetupView : QkView<SetupState> {
val activityResumedIntent: Observable<*>
val skipIntent: Observable<*>
val nextIntent: Observable<*>
fun requestDefaultSms()
fun requestPermissions()
fun finish()
}
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.setup
import android.content.Context
import android.provider.Telephony
import common.di.appComponent
import common.util.Permissions
import presentation.common.base.QkViewModel
import io.reactivex.rxkotlin.plusAssign
import javax.inject.Inject
class SetupViewModel : QkViewModel<SetupView, SetupState>(SetupState()) {
@Inject lateinit var context: Context
@Inject lateinit var permissions: Permissions
init {
appComponent.inject(this)
}
override fun bindView(view: SetupView) {
super.bindView(view)
intents += view.activityResumedIntent
.subscribe {
val isDefault = Telephony.Sms.getDefaultSmsPackage(context) == context.packageName
if (!permissions.hasSmsAndContacts()) view.requestPermissions()
else if (isDefault) view.finish()
}
intents += view.skipIntent.subscribe { view.finish() }
intents += view.nextIntent.subscribe { view.requestDefaultSms() }
}
}