Flatten hierarchy in presentation module

This commit is contained in:
Moez Bhatti
2018-03-22 01:43:09 -04:00
parent 2e4d96059a
commit 7212983ffe
95 changed files with 51 additions and 65 deletions
@@ -0,0 +1,74 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.blocked
import android.app.AlertDialog
import android.os.Bundle
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import common.util.extensions.setVisible
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.blocked_activity.*
import presentation.common.base.QkThemedActivity
import javax.inject.Inject
class BlockedActivity : QkThemedActivity<BlockedViewModel>(), BlockedView {
@Inject lateinit var blockedAdapter: BlockedAdapter
override val viewModelClass = BlockedViewModel::class
override val unblockIntent by lazy { blockedAdapter.unblock }
override val confirmUnblockIntent: Subject<Unit> = PublishSubject.create()
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.blocked_activity)
setTitle(R.string.blocked_title)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
colors.background
.autoDisposable(scope())
.subscribe { color -> window.decorView.setBackgroundColor(color) }
conversations.adapter = blockedAdapter
}
override fun render(state: BlockedState) {
blockedAdapter.flowable = state.data
empty.setVisible(state.empty)
}
override fun showUnblockDialog() {
AlertDialog.Builder(this)
.setTitle(R.string.blocked_unblock_dialog_title)
.setMessage(R.string.blocked_unblock_dialog_message)
.setPositiveButton(R.string.button_unblock, { _, _ -> confirmUnblockIntent.onNext(Unit) })
.setNegativeButton(R.string.button_cancel, null)
.show()
}
}
@@ -0,0 +1,55 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.blocked
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.moez.QKSMS.R
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.blocked_list_item.view.*
import model.Contact
import model.Conversation
import model.PhoneNumber
import presentation.common.base.FlowableAdapter
import presentation.common.base.QkViewHolder
import javax.inject.Inject
class BlockedAdapter @Inject constructor(private val context: Context) : FlowableAdapter<Conversation>() {
val unblock: PublishSubject<Long> = PublishSubject.create()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
return QkViewHolder(LayoutInflater.from(context).inflate(R.layout.blocked_list_item, parent, false))
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val conversation = getItem(position)
val view = holder.itemView
view.setOnClickListener { unblock.onNext(conversation.id) }
view.avatars.contacts = conversation.recipients.map { recipient ->
recipient.contact ?: Contact().apply { numbers.add(PhoneNumber().apply { address = recipient.address }) }
}
view.title.text = conversation.getTitle()
}
}
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.blocked
import io.reactivex.Flowable
import model.Conversation
data class BlockedState(
val data: Flowable<List<Conversation>>? = null,
val empty: Boolean = false
)
@@ -0,0 +1,31 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.blocked
import io.reactivex.Observable
import presentation.common.base.QkView
interface BlockedView : QkView<BlockedState> {
val unblockIntent: Observable<Long>
val confirmUnblockIntent: Observable<Unit>
fun showUnblockDialog()
}
@@ -0,0 +1,59 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.blocked
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import interactor.MarkUnblocked
import io.reactivex.rxkotlin.withLatestFrom
import presentation.common.base.QkViewModel
import repository.MessageRepository
import javax.inject.Inject
class BlockedViewModel : QkViewModel<BlockedView, BlockedState>(BlockedState()) {
@Inject lateinit var markUnblocked: MarkUnblocked
@Inject lateinit var messageRepo: MessageRepository
init {
appComponent.inject(this)
val conversations = messageRepo.getBlockedConversations()
.doOnNext { conversations -> newState { it.copy(empty = conversations.isEmpty()) } }
newState { it.copy(data = conversations) }
}
override fun bindView(view: BlockedView) {
super.bindView(view)
// Show confirm unblock conversation dialog
view.unblockIntent
.autoDisposable(view.scope())
.subscribe { view.showUnblockDialog() }
// Unblock conversation
view.confirmUnblockIntent
.withLatestFrom(view.unblockIntent, { _, threadId -> threadId })
.autoDisposable(view.scope())
.subscribe { threadId -> markUnblocked.execute(threadId) }
}
}
@@ -0,0 +1,80 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.content.Context
import android.net.Uri
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import common.util.Colors
import common.util.extensions.setBackgroundTint
import common.util.extensions.setTint
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.attachment_list_item.view.*
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import javax.inject.Inject
class AttachmentAdapter @Inject constructor(
private val context: Context,
private val colors: Colors
) : QkAdapter<Uri>() {
val attachmentDeleted: Subject<Uri> = PublishSubject.create()
private val disposables = CompositeDisposable()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.attachment_list_item, parent, false)
view.thumbnailBounds.clipToOutline = true
disposables += colors.bubble
.subscribe { color -> view.detach.setBackgroundTint(color) }
disposables += colors.textSecondary
.subscribe { color -> view.detach.setTint(color) }
return QkViewHolder(view)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
disposables.clear()
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val uri = getItem(position)
val view = holder.itemView
view.clicks().subscribe {
attachmentDeleted.onNext(uri)
}
Glide.with(context).load(uri).into(view.thumbnail)
}
}
+140
View File
@@ -0,0 +1,140 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.RelativeLayout
import com.google.android.flexbox.FlexboxLayoutManager
import com.jakewharton.rxbinding2.view.keys
import com.jakewharton.rxbinding2.widget.editorActions
import com.jakewharton.rxbinding2.widget.textChanges
import com.moez.QKSMS.R
import common.util.Colors
import common.util.extensions.dpToPx
import common.util.extensions.setBackgroundTint
import common.util.extensions.showKeyboard
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.contact_chip.view.*
import model.Contact
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import javax.inject.Inject
class ChipsAdapter @Inject constructor(private val context: Context, private val colors: Colors) : QkAdapter<Contact>() {
companion object {
private const val TYPE_EDIT_TEXT = 0
private const val TYPE_ITEM = 1
}
private val hint: String = context.getString(R.string.title_compose)
private val editText = View.inflate(context, R.layout.chip_input_list_item, null) as EditText
var view: RecyclerView? = null
val chipDeleted: PublishSubject<Contact> = PublishSubject.create<Contact>()
val textChanges = editText.textChanges()
val keyEvents = editText.keys()
val actions = editText.editorActions()
init {
val wrap = ViewGroup.LayoutParams.WRAP_CONTENT
editText.layoutParams = FlexboxLayoutManager.LayoutParams(wrap, wrap).apply {
minWidth = 56.dpToPx(context)
flexGrow = 8f
}
editText.hint = hint
}
override fun onDatasetChanged() {
editText.text = null
editText.hint = if (itemCount == 1) hint else null
if (itemCount != 2) {
editText.showKeyboard()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = when (viewType) {
TYPE_EDIT_TEXT -> QkViewHolder(editText)
else -> {
val view = LayoutInflater.from(context).inflate(R.layout.contact_chip, parent, false)
colors.composeBackground.subscribe { color -> view.content.setBackgroundTint(color) }
QkViewHolder(view)
}
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
when (getItemViewType(position)) {
TYPE_ITEM -> {
val contact = getItem(position)
val view = holder.itemView
view.avatar.contact = contact
// If the contact's name is empty, try to display a phone number instead
// The contacts provided here should only have one number
view.name.text = if (contact.name.isNotBlank()) {
contact.name
} else {
contact.numbers.firstOrNull { it.address.isNotBlank() }?.address ?: ""
}
view.setOnClickListener { showDetailedChip(contact) }
}
}
}
override fun getItemCount() = super.getItemCount() + 1
override fun getItemViewType(position: Int) = if (position == itemCount - 1) TYPE_EDIT_TEXT else TYPE_ITEM
private fun showDetailedChip(contact: Contact) {
val detailedChipView = DetailedChipView(context)
detailedChipView.setContact(contact)
val rootView = view?.rootView as ViewGroup
val layoutParams = RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
layoutParams.topMargin = 24.dpToPx(context)
layoutParams.marginStart = 56.dpToPx(context)
rootView.addView(detailedChipView, layoutParams)
detailedChipView.show()
detailedChipView.setOnDeleteListener {
chipDeleted.onNext(contact)
detailedChipView.hide()
}
}
override fun areItemsTheSame(old: Contact, new: Contact): Boolean {
return old.lookupKey == new.lookupKey
}
}
@@ -0,0 +1,252 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.app.AlertDialog
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.net.Uri
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import com.google.android.flexbox.FlexboxLayoutManager
import com.jakewharton.rxbinding2.view.clicks
import com.jakewharton.rxbinding2.widget.textChanges
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import common.util.extensions.setBackgroundTint
import common.util.extensions.setTint
import common.util.extensions.setVisible
import common.util.extensions.showKeyboard
import io.reactivex.Observable
import io.reactivex.rxkotlin.Observables
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.compose_activity.*
import model.Contact
import model.Message
import presentation.common.base.QkThemedActivity
import javax.inject.Inject
class ComposeActivity : QkThemedActivity<ComposeViewModel>(), ComposeView {
override val viewModelClass = ComposeViewModel::class
override val activityVisibleIntent: Subject<Boolean> = PublishSubject.create()
override val queryChangedIntent: Observable<CharSequence> by lazy { chipsAdapter.textChanges }
override val queryKeyEventIntent: Observable<KeyEvent> by lazy { chipsAdapter.keyEvents }
override val queryEditorActionIntent: Observable<Int> by lazy { chipsAdapter.actions }
override val chipSelectedIntent: Subject<Contact> by lazy { contactsAdapter.contactSelected }
override val chipDeletedIntent: Subject<Contact> by lazy { chipsAdapter.chipDeleted }
override val menuReadyIntent: Observable<Unit> = menu.map { Unit }
override val callIntent: Subject<Unit> = PublishSubject.create()
override val infoIntent: Subject<Unit> = PublishSubject.create()
override val copyTextIntent: Subject<Message> = PublishSubject.create()
override val forwardMessageIntent: Subject<Message> = PublishSubject.create()
override val deleteMessageIntent: Subject<Message> = PublishSubject.create()
override val messageClickIntent: Subject<Message> by lazy { messageAdapter.clicks }
override val attachmentDeletedIntent: Subject<Uri> by lazy { attachmentAdapter.attachmentDeleted }
override val textChangedIntent by lazy { message.textChanges() }
override val attachIntent by lazy { attach.clicks() }
override val sendIntent by lazy { send.clicks() }
@Inject lateinit var chipsAdapter: ChipsAdapter
@Inject lateinit var contactsAdapter: ContactAdapter
@Inject lateinit var messageAdapter: MessagesAdapter
@Inject lateinit var attachmentAdapter: AttachmentAdapter
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.compose_activity)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
chipsAdapter.view = chips
contacts.itemAnimator = null
chips.itemAnimator = null
chips.layoutManager = FlexboxLayoutManager(this)
val layoutManager = LinearLayoutManager(this).apply { stackFromEnd = true }
messageAdapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
if (positionStart > 0) {
messageAdapter.notifyItemChanged(positionStart - 1)
}
// If we're at the bottom, scroll down to show new messages
val lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition()
if (positionStart >= messageAdapter.itemCount - 1 && lastVisiblePosition == positionStart - 1) {
messageList.scrollToPosition(positionStart)
}
}
})
messageAdapter.longClicks.subscribe { message ->
AlertDialog.Builder(this)
.setItems(R.array.message_options, { _, row ->
when (row) {
0 -> copyTextIntent.onNext(message)
1 -> forwardMessageIntent.onNext(message)
2 -> deleteMessageIntent.onNext(message)
}
})
.show()
}
messageList.setHasFixedSize(true)
messageList.layoutManager = layoutManager
messageList.adapter = messageAdapter
attachments.adapter = attachmentAdapter
messageBackground.backgroundTintMode = PorterDuff.Mode.MULTIPLY
val states = arrayOf(
intArrayOf(android.R.attr.state_enabled),
intArrayOf(-android.R.attr.state_enabled))
val iconEnabled = threadId
.distinctUntilChanged()
.switchMap { threadId -> colors.textPrimaryOnThemeForConversation(threadId) }
val iconDisabled = threadId
.distinctUntilChanged()
.switchMap { threadId -> colors.textTertiaryOnThemeForConversation(threadId) }
Observables
.combineLatest(iconEnabled, iconDisabled, { primary, tertiary ->
ColorStateList(states, intArrayOf(primary, tertiary))
})
.autoDisposable(scope())
.subscribe { tintList -> send.imageTintList = tintList }
theme
.autoDisposable(scope())
.subscribe { color -> send.setBackgroundTint(color) }
colors.textSecondary
.autoDisposable(scope())
.subscribe { color -> attach.setTint(color) }
colors.bubble
.autoDisposable(scope())
.subscribe { color -> messageBackground.setBackgroundTint(color) }
colors.background
.autoDisposable(scope())
.subscribe { color -> contacts.setBackgroundColor(color) }
colors.composeBackground
.doOnNext { color -> composeBackground.setBackgroundTint(color) }
.doOnNext { color -> window.decorView.setBackgroundColor(color) }
.autoDisposable(scope())
.subscribe()
window.callback = ComposeWindowCallback(window.callback, this)
}
override fun onStart() {
super.onStart()
activityVisibleIntent.onNext(true)
}
override fun onPause() {
super.onPause()
activityVisibleIntent.onNext(false)
}
override fun render(state: ComposeState) {
if (state.hasError) {
finish()
return
}
threadId.onNext(state.selectedConversation)
toolbarTitle.setVisible(!state.editingMode)
chips.setVisible(state.editingMode)
contacts.setVisible(state.contactsVisible)
composeBar.setVisible(!state.contactsVisible)
// Don't set the adapters unless needed
if (state.editingMode && chips.adapter == null) chips.adapter = chipsAdapter
if (state.editingMode && contacts.adapter == null) contacts.adapter = contactsAdapter
toolbar.menu.findItem(R.id.call)?.isVisible = !state.editingMode
toolbar.menu.findItem(R.id.info)?.isVisible = !state.editingMode
if (chipsAdapter.data.isEmpty() && state.selectedContacts.isNotEmpty()) {
message.showKeyboard()
}
if (chipsAdapter.data !== state.selectedContacts) {
chipsAdapter.data = state.selectedContacts
}
if (contactsAdapter.data !== state.contacts) {
contactsAdapter.data = state.contacts
}
if (messageAdapter.data !== state.messages) {
messageAdapter.data = state.messages
}
attachments.setVisible(state.attachments.isNotEmpty())
if (attachmentAdapter.data !== state.attachments) {
attachmentAdapter.data = state.attachments
}
if (title != state.title) title = state.title
counter.text = state.remaining
counter.setVisible(counter.text.isNotBlank())
send.isEnabled = state.canSend
}
override fun setDraft(draft: String) {
message.setText(draft)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.compose, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.call -> callIntent.onNext(Unit)
R.id.info -> infoIntent.onNext(Unit)
else -> return super.onOptionsItemSelected(item)
}
return true
}
}
@@ -0,0 +1,40 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.net.Uri
import io.realm.RealmResults
import model.Contact
import model.Conversation
import model.Message
data class ComposeState(
val hasError: Boolean = false,
val editingMode: Boolean = false,
val contacts: List<Contact> = ArrayList(),
val contactsVisible: Boolean = false,
val selectedConversation: Long = 0,
val selectedContacts: List<Contact> = ArrayList(),
val title: String = "",
val archived: Boolean = false,
val messages: Pair<Conversation, RealmResults<Message>>? = null,
val attachments: List<Uri> = ArrayList(),
val remaining: String = "",
val canSend: Boolean = false
)
@@ -0,0 +1,51 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.net.Uri
import android.view.KeyEvent
import io.reactivex.Observable
import io.reactivex.subjects.Subject
import model.Contact
import model.Message
import presentation.common.base.QkView
interface ComposeView : QkView<ComposeState> {
val activityVisibleIntent: Observable<Boolean>
val queryChangedIntent: Observable<CharSequence>
val queryKeyEventIntent: Observable<KeyEvent>
val queryEditorActionIntent: Observable<Int>
val chipSelectedIntent: Subject<Contact>
val chipDeletedIntent: Subject<Contact>
val menuReadyIntent: Observable<Unit>
val callIntent: Subject<Unit>
val infoIntent: Subject<Unit>
val copyTextIntent: Subject<Message>
val forwardMessageIntent: Subject<Message>
val deleteMessageIntent: Subject<Message>
val messageClickIntent: Subject<Message>
val attachmentDeletedIntent: Subject<Uri>
val textChangedIntent: Observable<CharSequence>
val attachIntent: Observable<Unit>
val sendIntent: Observable<Unit>
fun setDraft(draft: String)
}
@@ -0,0 +1,411 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.telephony.PhoneNumberUtils
import android.telephony.SmsMessage
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import com.mlsdev.rximagepicker.RxImagePicker
import com.mlsdev.rximagepicker.Sources
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import common.util.ClipboardUtils
import common.util.extensions.makeToast
import common.util.filter.ContactFilter
import interactor.ContactSync
import interactor.DeleteMessage
import interactor.MarkRead
import interactor.RetrySending
import interactor.SendMessage
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.Observables
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.withLatestFrom
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import io.realm.RealmList
import model.Contact
import model.Conversation
import model.Message
import model.PhoneNumber
import presentation.common.Navigator
import presentation.common.base.QkViewModel
import repository.ContactRepository
import repository.MessageRepository
import util.extensions.asObservable
import java.net.URLDecoder
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class ComposeViewModel(intent: Intent) : QkViewModel<ComposeView, ComposeState>(ComposeState()) {
@Inject lateinit var context: Context
@Inject lateinit var contactFilter: ContactFilter
@Inject lateinit var contactsRepo: ContactRepository
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var navigator: Navigator
@Inject lateinit var syncContacts: ContactSync
@Inject lateinit var sendMessage: SendMessage
@Inject lateinit var retrySending: RetrySending
@Inject lateinit var markRead: MarkRead
@Inject lateinit var deleteMessage: DeleteMessage
private var sharedText: String = ""
private val attachments: Subject<List<Uri>> = BehaviorSubject.createDefault(ArrayList())
private val contacts: Observable<List<Contact>> by lazy { contactsRepo.getUnmanagedContacts().toObservable() }
private val contactsReducer: Subject<(List<Contact>) -> List<Contact>> = PublishSubject.create()
private val selectedContacts: Observable<List<Contact>>
private val conversation: Observable<Conversation>
private val messages: Observable<List<Message>>
init {
appComponent.inject(this)
sharedText = intent.extras?.getString(Intent.EXTRA_TEXT) ?: ""
// If there are any image attachments, we'll set those as the initial attachments for the
// conversation
val sharedImages = mutableListOf<Uri>()
intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)?.run { sharedImages += this }
intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)?.run { sharedImages += this }
attachments.onNext(sharedImages)
val threadId = intent.extras?.getLong("threadId") ?: 0L
var address = ""
intent.data?.let {
val data = it.toString()
address = when {
it.scheme.startsWith("smsto") -> data.replace("smsto:", "")
it.scheme.startsWith("mmsto") -> data.replace("mmsto:", "")
it.scheme.startsWith("sms") -> data.replace("sms:", "")
it.scheme.startsWith("mms") -> data.replace("mms:", "")
else -> ""
}
// The dialer app on Oreo sends a URL encoded string, make sure to decode it
if (address.contains('%')) address = URLDecoder.decode(address, "UTF-8")
}
val initialConversation: Observable<Conversation> = when {
threadId != 0L -> {
newState { it.copy(selectedConversation = threadId, editingMode = false) }
messageRepo.getConversationAsync(threadId).asObservable()
}
address.isNotBlank() -> {
newState { it.copy(editingMode = false) }
messageRepo.getOrCreateConversation(address).toObservable()
}
else -> {
newState { it.copy(editingMode = true) }
Observable.empty()
}
}
selectedContacts = contactsReducer
.scan(listOf<Contact>(), { previousState, reducer -> reducer(previousState) })
.doOnNext { contacts -> newState { it.copy(selectedContacts = contacts) } }
// Merges two potential conversation sources (threadId from constructor and contact selection) into a single
// stream of conversations. If the conversation was deleted, notify the activity to shut down
conversation = selectedContacts
.skipUntil(state.filter { state -> state.editingMode })
.takeUntil(state.filter { state -> !state.editingMode })
.map { contacts -> contacts.map { it.numbers.firstOrNull()?.address ?: "" } }
.flatMapMaybe { addresses -> messageRepo.getOrCreateConversation(addresses) }
.mergeWith(initialConversation)
.filter { conversation -> conversation.isLoaded }
.doOnNext { conversation ->
if (!conversation.isValid) {
newState { it.copy(hasError = true) }
}
}
.filter { conversation -> conversation.isValid }
.filter { conversation -> conversation.id != 0L }
.distinctUntilChanged()
// When the conversation changes, update the threadId and the messages for the adapter
messages = conversation
.distinctUntilChanged { conversation -> conversation.id }
.observeOn(AndroidSchedulers.mainThread())
.map { conversation ->
val messages = messageRepo.getMessages(conversation.id)
newState { it.copy(selectedConversation = conversation.id, messages = Pair(conversation, messages)) }
messages
}
.switchMap { messages -> messages.asObservable() }
disposables += sendMessage
disposables += markRead
disposables += conversation.subscribe()
disposables += messages.subscribe()
disposables += conversation
.distinctUntilChanged { conversation -> conversation.getTitle() }
.subscribe { conversation ->
newState { it.copy(title = conversation.getTitle()) }
}
disposables += conversation
.distinctUntilChanged { conversation -> conversation.archived }
.subscribe { conversation ->
newState { it.copy(archived = conversation.archived) }
}
disposables += attachments
.subscribe { attachments ->
newState { it.copy(attachments = attachments) }
}
if (threadId == 0L) {
syncContacts.execute(Unit)
}
}
override fun bindView(view: ComposeView) {
super.bindView(view)
// Set the contact suggestions list to visible at all times when in editing mode and there are no contacts
// selected yet, and also visible while in editing mode and there is text entered in the query field
Observables
.combineLatest(view.queryChangedIntent, selectedContacts, { query, selectedContacts ->
selectedContacts.isEmpty() || query.isNotEmpty()
})
.skipUntil(state.filter { state -> state.editingMode })
.takeUntil(state.filter { state -> !state.editingMode })
.distinctUntilChanged()
.autoDisposable(view.scope())
.subscribe { contactsVisible -> newState { it.copy(contactsVisible = contactsVisible && it.editingMode) } }
// Update the list of contact suggestions based on the query input, while also filtering out any contacts
// that have already been selected
Observables
.combineLatest(view.queryChangedIntent, contacts, selectedContacts, { query, contacts, selectedContacts ->
var filteredContacts = contacts
.filterNot { contact -> selectedContacts.contains(contact) }
.filter { contact -> contactFilter.filter(contact, query) }
if (PhoneNumberUtils.isWellFormedSmsAddress(query.toString())) {
filteredContacts = listOf(Contact(numbers = RealmList(PhoneNumber(address = query.toString())))) + filteredContacts
}
filteredContacts
})
.skipUntil(state.filter { state -> state.editingMode })
.takeUntil(state.filter { state -> !state.editingMode })
.subscribeOn(Schedulers.computation())
.autoDisposable(view.scope())
.subscribe { contacts -> newState { it.copy(contacts = contacts) } }
// Backspaces should delete the most recent contact if there's no text input
// Close the activity if user presses back
view.queryKeyEventIntent
.filter { event -> event.action == KeyEvent.ACTION_DOWN }
.withLatestFrom(selectedContacts, view.queryChangedIntent, { event, contacts, query ->
when (event.keyCode) {
KeyEvent.KEYCODE_DEL -> {
if (contacts.isNotEmpty() && query.isEmpty()) {
contactsReducer.onNext { it.dropLast(1) }
}
}
KeyEvent.KEYCODE_BACK -> {
newState { it.copy(hasError = true) }
}
}
})
.autoDisposable(view.scope())
.subscribe()
// Enter the first contact suggestion if the enter button is pressed
view.queryEditorActionIntent
.filter { actionId -> actionId == EditorInfo.IME_ACTION_DONE }
.withLatestFrom(state, { _, state -> state })
.autoDisposable(view.scope())
.subscribe { state ->
state.contacts.firstOrNull()?.let { contact ->
contactsReducer.onNext { contacts -> contacts + contact }
}
}
// Update the list of selected contacts when a new contact is selected or an existing one is deselected
Observable.merge(
view.chipDeletedIntent.doOnNext { contact ->
contactsReducer.onNext { contacts -> contacts.filterNot { it == contact } }
},
view.chipSelectedIntent.doOnNext { contact ->
contactsReducer.onNext { contacts -> contacts.toMutableList().apply { add(contact) } }
})
.skipUntil(state.filter { state -> state.editingMode })
.takeUntil(state.filter { state -> !state.editingMode })
.autoDisposable(view.scope())
.subscribe()
// When the menu is loaded, trigger a new state so that the menu options can be rendered correctly
view.menuReadyIntent
.autoDisposable(view.scope())
.subscribe { newState { it.copy() } }
// Open the phone dialer if the call button is clicked
view.callIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.map { conversation -> conversation.recipients.first() }
.map { recipient -> recipient.address }
.autoDisposable(view.scope())
.subscribe { address -> navigator.makePhoneCall(address) }
// Open the conversation settings if info button is clicked
view.infoIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.autoDisposable(view.scope())
.subscribe { conversation -> navigator.showConversationInfo(conversation.id) }
view.messageClickIntent
.filter { message -> message.isFailedMessage() }
.doOnNext { message -> retrySending.execute(message) }
.autoDisposable(view.scope())
.subscribe()
// Mark the conversation read, if in foreground
Observables.combineLatest(messages, view.activityVisibleIntent, { _, b -> b })
.withLatestFrom(conversation, { visible, conversation ->
if (visible && conversation.isValid) markRead.execute(conversation.id)
})
.autoDisposable(view.scope())
.subscribe()
// Attach a photo
view.attachIntent
.flatMap { RxImagePicker.with(context).requestImage(Sources.GALLERY) }
.withLatestFrom(attachments, { attachment, attachments -> attachments + attachment })
.autoDisposable(view.scope())
.subscribe { attachments.onNext(it) }
// Detach a photo
view.attachmentDeletedIntent
.withLatestFrom(attachments, { bitmap, attachments -> attachments.filter { it !== bitmap } })
.autoDisposable(view.scope())
.subscribe { attachments.onNext(it) }
conversation
.map { conversation -> conversation.draft }
.distinctUntilChanged()
.autoDisposable(view.scope())
.subscribe { draft ->
// If text was shared into the conversation, it should take priority over the
// existing draft
//
// TODO: Show dialog warning user about overwriting draft
if (sharedText.isNotBlank()) {
view.setDraft(sharedText)
} else {
view.setDraft(draft)
}
}
// Enable the send button when there is text input into the new message body or there's
// an attachment, disable otherwise
Observables
.combineLatest(view.textChangedIntent, attachments, { text, attachments ->
text.isNotBlank() || attachments.isNotEmpty()
})
.autoDisposable(view.scope())
.subscribe { canSend -> newState { it.copy(canSend = canSend) } }
// Show the remaining character counter when necessary
view.textChangedIntent
.observeOn(Schedulers.computation())
.map { draft -> SmsMessage.calculateLength(draft, false) }
.map { array ->
val messages = array[0]
val remaining = array[2]
when {
messages <= 1 && remaining > 10 -> ""
messages <= 1 && remaining <= 10 -> "$remaining"
else -> "$remaining / $messages"
}
}
.distinctUntilChanged()
.autoDisposable(view.scope())
.subscribe { remaining -> newState { it.copy(remaining = remaining) } }
// Update the draft whenever the text is changed
view.textChangedIntent
.debounce(100, TimeUnit.MILLISECONDS)
.map { draft -> draft.toString() }
.observeOn(Schedulers.io())
.withLatestFrom(conversation.map { it.id }, { draft, threadId ->
messageRepo.saveDraft(threadId, draft)
})
.autoDisposable(view.scope())
.subscribe()
// Send a message when the send button is clicked, and disable editing mode if it's enabled
view.sendIntent
.withLatestFrom(view.textChangedIntent, { _, body -> body })
.map { body -> body.toString() }
.withLatestFrom(attachments, conversation, { body, attachments, conversation ->
val threadId = conversation.id
val addresses = conversation.recipients.map { it.address }
sendMessage.execute(SendMessage.Params(threadId, addresses, body, attachments))
view.setDraft("")
this.attachments.onNext(ArrayList())
})
.withLatestFrom(state, { _, state ->
if (state.editingMode) {
newState { it.copy(editingMode = false) }
}
})
.autoDisposable(view.scope())
.subscribe()
// Copy the body of the selected message into the clipboard
view.copyTextIntent
.autoDisposable(view.scope())
.subscribe { message ->
ClipboardUtils.copy(context, message.body)
context.makeToast(R.string.toast_copied)
}
// Forward the message
view.forwardMessageIntent
.autoDisposable(view.scope())
.subscribe { message -> navigator.showCompose(message.body) }
// Delete the selected message
view.deleteMessageIntent
.autoDisposable(view.scope())
.subscribe { message -> deleteMessage.execute(message.id) }
}
}
@@ -0,0 +1,143 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.app.Activity
import android.graphics.Rect
import android.os.Build
import android.support.annotation.RequiresApi
import android.view.ActionMode
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.MotionEvent
import android.view.SearchEvent
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
class ComposeWindowCallback(private val localCallback: Window.Callback, private val activity: Activity) : Window.Callback {
override fun dispatchKeyEvent(keyEvent: KeyEvent): Boolean {
return localCallback.dispatchKeyEvent(keyEvent)
}
override fun dispatchKeyShortcutEvent(keyEvent: KeyEvent): Boolean {
return localCallback.dispatchKeyShortcutEvent(keyEvent)
}
override fun dispatchTouchEvent(motionEvent: MotionEvent): Boolean {
if (motionEvent.action == MotionEvent.ACTION_DOWN) {
val v = activity.currentFocus
when (v) {
is DetailedChipView -> {
val rect = Rect().apply { v.getGlobalVisibleRect(this) }
if (!rect.contains(motionEvent.rawX.toInt(), motionEvent.rawY.toInt())) {
v.hide()
return true
}
}
}
}
return localCallback.dispatchTouchEvent(motionEvent)
}
override fun dispatchTrackballEvent(motionEvent: MotionEvent): Boolean {
return localCallback.dispatchTrackballEvent(motionEvent)
}
override fun dispatchGenericMotionEvent(motionEvent: MotionEvent): Boolean {
return localCallback.dispatchGenericMotionEvent(motionEvent)
}
override fun dispatchPopulateAccessibilityEvent(accessibilityEvent: AccessibilityEvent): Boolean {
return localCallback.dispatchPopulateAccessibilityEvent(accessibilityEvent)
}
override fun onCreatePanelView(i: Int): View? {
return localCallback.onCreatePanelView(i)
}
override fun onCreatePanelMenu(i: Int, menu: Menu): Boolean {
return localCallback.onCreatePanelMenu(i, menu)
}
override fun onPreparePanel(i: Int, view: View, menu: Menu): Boolean {
return localCallback.onPreparePanel(i, view, menu)
}
override fun onMenuOpened(i: Int, menu: Menu): Boolean {
return localCallback.onMenuOpened(i, menu)
}
override fun onMenuItemSelected(i: Int, menuItem: MenuItem): Boolean {
return localCallback.onMenuItemSelected(i, menuItem)
}
override fun onWindowAttributesChanged(layoutParams: WindowManager.LayoutParams) {
localCallback.onWindowAttributesChanged(layoutParams)
}
override fun onContentChanged() {
localCallback.onContentChanged()
}
override fun onWindowFocusChanged(b: Boolean) {
localCallback.onWindowFocusChanged(b)
}
override fun onAttachedToWindow() {
localCallback.onAttachedToWindow()
}
override fun onDetachedFromWindow() {
localCallback.onDetachedFromWindow()
}
override fun onPanelClosed(i: Int, menu: Menu) {
localCallback.onPanelClosed(i, menu)
}
override fun onSearchRequested(): Boolean {
return localCallback.onSearchRequested()
}
@RequiresApi(api = Build.VERSION_CODES.M)
override fun onSearchRequested(searchEvent: SearchEvent): Boolean {
return localCallback.onSearchRequested(searchEvent)
}
override fun onWindowStartingActionMode(callback: ActionMode.Callback): ActionMode? {
return localCallback.onWindowStartingActionMode(callback)
}
@RequiresApi(api = Build.VERSION_CODES.M)
override fun onWindowStartingActionMode(callback: ActionMode.Callback, i: Int): ActionMode? {
return localCallback.onWindowStartingActionMode(callback, i)
}
override fun onActionModeStarted(actionMode: ActionMode) {
localCallback.onActionModeStarted(actionMode)
}
override fun onActionModeFinished(actionMode: ActionMode) {
localCallback.onActionModeFinished(actionMode)
}
}
@@ -0,0 +1,86 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import common.util.extensions.setVisible
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.contact_list_item.view.*
import model.Contact
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import javax.inject.Inject
class ContactAdapter @Inject constructor(private val context: Context) : QkAdapter<Contact>() {
val contactSelected: Subject<Contact> = PublishSubject.create()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val layoutRes = R.layout.contact_list_item
val layoutInflater = LayoutInflater.from(context)
val view = layoutInflater.inflate(layoutRes, parent, false)
return QkViewHolder(view)
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val contact = getItem(position)
val view = holder.itemView
view.primary.clicks().subscribe { contactSelected.onNext(copyContact(contact, 0)) }
view.avatar.contact = contact
view.name.text = contact.name
view.name.setVisible(view.name.text.isNotEmpty())
view.address.text = contact.numbers.first()?.address ?: ""
view.type.text = contact.numbers.first()?.type ?: ""
view.addresses.removeAllViews()
contact.numbers.forEachIndexed { index, number ->
if (index != 0) {
val numberView = View.inflate(context, R.layout.contact_number_list_item, null)
numberView.clicks().subscribe { contactSelected.onNext(copyContact(contact, index)) }
numberView.address.text = number.address
numberView.type.text = number.type
view.addresses.addView(numberView)
}
}
}
/**
* Creates a copy of the contact with only one phone number, so that the chips
* view can still display the name/photo, and not get confused about which phone number to use
*/
private fun copyContact(contact: Contact, numberIndex: Int) = Contact().apply {
lookupKey = contact.lookupKey
name = contact.name
numbers.add(contact.numbers[numberIndex])
}
override fun areItemsTheSame(old: Contact, new: Contact): Boolean {
return old.lookupKey == new.lookupKey
}
}
@@ -0,0 +1,86 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.content.Context
import android.view.View
import android.view.animation.AlphaAnimation
import android.widget.RelativeLayout
import com.moez.QKSMS.R
import com.uber.autodispose.android.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import common.util.Colors
import common.util.extensions.setBackgroundTint
import kotlinx.android.synthetic.main.contact_chip_detailed.view.*
import model.Contact
import javax.inject.Inject
class DetailedChipView(context: Context) : RelativeLayout(context) {
@Inject lateinit var colors: Colors
init {
View.inflate(context, R.layout.contact_chip_detailed, this)
appComponent.inject(this)
setOnClickListener { hide() }
visibility = View.GONE
isFocusable = true
isFocusableInTouchMode = true
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
colors.theme
.autoDisposable(scope())
.subscribe { color -> card.setBackgroundTint(color) }
}
fun setContact(contact: Contact) {
avatar.contact = contact
name.text = contact.name
info.text = contact.numbers.map { it.address }.toString()
}
fun show() {
startAnimation(AlphaAnimation(0f, 1f).apply { duration = 200 })
visibility = View.VISIBLE
requestFocus()
isClickable = true
}
fun hide() {
startAnimation(AlphaAnimation(1f, 0f).apply { duration = 200 })
visibility = View.GONE
clearFocus()
isClickable = false
}
fun setOnDeleteListener(listener: (View) -> Unit) {
delete.setOnClickListener(listener)
}
}
@@ -0,0 +1,256 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.telephony.PhoneNumberUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jakewharton.rxbinding2.view.RxView
import com.moez.QKSMS.R
import common.util.Colors
import common.util.DateFormatter
import common.util.extensions.dpToPx
import common.util.extensions.setBackgroundTint
import common.util.extensions.setPadding
import common.util.extensions.setVisible
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import io.realm.RealmList
import io.realm.RealmRecyclerViewAdapter
import io.realm.RealmResults
import kotlinx.android.synthetic.main.message_list_item_in.view.*
import model.Contact
import model.Conversation
import model.Message
import model.PhoneNumber
import presentation.common.base.QkViewHolder
import util.extensions.isImage
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class MessagesAdapter @Inject constructor(
private val context: Context,
private val colors: Colors,
private val dateFormatter: DateFormatter
) : RealmRecyclerViewAdapter<Message, QkViewHolder>(null, true) {
companion object {
private const val VIEW_TYPE_ME = 1
private const val TIMESTAMP_THRESHOLD = 10
}
val clicks: Subject<Message> = PublishSubject.create<Message>()
val longClicks: Subject<Message> = PublishSubject.create<Message>()
var data: Pair<Conversation, RealmResults<Message>>? = null
set(value) {
field = value
people.clear()
contactMap.clear()
// Update the theme
val threadId = value?.first?.id ?: 0
theme = colors.themeForConversation(threadId)
textPrimaryOnTheme = colors.textPrimaryOnThemeForConversation(threadId)
updateData(value?.second)
}
private val people = ArrayList<String>()
private val contactMap = HashMap<String, Contact>()
private val selected = HashMap<Long, Boolean>()
private val disposables = CompositeDisposable()
private var theme = colors.theme
private var textPrimaryOnTheme = colors.textPrimaryOnTheme
/**
* If the viewType is negative, then the viewHolder has an attachment. We'll consider
* this a unique viewType even though it uses the same view, so that regular messages
* don't need clipToOutline set to true, and they don't need to worry about images
*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val layoutInflater = LayoutInflater.from(context)
val view: View
val hasThumbnail = viewType < 0
val absViewType = Math.abs(viewType)
if (absViewType == VIEW_TYPE_ME) {
view = layoutInflater.inflate(R.layout.message_list_item_out, parent, false)
disposables += colors.bubble
.subscribe { color -> view.messageBackground.setBackgroundTint(color) }
} else {
view = layoutInflater.inflate(R.layout.message_list_item_in, parent, false)
view.subject.textColorObservable = textPrimaryOnTheme
view.body.textColorObservable = textPrimaryOnTheme
disposables += theme
.subscribe { color -> view.messageBackground.setBackgroundTint(color) }
}
if (hasThumbnail) {
view.messageBackground.clipToOutline = true
}
if (absViewType != VIEW_TYPE_ME) {
val address = people[absViewType - 2]
if (!contactMap.containsKey(address)) {
contactMap[address] = data?.first?.recipients?.mapNotNull { it.contact } // Map the conversation to its contacts
?.firstOrNull { it.numbers.any { PhoneNumberUtils.compare(it.address, address) } } // See if any of the phone numbers match
?: Contact(numbers = RealmList(PhoneNumber(address = address))) // Fallback to a fake contact
}
view.avatar.threadId = data?.first?.id ?: 0
view.avatar.contact = contactMap[address]
}
return QkViewHolder(view)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
disposables.clear()
}
override fun onBindViewHolder(viewHolder: QkViewHolder, position: Int) {
val message = getItem(position)!!
val view = viewHolder.itemView
RxView.clicks(view).subscribe {
clicks.onNext(message)
selected[message.id] = view.status.visibility != View.VISIBLE
notifyItemChanged(position)
}
RxView.longClicks(view).subscribe { longClicks.onNext(message) }
view.subject.text = message.getCleansedSubject()
view.subject.setVisible(view.subject.text.isNotBlank())
view.body.text = message.getText()
view.body.setVisible(message.isSms() || view.body.text.isNotEmpty() || message.parts.all { it.image == null })
view.timestamp.text = dateFormatter.getMessageTimestamp(message.date)
bindMmsPreview(view, position)
bindStatus(view, position)
bindGrouping(view, position)
}
private fun bindMmsPreview(view: View, position: Int) {
val message = getItem(position)!!
view.mmsPreview.parts = message.parts
}
private fun bindStatus(view: View, position: Int) {
val message = getItem(position)!!
val next = if (position == itemCount - 1) null else getItem(position + 1)
val age = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - message.date)
val timestamp = dateFormatter.getTimestamp(message.date)
view.status.text = when {
message.isSending() -> context.getString(R.string.message_status_sending)
message.isDelivered() -> context.getString(R.string.message_status_delivered, timestamp)
message.isFailedMessage() -> context.getString(R.string.message_status_failed)
!message.isMe() && data?.first?.recipients?.size ?: 0 > 1 -> "${contactMap[message.address]?.name} • $timestamp"
else -> timestamp
}
view.status.setVisible(when {
selected[message.id] == true -> true
message.isSending() -> true
message.isFailedMessage() -> true
selected[message.id] == false -> false
data?.first?.recipients?.size ?: 0 > 1 && !message.isMe() && next?.compareSender(message) != true -> true
message.isDelivered() && age <= TIMESTAMP_THRESHOLD -> true
else -> false
})
}
private fun bindGrouping(view: View, position: Int) {
val message = getItem(position)!!
val previous = if (position == 0) null else getItem(position - 1)
val next = if (position == itemCount - 1) null else getItem(position + 1)
val diff = TimeUnit.MILLISECONDS.toMinutes(message.date - (previous?.date ?: 0))
val sent = message.isMe()
val canGroupWithPrevious = canGroup(message, previous)
val canGroupWithNext = canGroup(message, next)
view.timestamp.visibility = if (diff < TIMESTAMP_THRESHOLD) View.GONE else View.VISIBLE
when {
!canGroupWithPrevious && canGroupWithNext -> {
view.setPadding(bottom = 2.dpToPx(context))
view.messageBackground.setBackgroundResource(if (sent) R.drawable.message_out_first else R.drawable.message_in_first)
view.avatar?.visibility = View.INVISIBLE
}
canGroupWithPrevious && canGroupWithNext -> {
view.setPadding(bottom = 2.dpToPx(context))
view.messageBackground.setBackgroundResource(if (sent) R.drawable.message_out_middle else R.drawable.message_in_middle)
view.avatar?.visibility = View.INVISIBLE
}
canGroupWithPrevious && !canGroupWithNext -> {
view.setPadding(bottom = 16.dpToPx(context))
view.messageBackground.setBackgroundResource(if (sent) R.drawable.message_out_last else R.drawable.message_in_last)
view.avatar?.visibility = View.VISIBLE
}
else -> {
view.setPadding(bottom = 16.dpToPx(context))
view.messageBackground.setBackgroundResource(R.drawable.message_only)
view.avatar?.visibility = View.VISIBLE
}
}
if (getItemViewType(position) < 0) view.messageBackground.setBackgroundResource(R.drawable.message_only)
}
private fun canGroup(message: Message, other: Message?): Boolean {
if (other == null) return false
val diff = TimeUnit.MILLISECONDS.toMinutes(Math.abs(message.date - other.date))
return message.compareSender(other) && diff < TIMESTAMP_THRESHOLD
}
override fun getItemViewType(position: Int): Int {
val message = getItem(position)!!
var index = if (message.isMe()) {
VIEW_TYPE_ME
} else {
if (!people.contains(message.address)) {
people.add(message.address)
}
2 + people.indexOf(message.address)
}
// If it contains a thumbnail, then use the negative viewtype
if (message.parts.filter { it.isImage() }.any()) {
index *= -1
}
return index
}
}
@@ -0,0 +1,109 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.conversationinfo
import android.os.Bundle
import android.support.v7.app.AlertDialog
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import common.util.extensions.setVisible
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.conversation_info_activity.*
import presentation.common.Navigator
import presentation.common.base.QkThemedActivity
import javax.inject.Inject
class ConversationInfoActivity : QkThemedActivity<ConversationInfoViewModel>(), ConversationInfoView {
override val viewModelClass = ConversationInfoViewModel::class
override val notificationsIntent by lazy { notifications.clicks() }
override val themeIntent by lazy { themePrefs.clicks() }
override val archiveIntent by lazy { archive.clicks() }
override val blockIntent by lazy { block.clicks() }
override val deleteIntent by lazy { delete.clicks() }
override val confirmDeleteIntent: PublishSubject<Unit> = PublishSubject.create()
@Inject lateinit var navigator: Navigator
@Inject lateinit var recipientAdapter: ConversationRecipientAdapter
@Inject lateinit var mediaAdapter: ConversationMediaAdapter
@Inject lateinit var itemDecoration: GridSpacingItemDecoration
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.conversation_info_activity)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
setTitle(R.string.info_title)
colors.background
.autoDisposable(scope())
.subscribe { color -> window.decorView.setBackgroundColor(color) }
mediaAdapter.thumbnailClicks
.autoDisposable(scope())
.subscribe { view -> navigator.showImageAnimated(this, view) }
recipients.adapter = recipientAdapter
media.adapter = mediaAdapter
media.addItemDecoration(itemDecoration)
}
override fun render(state: ConversationInfoState) {
if (state.hasError) {
finish()
return
}
recipientAdapter.data = state.recipients
recipientAdapter.threadId = state.threadId
notifications.setVisible(!state.blocked)
archive.setVisible(!state.blocked)
archive.title = getString(when (state.archived) {
true -> R.string.info_unarchive
false -> R.string.info_archive
})
block.title = getString(when (state.blocked) {
true -> R.string.info_unblock
false -> R.string.info_block
})
mediaAdapter.data = state.media
}
override fun showDeleteDialog() {
AlertDialog.Builder(this)
.setTitle(R.string.dialog_delete_title)
.setMessage(R.string.dialog_delete_message)
.setPositiveButton(R.string.button_delete, { _, _ -> confirmDeleteIntent.onNext(Unit) })
.setNegativeButton(R.string.button_cancel, null)
.show()
}
}
@@ -0,0 +1,31 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.conversationinfo
import model.MmsPart
import model.Recipient
data class ConversationInfoState(
val recipients: List<Recipient> = listOf(),
val threadId: Long = 0,
val archived: Boolean = false,
val blocked: Boolean = false,
val media: List<MmsPart> = ArrayList(),
val hasError: Boolean = false
)
@@ -0,0 +1,35 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.conversationinfo
import io.reactivex.Observable
import presentation.common.base.QkView
interface ConversationInfoView : QkView<ConversationInfoState> {
val notificationsIntent: Observable<Unit>
val themeIntent: Observable<Unit>
val archiveIntent: Observable<Unit>
val blockIntent: Observable<Unit>
val deleteIntent: Observable<Unit>
val confirmDeleteIntent: Observable<Unit>
fun showDeleteDialog()
}
@@ -0,0 +1,153 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.conversationinfo
import android.content.Context
import android.content.Intent
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import interactor.DeleteConversation
import interactor.MarkArchived
import interactor.MarkBlocked
import interactor.MarkUnarchived
import interactor.MarkUnblocked
import io.reactivex.Observable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.withLatestFrom
import model.Conversation
import presentation.common.Navigator
import presentation.common.base.QkViewModel
import repository.MessageRepository
import util.extensions.asObservable
import util.extensions.isImage
import javax.inject.Inject
class ConversationInfoViewModel(intent: Intent) : QkViewModel<ConversationInfoView,
ConversationInfoState>(ConversationInfoState()) {
@Inject lateinit var context: Context
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var markArchived: MarkArchived
@Inject lateinit var markUnarchived: MarkUnarchived
@Inject lateinit var markBlocked: MarkBlocked
@Inject lateinit var markUnblocked: MarkUnblocked
@Inject lateinit var navigator: Navigator
@Inject lateinit var deleteConversation: DeleteConversation
private val conversation: Observable<Conversation>
init {
appComponent.inject(this)
val threadId = intent.extras?.getLong("threadId") ?: 0L
newState { it.copy(threadId = threadId) }
conversation = messageRepo.getConversationAsync(threadId)
.asObservable<Conversation>()
.filter { conversation -> conversation.isLoaded }
.doOnNext { conversation ->
if (!conversation.isValid) {
newState { it.copy(hasError = true) }
}
}
.filter { conversation -> conversation.isValid }
.filter { conversation -> conversation.id != 0L }
disposables += markArchived
disposables += markUnarchived
disposables += markBlocked
disposables += markUnblocked
disposables += deleteConversation
// Update the recipients whenever they change
disposables += conversation
.map { conversation -> conversation.recipients }
.distinctUntilChanged()
.subscribe { recipients -> newState { it.copy(recipients = recipients) } }
// Update the view's archived state whenever it changes
disposables += conversation
.map { conversation -> conversation.archived }
.distinctUntilChanged()
.subscribe { archived -> newState { it.copy(archived = archived) } }
// Update the view's blocked state whenever it changes
disposables += conversation
.map { conversation -> conversation.blocked }
.distinctUntilChanged()
.subscribe { blocked -> newState { it.copy(blocked = blocked) } }
// Load the attachments from the conversation
disposables += messageRepo.getPartsForConversation(threadId)
.map { parts -> parts.filter { part -> part.isImage() } }
.map { parts -> parts.reversed() }
.subscribe { media -> newState { it.copy(media = media) } }
}
override fun bindView(view: ConversationInfoView) {
super.bindView(view)
// Show the notifications settings for the conversation
view.notificationsIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.autoDisposable(view.scope())
.subscribe { conversation -> navigator.showNotificationSettings(conversation.id) }
// Show the theme settings for the conversation
view.themeIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.autoDisposable(view.scope())
.subscribe { conversation -> navigator.showThemePicker(conversation.id) }
// Toggle the archived state of the conversation
view.archiveIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.autoDisposable(view.scope())
.subscribe { conversation ->
when (conversation.archived) {
true -> markUnarchived.execute(conversation.id)
false -> markArchived.execute(conversation.id)
}
}
// Toggle the blocked state of the conversation
view.blockIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.autoDisposable(view.scope())
.subscribe { conversation ->
when (conversation.blocked) {
true -> markUnblocked.execute(conversation.id)
false -> markBlocked.execute(conversation.id)
}
}
// Show the delete confirmation dialog
view.deleteIntent
.autoDisposable(view.scope())
.subscribe { view.showDeleteDialog() }
// Delete the conversation
view.confirmDeleteIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.autoDisposable(view.scope())
.subscribe { conversation -> deleteConversation.execute(conversation.id) }
}
}
@@ -0,0 +1,72 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.conversationinfo
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.moez.QKSMS.R
import common.util.Colors
import common.util.GlideApp
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.conversation_media_list_item.view.*
import model.MmsPart
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import javax.inject.Inject
class ConversationMediaAdapter @Inject constructor(
private val context: Context,
private val colors: Colors
) : QkAdapter<MmsPart>() {
val thumbnailClicks: PublishSubject<View> = PublishSubject.create()
private val disposables = CompositeDisposable()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.conversation_media_list_item, parent, false)
disposables += colors.separator.subscribe { color -> view.setBackgroundColor(color) }
return QkViewHolder(view)
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val part = getItem(position)
val view = holder.itemView
GlideApp.with(context)
.load(part.image)
.fitCenter()
.into(view.thumbnail)
view.thumbnail.transitionName = part.id.toString()
view.thumbnail.setOnClickListener { thumbnailClicks.onNext(it) }
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
disposables.clear()
}
}
@@ -0,0 +1,86 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.conversationinfo
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.moez.QKSMS.R
import common.util.Colors
import common.util.extensions.setTint
import common.util.extensions.setVisible
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import kotlinx.android.synthetic.main.conversation_recipient_list_item.view.*
import model.Recipient
import presentation.common.Navigator
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import javax.inject.Inject
class ConversationRecipientAdapter @Inject constructor(
private val context: Context,
private val colors: Colors,
private val navigator: Navigator
) : QkAdapter<Recipient>() {
var threadId: Long = 0L
private val disposables = CompositeDisposable()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val layoutInflater = LayoutInflater.from(context)
val view = layoutInflater.inflate(R.layout.conversation_recipient_list_item, parent, false)
disposables += colors.textSecondary
.subscribe { color -> view.add.setTint(color) }
return QkViewHolder(view)
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val recipient = getItem(position)
val view = holder.itemView
view.setOnClickListener {
if (recipient.contact == null) {
navigator.addContact(recipient.address)
} else {
view.avatar.callOnClick()
}
}
view.avatar.threadId = threadId
view.avatar.contact = recipient.contact
view.name.text = recipient.contact?.name ?: recipient.address
view.address.text = recipient.address
view.address.setVisible(recipient.contact != null)
view.add.setVisible(recipient.contact == null)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
disposables.clear()
}
}
@@ -0,0 +1,47 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.conversationinfo
import android.content.Context
import android.graphics.Rect
import android.support.v7.widget.RecyclerView
import android.view.View
import common.util.extensions.dpToPx
import javax.inject.Inject
class GridSpacingItemDecoration @Inject constructor(context: Context) : RecyclerView.ItemDecoration() {
private val spanCount = 3
private val spacing = 2.dpToPx(context)
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val position = parent.getChildAdapterPosition(view)
val column = position % spanCount
outRect.left = column * spacing / spanCount
outRect.right = spacing - (column + 1) * spacing / spanCount
if (position >= spanCount) {
outRect.top = spacing
}
}
}
@@ -0,0 +1,39 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.conversations
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import javax.inject.Inject
class ConversationItemTouchCallback @Inject constructor() : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
val swipes: Subject<Int> = PublishSubject.create()
override fun onMove(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, target: RecyclerView.ViewHolder?): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
swipes.onNext(viewHolder.adapterPosition)
}
}
@@ -0,0 +1,109 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.conversations
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.jakewharton.rxbinding2.view.clicks
import com.jakewharton.rxbinding2.view.longClicks
import com.moez.QKSMS.R
import common.util.Colors
import common.util.DateFormatter
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.conversation_list_item.view.*
import model.Contact
import model.Conversation
import model.Message
import model.PhoneNumber
import presentation.common.Navigator
import presentation.common.base.FlowableAdapter
import presentation.common.base.QkViewHolder
import repository.MessageRepository
import javax.inject.Inject
class ConversationsAdapter @Inject constructor(
val context: Context,
val navigator: Navigator,
val messageRepo: MessageRepository,
val dateFormatter: DateFormatter,
val colors: Colors
) : FlowableAdapter<Pair<Conversation, Message>>() {
val clicks: Subject<Long> = PublishSubject.create()
val longClicks: Subject<Long> = PublishSubject.create()
private val disposables = CompositeDisposable()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val layoutRes = when (viewType) {
0 -> R.layout.conversation_list_item
else -> R.layout.conversation_list_item_unread
}
val layoutInflater = LayoutInflater.from(context)
val view = layoutInflater.inflate(layoutRes, parent, false)
if (viewType == 1) {
disposables += colors.theme
.subscribe { color -> view.date.setTextColor(color) }
}
return QkViewHolder(view)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
disposables.clear()
}
override fun onBindViewHolder(viewHolder: QkViewHolder, position: Int) {
val conversation = getItem(position).first
val message = getItem(position).second
val view = viewHolder.itemView
view.clicks().subscribe { clicks.onNext(conversation.id) }
view.longClicks().subscribe { longClicks.onNext(conversation.id) }
view.avatars.contacts = conversation.recipients.map { recipient ->
recipient.contact ?: Contact().apply { numbers.add(PhoneNumber().apply { address = recipient.address }) }
}
view.title.text = conversation.getTitle()
view.date.text = dateFormatter.getConversationTimestamp(message.date)
view.snippet.text = if (message.isMe()) "You: ${message.getSummary()}" else message.getSummary()
}
override fun getItemViewType(position: Int): Int {
return if (getItem(position).second.read) 0 else 1
}
override fun areItemsTheSame(old: Pair<Conversation, Message>, new: Pair<Conversation, Message>): Boolean {
return old.first.id == new.first.id
}
override fun areContentsTheSame(old: Pair<Conversation, Message>, new: Pair<Conversation, Message>): Boolean {
return old.second.id == new.second.id &&
old.second.read == new.second.read &&
old.first.recipients == new.first.recipients
}
}
@@ -0,0 +1,107 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.gallery
import android.os.Bundle
import android.transition.ChangeBounds
import android.transition.ChangeImageTransform
import android.transition.TransitionSet
import android.view.Menu
import android.view.MenuItem
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import common.util.GlideApp
import common.util.extensions.setVisible
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.gallery_activity.*
import presentation.common.GlideCompletionListener
import presentation.common.base.QkActivity
class GalleryActivity : QkActivity<GalleryViewModel>(), GalleryView {
override val viewModelClass = GalleryViewModel::class
override val screenTouchedIntent by lazy { image.clicks() }
override val optionsItemSelectedIntent: Subject<Int> = PublishSubject.create()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.gallery_activity)
postponeEnterTransition()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
val transition = TransitionSet().apply {
duration = 100
addTransition(ChangeBounds())
addTransition(ChangeImageTransform())
}
window.sharedElementReturnTransition = transition
window.sharedElementEnterTransition = transition
image.transitionName = intent.getLongExtra("partId", 0L).toString()
// When calling the public setter, it doesn't allow the midscale to be the same as the
// maxscale or the minscale. We don't want 3 levels and we don't want to modify the library
// so let's celebrate the invention of reflection!
image.attacher.run {
javaClass.getDeclaredField("mMinScale").run {
isAccessible = true
setFloat(image.attacher, 1f)
}
javaClass.getDeclaredField("mMidScale").run {
isAccessible = true
setFloat(image.attacher, 1f)
}
javaClass.getDeclaredField("mMaxScale").run {
isAccessible = true
setFloat(image.attacher, 3f)
}
}
}
override fun render(state: GalleryState) {
toolbar.setVisible(state.navigationVisible)
title = state.title
if (image.drawable == null) {
GlideApp.with(this)
.load(state.imagePath)
.dontAnimate()
.listener(GlideCompletionListener {
startPostponedEnterTransition()
})
.into(image)
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.gallery, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
optionsItemSelectedIntent.onNext(item.itemId)
return true
}
}
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.gallery
data class GalleryState(
val navigationVisible: Boolean = true,
val title: String = "",
val imagePath: String = ""
)
@@ -0,0 +1,29 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.gallery
import io.reactivex.Observable
import presentation.common.base.QkView
interface GalleryView : QkView<GalleryState> {
val screenTouchedIntent: Observable<Unit>
val optionsItemSelectedIntent: Observable<Int>
}
@@ -0,0 +1,79 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.gallery
import android.content.Context
import android.content.Intent
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import common.util.extensions.makeToast
import interactor.SaveImage
import io.reactivex.Flowable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.withLatestFrom
import presentation.common.base.QkViewModel
import repository.MessageRepository
import util.extensions.mapNotNull
import javax.inject.Inject
class GalleryViewModel(intent: Intent) : QkViewModel<GalleryView, GalleryState>(GalleryState()) {
@Inject lateinit var context: Context
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var saveImage: SaveImage
private val partIdFlowable = Flowable.just(intent)
.map { it.getLongExtra("partId", 0L) }
.filter { partId -> partId != 0L }
init {
appComponent.inject(this)
disposables += partIdFlowable
.mapNotNull { partId -> messageRepo.getPart(partId) }
.mapNotNull { part -> part.image }
.subscribe { path -> newState { it.copy(imagePath = path) } }
disposables += partIdFlowable
.mapNotNull { partId -> messageRepo.getMessageForPart(partId) }
.mapNotNull { message -> messageRepo.getConversation(message.threadId) }
.subscribe { conversation -> newState { it.copy(title = conversation.getTitle()) } }
}
override fun bindView(view: GalleryView) {
super.bindView(view)
// When the screen is touched, toggle the visibility of the navigation UI
view.screenTouchedIntent
.withLatestFrom(state, { _, state -> state.navigationVisible })
.map { navigationVisible -> !navigationVisible }
.autoDisposable(view.scope())
.subscribe { navigationVisible -> newState { it.copy(navigationVisible = navigationVisible) } }
// Save image to device
view.optionsItemSelectedIntent
.filter { itemId -> itemId == R.id.save }
.withLatestFrom(partIdFlowable.toObservable(), { _, partId -> partId })
.autoDisposable(view.scope())
.subscribe { partId -> saveImage.execute(partId) { context.makeToast(R.string.gallery_toast_saved) } }
}
}
@@ -0,0 +1,283 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.main
import android.app.AlertDialog
import android.content.res.ColorStateList
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.StateListDrawable
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import com.jakewharton.rxbinding2.support.v4.widget.drawerOpen
import com.jakewharton.rxbinding2.view.clicks
import com.jakewharton.rxbinding2.widget.textChanges
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import common.util.extensions.dpToPx
import common.util.extensions.setBackgroundTint
import common.util.extensions.setVisible
import io.reactivex.Observable
import io.reactivex.rxkotlin.Observables
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.drawer_view.*
import kotlinx.android.synthetic.main.main_activity.*
import presentation.common.MenuItemAdapter
import presentation.common.Navigator
import presentation.common.base.QkThemedActivity
import presentation.feature.conversations.ConversationItemTouchCallback
import presentation.feature.conversations.ConversationsAdapter
import javax.inject.Inject
class MainActivity : QkThemedActivity<MainViewModel>(), MainView {
@Inject lateinit var navigator: Navigator
@Inject lateinit var conversationsAdapter: ConversationsAdapter
@Inject lateinit var itemTouchCallback: ConversationItemTouchCallback
@Inject lateinit var menuItemAdapter: MenuItemAdapter
override val viewModelClass = MainViewModel::class
override val queryChangedIntent by lazy { toolbarSearch.textChanges() }
override val queryCancelledIntent: PublishSubject<Unit> = PublishSubject.create()
override val composeIntent by lazy { compose.clicks() }
override val drawerOpenIntent by lazy { drawerLayout.drawerOpen(Gravity.START) }
override val drawerItemIntent: Observable<DrawerItem> by lazy {
Observable.merge(listOf(
inbox.clicks().map { DrawerItem.INBOX },
archived.clicks().map { DrawerItem.ARCHIVED },
scheduled.clicks().map { DrawerItem.SCHEDULED },
settings.clicks().map { DrawerItem.SETTINGS },
plus.clicks().map { DrawerItem.PLUS },
help.clicks().map { DrawerItem.HELP }))
}
override val conversationClickIntent by lazy { conversationsAdapter.clicks }
override val conversationLongClickIntent by lazy { conversationsAdapter.longClicks }
override val conversationMenuItemIntent by lazy { menuItemAdapter.menuItemClicks }
override val confirmDeleteIntent: Subject<Unit> = PublishSubject.create()
override val swipeConversationIntent by lazy { itemTouchCallback.swipes }
override val undoSwipeConversationIntent: Subject<Unit> = PublishSubject.create()
private val itemTouchHelper by lazy { ItemTouchHelper(itemTouchCallback) }
private val archiveSnackbar by lazy {
Snackbar.make(drawerLayout, R.string.toast_archived, Snackbar.LENGTH_INDEFINITE).apply {
setAction(R.string.button_undo, { undoSwipeConversationIntent.onNext(Unit) })
}
}
private var conversationMenuDialog: AlertDialog? = null
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
viewModel.bindView(this)
toolbarSearch.setHint(R.string.title_conversations)
val toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, 0, 0).apply { syncState() }
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager = LinearLayoutManager(this)
// Don't allow clicks to pass through the drawer layout
drawer.clicks().subscribe()
scheduled.isEnabled = false
colors.background
.doOnNext { color -> window.decorView.setBackgroundColor(color) }
.doOnNext { color -> drawer.setBackgroundColor(color) }
.autoDisposable(scope())
.subscribe()
val states = arrayOf(
intArrayOf(android.R.attr.state_selected),
intArrayOf(-android.R.attr.state_selected))
val rowBackground = { separator: Int ->
StateListDrawable().apply {
addState(intArrayOf(android.R.attr.state_selected), ColorDrawable(separator))
addState(intArrayOf(-android.R.attr.state_selected), getDrawable(R.drawable.ripple))
mutate()
}
}
// Set the theme color tint to the progressbar and FAB
colors.theme
.doOnNext { color -> syncingProgress.indeterminateTintList = ColorStateList.valueOf(color) }
.doOnNext { color -> compose.setBackgroundTint(color) }
.autoDisposable(scope())
.subscribe()
// Set the hamburger icon color
colors.textSecondary
.autoDisposable(scope())
.subscribe { color -> toggle.drawerArrowDrawable.color = color }
// Set the color for the drawer icons
Observables
.combineLatest(colors.theme, colors.textSecondary, { theme, textSecondary ->
ColorStateList(states, intArrayOf(theme, textSecondary))
})
.doOnNext { tintList -> inboxIcon.imageTintList = tintList }
.doOnNext { tintList -> archivedIcon.imageTintList = tintList }
.doOnNext { tintList -> scheduledIcon.imageTintList = tintList }
.doOnNext { tintList -> settingsIcon.imageTintList = tintList }
.doOnNext { tintList -> plusIcon.imageTintList = tintList }
.doOnNext { tintList -> helpIcon.imageTintList = tintList }
.autoDisposable(scope())
.subscribe()
// Set the background highlight for the drawer options
colors.separator
.doOnNext { color -> inbox.background = rowBackground(color) }
.doOnNext { color -> archived.background = rowBackground(color) }
.doOnNext { color -> scheduled.background = rowBackground(color) }
.autoDisposable(scope())
.subscribe()
conversationsAdapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
// If we're at the top, scroll up to show new conversations
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
val firstVisiblePosition = layoutManager.findFirstCompletelyVisibleItemPosition()
if (firstVisiblePosition == 0) {
recyclerView.scrollToPosition(positionStart)
}
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
onItemRangeInserted(positionStart, itemCount)
}
})
}
override fun render(state: MainState) {
toolbarSearch.isEnabled = state.page is Inbox
toolbarSearch.textSize = if (state.page is Inbox) 16f else 20f
toolbar.menu.findItem(R.id.clear)?.run {
isVisible = state.page is Inbox && state.page.showClearButton
}
syncing.setVisible(state.syncing)
recyclerView.setVisible(!state.syncing)
when (state.page) {
is Inbox -> {
if (!inbox.isSelected) toolbarSearch.text = null
if (recyclerView.adapter !== conversationsAdapter) recyclerView.adapter = conversationsAdapter
conversationsAdapter.flowable = state.page.data
itemTouchHelper.attachToRecyclerView(recyclerView)
menuItemAdapter.data = state.page.menu
empty.setText(R.string.inbox_empty_text)
empty.setVisible(state.page.empty && !state.syncing)
compose.setVisible(true)
}
is Archived -> {
if (!archived.isSelected) toolbarSearch.setText(R.string.title_archived)
if (recyclerView.adapter !== conversationsAdapter) recyclerView.adapter = conversationsAdapter
conversationsAdapter.flowable = state.page.data
itemTouchHelper.attachToRecyclerView(null)
menuItemAdapter.data = state.page.menu
empty.setText(R.string.archived_empty_text)
empty.setVisible(state.page.empty && !state.syncing)
compose.setVisible(true)
}
is Scheduled -> {
if (!scheduled.isSelected) toolbarSearch.setText(R.string.title_scheduled)
recyclerView.adapter = null
itemTouchHelper.attachToRecyclerView(null)
menuItemAdapter.data = ArrayList()
empty.setText(R.string.scheduled_empty_text)
empty.setVisible(state.page.empty && !state.syncing)
compose.setVisible(false)
}
}
when (state.page is Inbox && state.page.showArchivedSnackbar) {
true -> archiveSnackbar.show()
false -> archiveSnackbar.dismiss()
}
inbox.isSelected = state.page is Inbox
inboxIcon.isSelected = state.page is Inbox
archived.isSelected = state.page is Archived
archivedIcon.isSelected = state.page is Archived
scheduled.isSelected = state.page is Scheduled
scheduledIcon.isSelected = state.page is Scheduled
if (drawerLayout.isDrawerOpen(Gravity.START) && !state.drawerOpen) drawerLayout.closeDrawer(Gravity.START)
else if (!drawerLayout.isDrawerVisible(Gravity.START) && state.drawerOpen) drawerLayout.openDrawer(Gravity.START)
if (conversationMenuDialog?.isShowing == true && menuItemAdapter.data.isEmpty()) {
conversationMenuDialog?.dismiss()
conversationMenuDialog = null
} else if (conversationMenuDialog?.isShowing != true && menuItemAdapter.data.isNotEmpty()) {
val recyclerView = RecyclerView(this)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = menuItemAdapter
recyclerView.setPadding(0, 8.dpToPx(this), 0, 8.dpToPx(this))
conversationMenuDialog = AlertDialog.Builder(this).setView(recyclerView).create().apply {
setOnDismissListener { conversationMenuItemIntent.onNext(-1) }
show()
}
}
}
override fun clearSearch() {
toolbarSearch.text = null
}
override fun showDeleteDialog() {
AlertDialog.Builder(this)
.setTitle(R.string.dialog_delete_title)
.setMessage(R.string.dialog_delete_message)
.setPositiveButton(R.string.button_delete, { _, _ -> confirmDeleteIntent.onNext(Unit) })
.setNegativeButton(R.string.button_cancel, null)
.show()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.clear -> queryCancelledIntent.onNext(Unit)
else -> return super.onOptionsItemSelected(item)
}
return true
}
}
@@ -0,0 +1,48 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.main
import io.reactivex.Flowable
import model.Conversation
import model.Message
import presentation.common.MenuItem
data class MainState(
val page: MainPage = Inbox(),
val drawerOpen: Boolean = false,
val syncing: Boolean = false
)
sealed class MainPage
data class Inbox(
val showClearButton: Boolean = false,
val data: Flowable<List<Pair<Conversation, Message>>>? = null,
val empty: Boolean = false,
val menu: List<MenuItem> = ArrayList(),
val showArchivedSnackbar: Boolean = false) : MainPage()
data class Archived(
val data: Flowable<List<Pair<Conversation, Message>>>?,
val empty: Boolean = false,
val menu: List<MenuItem> = ArrayList()) : MainPage()
data class Scheduled(
val data: Any? = null,
val empty: Boolean = false) : MainPage()
@@ -0,0 +1,43 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.main
import io.reactivex.Observable
import presentation.common.base.QkView
interface MainView : QkView<MainState> {
val queryChangedIntent: Observable<CharSequence>
val queryCancelledIntent: Observable<*>
val composeIntent: Observable<Unit>
val drawerOpenIntent: Observable<Boolean>
val drawerItemIntent: Observable<DrawerItem>
val conversationClickIntent: Observable<Long>
val conversationLongClickIntent: Observable<Long>
val conversationMenuItemIntent: Observable<Int>
val confirmDeleteIntent: Observable<Unit>
val swipeConversationIntent: Observable<Int>
val undoSwipeConversationIntent: Observable<Unit>
fun clearSearch()
fun showDeleteDialog()
}
enum class DrawerItem { INBOX, ARCHIVED, SCHEDULED, BLOCKED, SETTINGS, PLUS, HELP }
@@ -0,0 +1,264 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.main
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.provider.Telephony
import android.support.v4.content.ContextCompat
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import common.util.filter.ConversationFilter
import interactor.DeleteConversation
import interactor.MarkAllSeen
import interactor.MarkArchived
import interactor.MarkUnarchived
import interactor.MigratePreferences
import interactor.PartialSync
import io.reactivex.Observable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.withLatestFrom
import io.realm.Realm
import model.SyncLog
import presentation.common.MenuItem
import presentation.common.Navigator
import presentation.common.base.QkViewModel
import repository.MessageRepository
import util.Preferences
import util.extensions.toFlowable
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class MainViewModel : QkViewModel<MainView, MainState>(MainState()) {
@Inject lateinit var context: Context
@Inject lateinit var navigator: Navigator
@Inject lateinit var conversationFilter: ConversationFilter
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var markAllSeen: MarkAllSeen
@Inject lateinit var deleteConversation: DeleteConversation
@Inject lateinit var markArchived: MarkArchived
@Inject lateinit var markUnarchived: MarkUnarchived
@Inject lateinit var migratePreferences: MigratePreferences
@Inject lateinit var partialSync: PartialSync
@Inject lateinit var prefs: Preferences
private val conversations by lazy {
messageRepo.getConversations()
.withLatestFrom(state.toFlowable(), { conversations, state ->
(state.page as? Inbox)?.let { page ->
newState { it.copy(page = page.copy(empty = conversations.isEmpty())) }
}
conversations
})
}
private val archivedConversations by lazy {
messageRepo.getConversations(true)
.withLatestFrom(state.toFlowable(), { conversations, state ->
(state.page as? Archived)?.let { page ->
newState { it.copy(page = page.copy(empty = conversations.isEmpty())) }
}
conversations
})
}
private val menuArchive by lazy { MenuItem(context.getString(R.string.menu_archive), 0) }
private val menuUnarchive by lazy { MenuItem(context.getString(R.string.menu_unarchive), 1) }
private val menuDelete by lazy { MenuItem(context.getString(R.string.menu_delete), 2) }
init {
appComponent.inject(this)
disposables += deleteConversation
disposables += markAllSeen
disposables += markArchived
disposables += markUnarchived
disposables += migratePreferences
disposables += partialSync
// If it's the first sync, reflect that in the ViewState
disposables += Realm.getDefaultInstance()
.where(SyncLog::class.java)
.findAll()
.asFlowable()
.filter { it.isLoaded }
.map { it.size == 0 }
.doOnNext { if (it) partialSync.execute(Unit) }
.distinctUntilChanged()
.subscribe { syncing -> newState { it.copy(syncing = syncing) } }
newState { it.copy(page = Inbox(data = conversations)) }
// Migrate the preferences from 2.7.3 if necessary
migratePreferences.execute(Unit)
val isNotDefaultSms = Telephony.Sms.getDefaultSmsPackage(context) != context.packageName
val hasSmsPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED
val hasContactPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
if (isNotDefaultSms) {
partialSync.execute(Unit)
}
if (isNotDefaultSms || !hasSmsPermission || !hasContactPermission) {
navigator.showSetupActivity()
}
markAllSeen.execute(Unit)
}
override fun bindView(view: MainView) {
super.bindView(view)
view.queryChangedIntent
.skip(1)
.debounce(200, TimeUnit.MILLISECONDS)
.withLatestFrom(state, { query, state ->
if (state.page is Inbox) {
val conversations = when {
query.isEmpty() -> conversations
else -> conversations.map { list -> list.filter { conversationFilter.filter(it.first, query) } }
}
val page = state.page.copy(showClearButton = query.isNotEmpty(), data = conversations)
newState { it.copy(page = page) }
}
})
.autoDisposable(view.scope())
.subscribe()
view.queryCancelledIntent
.autoDisposable(view.scope())
.subscribe { view.clearSearch() }
view.composeIntent
.autoDisposable(view.scope())
.subscribe { navigator.showCompose() }
view.drawerOpenIntent
.autoDisposable(view.scope())
.subscribe { open -> newState { it.copy(drawerOpen = open) } }
view.drawerItemIntent
.doOnNext { newState { it.copy(drawerOpen = false) } }
.doOnNext { if (it == DrawerItem.SETTINGS) navigator.showSettings() }
.doOnNext { if (it == DrawerItem.PLUS) navigator.showQksmsPlusActivity() }
.doOnNext { if (it == DrawerItem.HELP) navigator.showSupport() }
.distinctUntilChanged()
.doOnNext {
when (it) {
DrawerItem.INBOX -> newState { it.copy(page = Inbox(data = conversations)) }
DrawerItem.ARCHIVED -> newState { it.copy(page = Archived(archivedConversations)) }
DrawerItem.SCHEDULED -> newState { it.copy(page = Scheduled()) }
else -> {
} // Do nothing
}
}
.autoDisposable(view.scope())
.subscribe()
view.conversationClickIntent
.doOnNext { view.clearSearch() }
.doOnNext { threadId -> navigator.showConversation(threadId) }
.autoDisposable(view.scope())
.subscribe()
view.conversationLongClickIntent
.withLatestFrom(state, { _, mainState ->
when (mainState.page) {
is Inbox -> {
val page = mainState.page.copy(menu = listOf(menuArchive, menuDelete))
newState { it.copy(page = page) }
}
is Archived -> {
val page = mainState.page.copy(menu = listOf(menuUnarchive, menuDelete))
newState { it.copy(page = page) }
}
}
})
.autoDisposable(view.scope())
.subscribe()
view.conversationMenuItemIntent
.withLatestFrom(state, { actionId, mainState ->
when (mainState.page) {
is Inbox -> {
val page = mainState.page.copy(menu = ArrayList())
newState { it.copy(page = page) }
}
is Archived -> {
val page = mainState.page.copy(menu = ArrayList())
newState { it.copy(page = page) }
}
}
actionId
})
.withLatestFrom(view.conversationLongClickIntent, { actionId, threadId ->
when (actionId) {
menuArchive.actionId -> markArchived.execute(threadId)
menuUnarchive.actionId -> markUnarchived.execute(threadId)
menuDelete.actionId -> view.showDeleteDialog()
}
})
.autoDisposable(view.scope())
.subscribe()
// Delete the conversation
view.confirmDeleteIntent
.withLatestFrom(view.conversationLongClickIntent, { _, threadId -> threadId })
.autoDisposable(view.scope())
.subscribe { threadId -> deleteConversation.execute(threadId) }
val swipedConversation = view.swipeConversationIntent
.withLatestFrom(conversations.toObservable(), { position, conversations -> conversations[position] })
.map { pair -> pair.first }
.map { conversation -> conversation.id }
swipedConversation
.withLatestFrom(state, { threadId, state ->
markArchived.execute(threadId) {
if (state.page is Inbox) {
val page = state.page.copy(showArchivedSnackbar = true)
newState { it.copy(page = page) }
}
}
})
.switchMap { Observable.timer(2750, TimeUnit.MILLISECONDS) }
.withLatestFrom(state, { threadId, state ->
markArchived.execute(threadId) {
if (state.page is Inbox) {
val page = state.page.copy(showArchivedSnackbar = false)
newState { it.copy(page = page) }
}
}
})
.autoDisposable(view.scope())
.subscribe()
view.undoSwipeConversationIntent
.withLatestFrom(swipedConversation, { _, threadId -> threadId })
.autoDisposable(view.scope())
.subscribe { threadId -> markUnarchived.execute(threadId) }
}
}
@@ -0,0 +1,105 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.notificationprefs
import android.app.Activity
import android.content.Intent
import android.media.RingtoneManager
import android.net.Uri
import android.os.Bundle
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.notification_prefs_activity.*
import kotlinx.android.synthetic.main.settings_switch_widget.view.*
import presentation.common.MenuItemAdapter
import presentation.common.base.QkThemedActivity
import presentation.common.widget.PreferenceView
import javax.inject.Inject
class NotificationPrefsActivity : QkThemedActivity<NotificationPrefsViewModel>(), NotificationPrefsView {
@Inject lateinit var nightModeAdapter: MenuItemAdapter
@Inject lateinit var mmsSizeAdapter: MenuItemAdapter
override val viewModelClass = NotificationPrefsViewModel::class
override val preferenceClickIntent: Subject<PreferenceView> = PublishSubject.create()
override val ringtoneSelectedIntent: Subject<String> = PublishSubject.create()
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.notification_prefs_activity)
setTitle(R.string.title_notification_prefs)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
nightModeAdapter.setData(R.array.night_modes)
mmsSizeAdapter.setData(R.array.mms_sizes, R.array.mms_sizes_ids)
colors.background
.autoDisposable(scope())
.subscribe { color -> window.decorView.setBackgroundColor(color) }
// Listen to clicks for all of the preferences
(0 until preferences.childCount)
.map { index -> preferences.getChildAt(index) }
.filter { view -> view is PreferenceView }
.forEach { preference ->
preference.clicks().subscribe {
preferenceClickIntent.onNext(preference as PreferenceView)
}
}
}
override fun render(state: NotificationPrefsState) {
if (state.conversationTitle.isNotEmpty()) {
title = state.conversationTitle
}
notifications.checkbox.isChecked = state.notificationsEnabled
vibration.checkbox.isChecked = state.vibrationEnabled
ringtone.summary = state.ringtoneName
}
override fun showRingtonePicker(default: Uri) {
val intent = Intent(RingtoneManager.ACTION_RINGTONE_PICKER)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, default)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION)
startActivityForResult(intent, 123)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 123 && resultCode == Activity.RESULT_OK) {
val uri: Uri? = data?.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI)
uri?.let { ringtoneSelectedIntent.onNext(uri.toString()) }
}
}
}
@@ -0,0 +1,26 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.notificationprefs
data class NotificationPrefsState(
val conversationTitle: String = "",
val notificationsEnabled: Boolean = true,
val vibrationEnabled: Boolean = true,
val ringtoneName: String = ""
)
@@ -0,0 +1,33 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.notificationprefs
import android.net.Uri
import io.reactivex.Observable
import io.reactivex.subjects.Subject
import presentation.common.base.QkView
import presentation.common.widget.PreferenceView
interface NotificationPrefsView : QkView<NotificationPrefsState> {
val preferenceClickIntent: Subject<PreferenceView>
val ringtoneSelectedIntent: Observable<String>
fun showRingtonePicker(default: Uri)
}
@@ -0,0 +1,101 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.notificationprefs
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.net.Uri
import androidx.net.toUri
import com.f2prateek.rx.preferences2.Preference
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import util.Preferences
import io.reactivex.Flowable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.schedulers.Schedulers
import presentation.common.Navigator
import presentation.common.base.QkViewModel
import repository.MessageRepository
import timber.log.Timber
import util.extensions.mapNotNull
import javax.inject.Inject
class NotificationPrefsViewModel(intent: Intent) : QkViewModel<NotificationPrefsView, NotificationPrefsState>(NotificationPrefsState()) {
@Inject lateinit var context: Context
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var navigator: Navigator
@Inject lateinit var prefs: Preferences
private val threadId = intent.extras?.getLong("threadId") ?: 0L
private val notifications: Preference<Boolean>
private val vibration: Preference<Boolean>
private val ringtone: Preference<String>
init {
appComponent.inject(this)
notifications = prefs.notifications(threadId)
vibration = prefs.vibration(threadId)
ringtone = prefs.ringtone(threadId)
disposables += Flowable.just(threadId)
.mapNotNull { threadId -> messageRepo.getConversation(threadId) }
.map { conversation -> conversation.getTitle() }
.subscribeOn(Schedulers.io())
.subscribe { title -> newState { it.copy(conversationTitle = title) } }
disposables += notifications.asObservable()
.subscribe { enabled -> newState { it.copy(notificationsEnabled = enabled) } }
disposables += vibration.asObservable()
.subscribe { enabled -> newState { it.copy(vibrationEnabled = enabled) } }
disposables += ringtone.asObservable()
.map { uri -> uri.toUri() }
.map { uri -> RingtoneManager.getRingtone(context, uri).getTitle(context) }
.subscribe { title -> newState { it.copy(ringtoneName = title) } }
}
override fun bindView(view: NotificationPrefsView) {
super.bindView(view)
view.preferenceClickIntent
.autoDisposable(view.scope())
.subscribe {
Timber.v("Preference click: ${context.resources.getResourceName(it.id)}")
when (it.id) {
R.id.notifications -> notifications.set(!notifications.get())
R.id.vibration -> vibration.set(!vibration.get())
R.id.ringtone -> view.showRingtonePicker(Uri.parse(ringtone.get()))
}
}
view.ringtoneSelectedIntent
.autoDisposable(view.scope())
.subscribe { ringtone -> this.ringtone.set(ringtone) }
}
}
@@ -0,0 +1,99 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.plus
import android.graphics.Typeface
import android.os.Bundle
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import common.util.BillingManager
import common.util.FontProvider
import common.util.extensions.setBackgroundTint
import common.util.extensions.setTint
import common.util.extensions.setVisible
import kotlinx.android.synthetic.main.qksms_plus_activity.*
import presentation.common.base.QkThemedActivity
import javax.inject.Inject
class PlusActivity : QkThemedActivity<PlusViewModel>(), PlusView {
@Inject lateinit var fontProvider: FontProvider
override val viewModelClass = PlusViewModel::class
override val upgradeIntent by lazy { upgrade.clicks() }
override val upgradeDonateIntent by lazy { upgradeDonate.clicks() }
override fun onCreate(savedInstanceState: Bundle?) {
appComponent.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.qksms_plus_activity)
setTitle(R.string.title_qksms_plus)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
fontProvider.getLato {
val typeface = Typeface.create(it, Typeface.BOLD)
collapsingToolbar.setCollapsedTitleTypeface(typeface)
collapsingToolbar.setExpandedTitleTypeface(typeface)
}
colors.textPrimary
.autoDisposable(scope())
.subscribe { color ->
collapsingToolbar.setCollapsedTitleTextColor(color)
collapsingToolbar.setExpandedTitleColor(color)
}
colors.background
.autoDisposable(scope())
.subscribe { color -> window.decorView.setBackgroundColor(color) }
colors.separator
.autoDisposable(scope())
.subscribe { color ->
upgradeDonate.setBackgroundTint(color)
thanks.setBackgroundTint(color)
}
colors.theme
.autoDisposable(scope())
.subscribe { color ->
upgrade.setBackgroundTint(color)
thanksIcon.setTint(color)
}
}
override fun render(state: PlusState) {
description.text = getString(R.string.qksms_plus_description_summary, state.upgradePrice)
upgrade.text = getString(R.string.qksms_plus_upgrade, state.upgradePrice, state.currency)
upgradeDonate.text = getString(R.string.qksms_plus_upgrade_donate, state.upgradeDonatePrice, state.currency)
upgrade.setVisible(state.currentPlan == BillingManager.UpgradeStatus.REGULAR)
upgradeDonate.setVisible(state.currentPlan == BillingManager.UpgradeStatus.REGULAR)
thanks.setVisible(state.currentPlan != BillingManager.UpgradeStatus.REGULAR)
}
override fun initiatePurchaseFlow(billingManager: BillingManager, sku: String) {
billingManager.initiatePurchaseFlow(this, sku)
}
}
@@ -0,0 +1,28 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.plus
import common.util.BillingManager
data class PlusState(
val currentPlan: BillingManager.UpgradeStatus = BillingManager.UpgradeStatus.REGULAR,
val upgradePrice: String = "",
val upgradeDonatePrice: String = "",
val currency: String = ""
)
@@ -0,0 +1,32 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.plus
import common.util.BillingManager
import io.reactivex.Observable
import presentation.common.base.QkView
interface PlusView : QkView<PlusState> {
val upgradeIntent: Observable<Unit>
val upgradeDonateIntent: Observable<Unit>
fun initiatePurchaseFlow(billingManager: BillingManager, sku: String)
}
@@ -0,0 +1,63 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.plus
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import common.util.BillingManager
import io.reactivex.Observable
import io.reactivex.rxkotlin.plusAssign
import presentation.common.base.QkViewModel
import javax.inject.Inject
class PlusViewModel : QkViewModel<PlusView, PlusState>(PlusState()) {
@Inject lateinit var billingManager: BillingManager
init {
appComponent.inject(this)
disposables += billingManager.plusStatus
.subscribe { plan ->
newState { it.copy(currentPlan = plan) }
}
disposables += billingManager.products
.subscribe { products ->
newState {
val upgrade = products.firstOrNull { it.sku == BillingManager.SKU_PLUS }
val upgradeDonate = products.firstOrNull { it.sku == BillingManager.SKU_PLUS_DONATE }
it.copy(upgradePrice = upgrade?.price ?: "", upgradeDonatePrice = upgradeDonate?.price ?: "",
currency = upgrade?.priceCurrencyCode ?: upgradeDonate?.priceCurrencyCode ?: "")
}
}
}
override fun bindView(view: PlusView) {
super.bindView(view)
Observable.merge(
view.upgradeIntent.map { BillingManager.SKU_PLUS },
view.upgradeDonateIntent.map { BillingManager.SKU_PLUS_DONATE })
.autoDisposable(view.scope())
.subscribe { sku -> view.initiatePurchaseFlow(billingManager, sku) }
}
}
@@ -0,0 +1,176 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.settings
import android.app.AlertDialog
import android.app.ProgressDialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import util.Preferences
import common.util.extensions.dpToPx
import common.util.extensions.setVisible
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.settings_activity.*
import kotlinx.android.synthetic.main.settings_switch_widget.view.*
import presentation.common.MenuItemAdapter
import presentation.common.base.QkThemedActivity
import presentation.common.widget.PreferenceView
import javax.inject.Inject
class SettingsActivity : QkThemedActivity<SettingsViewModel>(), SettingsView {
@Inject lateinit var nightModeAdapter: MenuItemAdapter
@Inject lateinit var mmsSizeAdapter: MenuItemAdapter
override val viewModelClass = SettingsViewModel::class
override val preferenceClickIntent: Subject<PreferenceView> = PublishSubject.create()
override val nightModeSelectedIntent by lazy { nightModeAdapter.menuItemClicks }
override val viewQksmsPlusIntent: Subject<Unit> = PublishSubject.create()
override val startTimeSelectedIntent: Subject<Pair<Int, Int>> = PublishSubject.create()
override val endTimeSelectedIntent: Subject<Pair<Int, Int>> = PublishSubject.create()
override val mmsSizeSelectedIntent: Subject<Int> by lazy { mmsSizeAdapter.menuItemClicks }
// TODO remove this
private val progressDialog by lazy {
ProgressDialog(this).apply {
isIndeterminate = true
setCancelable(false)
setCanceledOnTouchOutside(false)
}
}
private var nightModeDialog: AlertDialog? = null
private var mmsSizeDialog: AlertDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
appComponent.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.settings_activity)
setTitle(R.string.title_settings)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
nightModeAdapter.setData(R.array.night_modes)
mmsSizeAdapter.setData(R.array.mms_sizes, R.array.mms_sizes_ids)
colors.background
.autoDisposable(scope())
.subscribe { color -> window.decorView.setBackgroundColor(color) }
// Listen to clicks for all of the preferences
(0 until preferences.childCount)
.map { index -> preferences.getChildAt(index) }
.filter { view -> view is PreferenceView }
.forEach { preference ->
preference.clicks().subscribe {
preferenceClickIntent.onNext(preference as PreferenceView)
}
}
}
override fun render(state: SettingsState) {
if (progressDialog.isShowing && !state.syncing) progressDialog.dismiss()
else if (!progressDialog.isShowing && state.syncing) progressDialog.show()
defaultSms.summary = getString(when (state.isDefaultSmsApp) {
true -> R.string.settings_default_sms_summary_true
else -> R.string.settings_default_sms_summary_false
})
night.summary = state.nightModeSummary
nightStart.setVisible(state.nightModeId == Preferences.NIGHT_MODE_AUTO)
nightStart.summary = state.nightStart
nightEnd.setVisible(state.nightModeId == Preferences.NIGHT_MODE_AUTO)
nightEnd.summary = state.nightEnd
black.setVisible(state.nightModeId != Preferences.NIGHT_MODE_OFF)
black.checkbox.isChecked = state.black
autoEmoji.checkbox.isChecked = state.autoEmojiEnabled
delivery.checkbox.isChecked = state.deliveryEnabled
unicode.checkbox.isChecked = state.stripUnicodeEnabled
mms.checkbox.isChecked = state.mmsEnabled
mmsSize.summary = state.maxMmsSizeSummary
mmsSizeAdapter.selectedItem = state.maxMmsSizeId
}
// TODO change this to a PopupWindow
override fun showNightModeDialog() {
val recyclerView = RecyclerView(this)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = nightModeAdapter
recyclerView.setPadding(0, 8.dpToPx(this), 0, 8.dpToPx(this))
nightModeDialog = AlertDialog.Builder(this)
.setTitle(R.string.settings_night_title)
.setView(recyclerView)
.create().apply { show() }
}
override fun dismissNightModeDialog() {
nightModeDialog?.dismiss()
nightModeDialog = null
}
override fun showQksmsPlusSnackbar() {
Snackbar.make(contentView, R.string.toast_qksms_plus, Snackbar.LENGTH_LONG).run {
setAction(R.string.button_more, { viewQksmsPlusIntent.onNext(Unit) })
show()
}
}
override fun showStartTimePicker(hour: Int, minute: Int) {
TimePickerDialog(this, TimePickerDialog.OnTimeSetListener { _, newHour, newMinute ->
startTimeSelectedIntent.onNext(Pair(newHour, newMinute))
}, hour, minute, false).show()
}
override fun showEndTimePicker(hour: Int, minute: Int) {
TimePickerDialog(this, TimePickerDialog.OnTimeSetListener { _, newHour, newMinute ->
endTimeSelectedIntent.onNext(Pair(newHour, newMinute))
}, hour, minute, false).show()
}
override fun showMmsSizePicker() {
val recyclerView = RecyclerView(this)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = mmsSizeAdapter
recyclerView.setPadding(0, 8.dpToPx(this), 0, 8.dpToPx(this))
mmsSizeDialog = AlertDialog.Builder(this)
.setTitle(R.string.settings_mms_size_title)
.setNegativeButton(R.string.button_cancel, null)
.setView(recyclerView)
.create().apply { show() }
}
override fun dismissMmsSizePicker() {
mmsSizeDialog?.dismiss()
mmsSizeDialog = null
}
}
@@ -0,0 +1,40 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.settings
import util.Preferences
data class SettingsState(
val syncing: Boolean = false,
val isDefaultSmsApp: Boolean = false,
val nightModeSummary: String = "",
val nightModeId: Int = Preferences.NIGHT_MODE_OFF,
val nightStart: String = "",
val nightEnd: String = "",
val black: Boolean = false,
val autoEmojiEnabled: Boolean = true,
val notificationsEnabled: Boolean = true,
val deliveryEnabled: Boolean = false,
val splitSmsEnabled: Boolean = false,
val stripUnicodeEnabled: Boolean = false,
val mmsEnabled: Boolean = true,
val maxMmsSizeSummary: String = "100KB",
val maxMmsSizeId: Int = 100
)
@@ -0,0 +1,42 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.settings
import io.reactivex.Observable
import io.reactivex.subjects.Subject
import presentation.common.base.QkView
import presentation.common.widget.PreferenceView
interface SettingsView : QkView<SettingsState> {
val preferenceClickIntent: Subject<PreferenceView>
val nightModeSelectedIntent: Observable<Int>
val viewQksmsPlusIntent: Subject<Unit>
val startTimeSelectedIntent: Subject<Pair<Int, Int>>
val endTimeSelectedIntent: Subject<Pair<Int, Int>>
val mmsSizeSelectedIntent: Observable<Int>
fun showNightModeDialog()
fun dismissNightModeDialog()
fun showQksmsPlusSnackbar()
fun showStartTimePicker(hour: Int, minute: Int)
fun showEndTimePicker(hour: Int, minute: Int)
fun showMmsSizePicker()
fun dismissMmsSizePicker()
}
@@ -0,0 +1,182 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.settings
import android.content.Context
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import common.util.BillingManager
import common.util.DateFormatter
import common.util.NightModeManager
import util.Preferences
import interactor.FullSync
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.withLatestFrom
import presentation.common.Navigator
import presentation.common.base.QkViewModel
import timber.log.Timber
import java.util.*
import javax.inject.Inject
class SettingsViewModel : QkViewModel<SettingsView, SettingsState>(SettingsState()) {
@Inject lateinit var context: Context
@Inject lateinit var billingManager: BillingManager
@Inject lateinit var dateFormatter: DateFormatter
@Inject lateinit var navigator: Navigator
@Inject lateinit var nightModeManager: NightModeManager
@Inject lateinit var prefs: Preferences
@Inject lateinit var fullSync: FullSync
init {
appComponent.inject(this)
disposables += prefs.defaultSms
.asObservable()
.subscribe { isDefaultSmsApp ->
newState { it.copy(isDefaultSmsApp = isDefaultSmsApp) }
}
val nightModeLabels = context.resources.getStringArray(R.array.night_modes)
disposables += prefs.nightMode.asObservable()
.subscribe { nightMode ->
newState { it.copy(nightModeSummary = nightModeLabels[nightMode], nightModeId = nightMode) }
}
disposables += prefs.nightStart.asObservable()
.subscribe { nightStart -> newState { it.copy(nightStart = nightStart) } }
disposables += prefs.nightEnd.asObservable()
.subscribe { nightEnd -> newState { it.copy(nightEnd = nightEnd) } }
disposables += prefs.black.asObservable()
.subscribe { black -> newState { it.copy(black = black) } }
disposables += prefs.autoEmoji.asObservable()
.subscribe { enabled -> newState { it.copy(autoEmojiEnabled = enabled) } }
disposables += prefs.notifications().asObservable()
.subscribe { enabled -> newState { it.copy(notificationsEnabled = enabled) } }
disposables += prefs.delivery.asObservable()
.subscribe { enabled -> newState { it.copy(deliveryEnabled = enabled) } }
disposables += prefs.unicode.asObservable()
.subscribe { enabled -> newState { it.copy(stripUnicodeEnabled = enabled) } }
disposables += prefs.mms.asObservable()
.subscribe { enabled -> newState { it.copy(mmsEnabled = enabled) } }
val mmsSizeLabels = context.resources.getStringArray(R.array.mms_sizes)
val mmsSizeIds = context.resources.getIntArray(R.array.mms_sizes_ids)
disposables += prefs.mmsSize.asObservable()
.subscribe { maxMmsSize ->
val index = mmsSizeIds.indexOf(maxMmsSize)
newState { it.copy(maxMmsSizeSummary = mmsSizeLabels[index], maxMmsSizeId = maxMmsSize) }
}
disposables += fullSync
}
override fun bindView(view: SettingsView) {
super.bindView(view)
view.preferenceClickIntent
.autoDisposable(view.scope())
.subscribe {
Timber.v("Preference click: ${context.resources.getResourceName(it.id)}")
when (it.id) {
R.id.defaultSms -> navigator.showDefaultSmsDialog()
R.id.theme -> navigator.showThemePicker()
R.id.night -> view.showNightModeDialog()
R.id.nightStart -> {
val date = dateFormatter.parseTime(prefs.nightStart.get())
view.showStartTimePicker(date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE))
}
R.id.nightEnd -> {
val date = dateFormatter.parseTime(prefs.nightEnd.get())
view.showEndTimePicker(date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE))
}
R.id.black -> prefs.black.set(!prefs.black.get())
R.id.autoEmoji -> prefs.autoEmoji.set(!prefs.autoEmoji.get())
R.id.notifications -> navigator.showNotificationSettings()
R.id.blocked -> navigator.showBlockedConversations()
R.id.delivery -> prefs.delivery.set(!prefs.delivery.get())
R.id.unicode -> prefs.unicode.set(!prefs.unicode.get())
R.id.mms -> prefs.mms.set(!prefs.mms.get())
R.id.mmsSize -> view.showMmsSizePicker()
R.id.sync -> {
newState { it.copy(syncing = true) }
fullSync.execute(Unit, {
newState { it.copy(syncing = false) }
})
}
}
}
view.nightModeSelectedIntent
.doOnNext { view.dismissNightModeDialog() }
.withLatestFrom(billingManager.plusStatus, { mode, plusStatus ->
if (plusStatus == BillingManager.UpgradeStatus.REGULAR && mode == Preferences.NIGHT_MODE_AUTO) {
view.showQksmsPlusSnackbar()
} else {
nightModeManager.updateNightMode(mode)
}
})
.autoDisposable(view.scope())
.subscribe()
view.viewQksmsPlusIntent
.autoDisposable(view.scope())
.subscribe { navigator.showQksmsPlusActivity() }
view.startTimeSelectedIntent
.doOnNext { nightModeManager.updateAlarms() }
.map { dateFormatter.formatTime(it.first, it.second) }
.autoDisposable(view.scope())
.subscribe { prefs.nightStart.set(it) }
view.endTimeSelectedIntent
.doOnNext { nightModeManager.updateAlarms() }
.map { dateFormatter.formatTime(it.first, it.second) }
.autoDisposable(view.scope())
.subscribe { prefs.nightEnd.set(it) }
view.mmsSizeSelectedIntent
.doOnNext { view.dismissMmsSizePicker() }
.autoDisposable(view.scope())
.subscribe { prefs.mmsSize.set(it) }
}
}
@@ -0,0 +1,75 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.setup
import android.Manifest
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.setup_activity.*
import presentation.common.Navigator
import presentation.common.base.QkThemedActivity
import javax.inject.Inject
class SetupActivity : QkThemedActivity<SetupViewModel>(), SetupView {
override val viewModelClass = SetupViewModel::class
override val activityResumedIntent: Subject<Unit> = PublishSubject.create()
override val skipIntent by lazy { skip.clicks() }
override val nextIntent by lazy { next.clicks() }
@Inject lateinit var navigator: Navigator
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.setup_activity)
viewModel.bindView(this)
colors.background
.autoDisposable(scope())
.subscribe { color -> window.decorView.setBackgroundColor(color) }
}
override fun onResume() {
super.onResume()
activityResumedIntent.onNext(Unit)
}
override fun render(state: SetupState) {
}
override fun requestDefaultSms() {
navigator.showDefaultSmsDialog()
}
override fun requestPermissions() {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CONTACTS, Manifest.permission.READ_SMS), 0)
}
}
@@ -0,0 +1,21 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.setup
class SetupState
@@ -0,0 +1,34 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.setup
import io.reactivex.Observable
import presentation.common.base.QkView
interface SetupView : QkView<SetupState> {
val activityResumedIntent: Observable<*>
val skipIntent: Observable<*>
val nextIntent: Observable<*>
fun requestDefaultSms()
fun requestPermissions()
fun finish()
}
@@ -0,0 +1,60 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.setup
import android.content.Context
import android.provider.Telephony
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import manager.PermissionManager
import presentation.common.base.QkViewModel
import javax.inject.Inject
class SetupViewModel : QkViewModel<SetupView, SetupState>(SetupState()) {
@Inject lateinit var context: Context
@Inject lateinit var permissions: PermissionManager
init {
appComponent.inject(this)
}
override fun bindView(view: SetupView) {
super.bindView(view)
view.activityResumedIntent
.autoDisposable(view.scope())
.subscribe {
val isDefault = Telephony.Sms.getDefaultSmsPackage(context) == context.packageName
if (!permissions.hasSmsAndContacts()) view.requestPermissions()
else if (isDefault) view.finish()
}
view.skipIntent
.autoDisposable(view.scope())
.subscribe { view.finish() }
view.nextIntent
.autoDisposable(view.scope())
.subscribe { view.requestDefaultSms() }
}
}
@@ -0,0 +1,133 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.themepicker
import android.content.Context
import android.content.res.Resources
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayout
import com.moez.QKSMS.R
import common.util.Colors
import common.util.extensions.dpToPx
import common.util.extensions.setBackgroundTint
import common.util.extensions.setTint
import common.util.extensions.setVisible
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.theme_list_item.view.*
import kotlinx.android.synthetic.main.theme_palette_list_item.view.*
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import javax.inject.Inject
class ThemeAdapter @Inject constructor(
private val context: Context,
private val colors: Colors
) : QkAdapter<List<Int>>() {
var threadId: Long = 0
set(value) {
field = value
threadIdChanged()
}
val colorSelected: Subject<Int> = PublishSubject.create()
var selectedColor: Int = -1
set(value) {
val oldPosition = data.indexOfFirst { it.contains(field) }
val newPosition = data.indexOfFirst { it.contains(value) }
field = value
oldPosition.takeIf { it != -1 }?.let { position -> notifyItemChanged(position) }
newPosition.takeIf { it != -1 }?.let { position -> notifyItemChanged(position) }
}
private var iconTint = 0
private val disposables = CompositeDisposable()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.theme_palette_list_item, parent, false)
view.palette.flexWrap = FlexWrap.WRAP
view.palette.flexDirection = FlexDirection.ROW
return QkViewHolder(view)
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val palette = getItem(position)
val view = holder.itemView
val screenWidth = Resources.getSystem().displayMetrics.widthPixels
val minPadding = (16 * 6).dpToPx(context)
val size = if (screenWidth - minPadding > (56 * 5).dpToPx(context)) {
56.dpToPx(context)
} else {
(screenWidth - minPadding) / 5
}
val swatchPadding = (screenWidth - size * 5) / 12
view.palette.removeAllViews()
view.palette.setPadding(swatchPadding, swatchPadding, swatchPadding, swatchPadding)
(palette.subList(0, 5) + palette.subList(5, 10).reversed())
.mapIndexed { index, color ->
LayoutInflater.from(context).inflate(R.layout.theme_list_item, view.palette, false).apply {
// Send clicks to the selected subject
setOnClickListener { colorSelected.onNext(color) }
// Apply the color to the view
theme.setBackgroundTint(color)
// Control the check visibility and tint
check.setVisible(color == selectedColor)
check.setTint(iconTint)
// Update the size so that the spacing is perfectly even
layoutParams = (layoutParams as FlexboxLayout.LayoutParams).apply {
height = size
width = size
isWrapBefore = index % 5 == 0
setMargins(swatchPadding, swatchPadding, swatchPadding, swatchPadding)
}
}
}
.forEach { theme -> view.palette.addView(theme) }
}
private fun threadIdChanged() {
disposables.clear()
disposables += colors.textPrimaryOnThemeForConversation(threadId)
.subscribe { color -> iconTint = color }
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
disposables.clear()
}
}
@@ -0,0 +1,52 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.themepicker
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.view.View
import android.view.ViewGroup
import com.moez.QKSMS.R
import javax.inject.Inject
class ThemePagerAdapter @Inject constructor(private val context: Context) : PagerAdapter() {
override fun instantiateItem(container: ViewGroup, position: Int): Any {
return when (position) {
1 -> container.findViewById(R.id.rgbPicker)
else -> container.findViewById(R.id.materialColors)
}
}
override fun getPageTitle(position: Int): CharSequence? {
return when (position) {
1 -> context.getString(R.string.theme_rgb)
else -> context.getString(R.string.theme_material)
}
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view == `object`
}
override fun getCount(): Int {
return 2
}
}
@@ -0,0 +1,74 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.themepicker
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import com.moez.QKSMS.R
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import common.util.extensions.pageScrolled
import kotlinx.android.synthetic.main.theme_picker_activity.*
import presentation.common.base.QkThemedActivity
import javax.inject.Inject
class ThemePickerActivity : QkThemedActivity<ThemePickerViewModel>(), ThemePickerView {
override val viewModelClass = ThemePickerViewModel::class
override val themeSelectedIntent by lazy { themeAdapter.colorSelected }
override val pageScrolledIntent by lazy { pager.pageScrolled() }
@Inject lateinit var themeAdapter: ThemeAdapter
@Inject lateinit var themePagerAdapter: ThemePagerAdapter
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.theme_picker_activity)
setTitle(R.string.title_theme)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
pager.offscreenPageLimit = 1
pager.adapter = themePagerAdapter
tabs.pager = pager
themeAdapter.data = colors.materialColors
materialColors.layoutManager = LinearLayoutManager(this)
materialColors.adapter = themeAdapter
colors.background
.autoDisposable(scope())
.subscribe { color -> window.decorView.setBackgroundColor(color) }
}
override fun render(state: ThemePickerState) {
rgbPicker.alpha = state.rgbAlpha
rgbPicker.setBackgroundColor(state.selectedColor)
themeAdapter.threadId = state.threadId
themeAdapter.selectedColor = state.selectedColor
}
}
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.themepicker
data class ThemePickerState(
val threadId: Long = 0,
val selectedColor: Int = -1,
val rgbAlpha: Float = 0f
)
@@ -0,0 +1,30 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.themepicker
import common.util.extensions.PageScroll
import io.reactivex.Observable
import presentation.common.base.QkView
interface ThemePickerView : QkView<ThemePickerState> {
val pageScrolledIntent: Observable<PageScroll>
val themeSelectedIntent: Observable<Int>
}
@@ -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.feature.themepicker
import android.content.Intent
import com.f2prateek.rx.preferences2.Preference
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.kotlin.autoDisposable
import injection.appComponent
import util.Preferences
import io.reactivex.rxkotlin.plusAssign
import presentation.common.base.QkViewModel
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class ThemePickerViewModel(intent: Intent) : QkViewModel<ThemePickerView, ThemePickerState>(ThemePickerState()) {
@Inject lateinit var prefs: Preferences
private val threadId = intent.extras?.getLong("threadId") ?: 0L
private val theme: Preference<Int>
init {
appComponent.inject(this)
newState { it.copy(threadId = threadId) }
theme = prefs.theme(threadId)
disposables += theme.asObservable()
.subscribe { color -> newState { it.copy(selectedColor = color) } }
}
override fun bindView(view: ThemePickerView) {
super.bindView(view)
view.pageScrolledIntent
.throttleFirst(16, TimeUnit.MILLISECONDS)
.map { (position, positionOffset) -> if (position == 0) positionOffset * positionOffset else 1f }
.autoDisposable(view.scope())
.subscribe { alpha -> newState { it.copy(rgbAlpha = alpha) } }
view.themeSelectedIntent
.autoDisposable(view.scope())
.subscribe { color -> theme.set(color) }
}
}