Reorganize presentation package

This commit is contained in:
Moez Bhatti
2018-01-04 01:03:08 -05:00
parent 2d90791a9f
commit f02bdde618
40 changed files with 81 additions and 79 deletions
@@ -0,0 +1,139 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.RelativeLayout
import com.google.android.flexbox.FlexboxLayoutManager
import com.jakewharton.rxbinding2.view.keys
import com.jakewharton.rxbinding2.widget.textChanges
import com.moez.QKSMS.R
import common.util.Colors
import common.util.extensions.dpToPx
import common.util.extensions.setBackgroundTint
import common.util.extensions.showKeyboard
import data.model.Contact
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.contact_chip.view.*
import javax.inject.Inject
class ChipsAdapter @Inject constructor(private val context: Context, private val colors: Colors) : QkAdapter<Contact>() {
companion object {
private val TYPE_EDIT_TEXT = 0
private val TYPE_ITEM = 1
}
private val hint: String = context.getString(R.string.title_compose)
private val editText = View.inflate(context, R.layout.chip_input_list_item, null) as EditText
var view: RecyclerView? = null
val chipDeleted: PublishSubject<Contact> = PublishSubject.create<Contact>()
val textChanges = editText.textChanges()
init {
val wrap = ViewGroup.LayoutParams.WRAP_CONTENT
editText.layoutParams = FlexboxLayoutManager.LayoutParams(wrap, wrap).apply {
minWidth = 56.dpToPx(context)
flexGrow = 8f
}
editText.hint = hint
editText.keys()
.filter { event -> event.action == KeyEvent.ACTION_DOWN }
.filter { event -> event.keyCode == KeyEvent.KEYCODE_DEL }
.subscribe {
if (itemCount > 1 && editText.text.isEmpty()) {
chipDeleted.onNext(getItem(itemCount - 2))
}
}
}
override fun onDatasetChanged() {
editText.text = null
editText.hint = if (itemCount == 1) hint else null
if (itemCount != 2) {
editText.showKeyboard()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = when (viewType) {
TYPE_EDIT_TEXT -> QkViewHolder(editText)
else -> {
val view = LayoutInflater.from(context).inflate(R.layout.contact_chip, parent, false)
colors.composeBackground.subscribe { color -> view.content.setBackgroundTint(color) }
QkViewHolder(view)
}
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
when (getItemViewType(position)) {
TYPE_ITEM -> {
val contact = getItem(position)
val view = holder.itemView
view.avatar.contact = contact
view.name.text = contact.name
view.setOnClickListener { showDetailedChip(contact) }
}
}
}
override fun getItemCount() = super.getItemCount() + 1
override fun getItemViewType(position: Int) = if (position == itemCount - 1) TYPE_EDIT_TEXT else TYPE_ITEM
private fun showDetailedChip(contact: Contact) {
val detailedChipView = DetailedChipView(context)
detailedChipView.setContact(contact)
val rootView = view?.rootView as ViewGroup
val layoutParams = RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
layoutParams.topMargin = 24.dpToPx(context)
layoutParams.marginStart = 56.dpToPx(context)
rootView.addView(detailedChipView, layoutParams)
detailedChipView.show()
detailedChipView.setOnDeleteListener {
chipDeleted.onNext(contact)
detailedChipView.hide()
}
}
override fun areItemsTheSame(old: Contact, new: Contact): Boolean {
return old.lookupKey == new.lookupKey
}
}
@@ -0,0 +1,224 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.app.AlertDialog
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Menu
import android.view.MenuItem
import com.google.android.flexbox.FlexboxLayoutManager
import com.jakewharton.rxbinding2.view.clicks
import com.jakewharton.rxbinding2.widget.textChanges
import com.moez.QKSMS.R
import common.di.appComponent
import common.util.extensions.setBackgroundTint
import common.util.extensions.setTint
import common.util.extensions.setVisible
import common.util.extensions.showKeyboard
import data.model.Contact
import data.model.Message
import presentation.common.base.QkActivity
import io.reactivex.Observable
import io.reactivex.rxkotlin.Observables
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.compose_activity.*
import kotlinx.android.synthetic.main.toolbar_chips.*
import javax.inject.Inject
class ComposeActivity : QkActivity<ComposeViewModel>(), ComposeView {
override val viewModelClass = ComposeViewModel::class
override val queryChangedIntent: Observable<CharSequence> by lazy { chipsAdapter.textChanges }
override val chipSelectedIntent: Subject<Contact> by lazy { contactsAdapter.contactSelected }
override val chipDeletedIntent: Subject<Contact> by lazy { chipsAdapter.chipDeleted }
override val menuReadyIntent: Observable<Unit> = menu.map { Unit }
override val callIntent: Subject<Unit> = PublishSubject.create()
override val archiveIntent: Subject<Unit> = PublishSubject.create()
override val deleteIntent: Subject<Unit> = PublishSubject.create()
override val copyTextIntent: Subject<Message> = PublishSubject.create()
override val forwardMessageIntent: Subject<Message> = PublishSubject.create()
override val deleteMessageIntent: Subject<Message> = PublishSubject.create()
override val textChangedIntent by lazy { message.textChanges() }
override val attachIntent by lazy { attach.clicks() }
override val sendIntent by lazy { send.clicks() }
@Inject lateinit var chipsAdapter: ChipsAdapter
@Inject lateinit var contactsAdapter: ContactAdapter
@Inject lateinit var messageAdapter: MessagesAdapter
init {
appComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.compose_activity)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
viewModel.bindView(this)
chipsAdapter.view = chips
chips.itemAnimator = null
chips.layoutManager = FlexboxLayoutManager(this)
contacts.itemAnimator = null
contacts.layoutManager = LinearLayoutManager(this)
val layoutManager = LinearLayoutManager(this).apply { stackFromEnd = true }
messageAdapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
if (positionStart > 0) {
messageAdapter.notifyItemChanged(positionStart - 1)
}
// If we're at the bottom, scroll down to show new messages
val lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition()
if (positionStart >= messageAdapter.itemCount - 1 && lastVisiblePosition == positionStart - 1) {
messageList.scrollToPosition(positionStart)
}
}
})
messageAdapter.longClicks.subscribe { message ->
AlertDialog.Builder(this)
.setItems(R.array.message_options, { _, row ->
when (row) {
0 -> copyTextIntent.onNext(message)
1 -> forwardMessageIntent.onNext(message)
2 -> deleteMessageIntent.onNext(message)
}
})
.show()
}
messageList.setHasFixedSize(true)
messageList.layoutManager = layoutManager
messageList.adapter = messageAdapter
messageBackground.backgroundTintMode = PorterDuff.Mode.MULTIPLY
val states = arrayOf(
intArrayOf(android.R.attr.state_enabled),
intArrayOf(-android.R.attr.state_enabled))
disposables += Observables
.combineLatest(colors.textPrimaryOnTheme, colors.textTertiaryOnTheme, { primary, tertiary ->
ColorStateList(states, intArrayOf(primary, tertiary))
})
.subscribe { tintList -> sendIcon.imageTintList = tintList }
disposables += colors.theme
.subscribe { color -> send.setBackgroundTint(color) }
disposables += colors.textSecondary
.subscribe { color -> attach.setTint(color) }
disposables += colors.bubble
.subscribe { color -> messageBackground.setBackgroundTint(color) }
disposables += colors.background
.subscribe { color -> contacts.setBackgroundColor(color) }
disposables += colors.composeBackground
.doOnNext { color -> composeBar.setBackgroundTint(color) }
.doOnNext { color -> window.decorView.setBackgroundColor(color) }
.subscribe()
window.callback = ComposeWindowCallback(window.callback, this)
}
override fun render(state: ComposeState) {
if (state.hasError) {
finish()
return
}
toolbarTitle.setVisible(!state.editingMode)
chips.setVisible(state.editingMode)
contacts.setVisible(state.contactsVisible)
composeBar.setVisible(!state.contactsVisible)
// Don't set the adapters unless needed
if (state.editingMode && chips.adapter == null) chips.adapter = chipsAdapter
if (state.editingMode && contacts.adapter == null) contacts.adapter = contactsAdapter
toolbar.menu.findItem(R.id.call)?.run {
isVisible = !state.editingMode
}
toolbar.menu.findItem(R.id.archive)?.run {
isVisible = !state.editingMode
setTitle(if (state.archived) R.string.menu_unarchive else R.string.menu_archive)
}
toolbar.menu.findItem(R.id.delete)?.run {
isVisible = !state.editingMode
}
if (chipsAdapter.data.isEmpty() && state.selectedContacts.isNotEmpty()) {
message.showKeyboard()
}
if (chipsAdapter.data !== state.selectedContacts) {
chipsAdapter.data = state.selectedContacts
}
if (contactsAdapter.data !== state.contacts) {
contactsAdapter.data = state.contacts
}
if (messageAdapter.data !== state.messages) {
messageAdapter.updateData(state.messages)
}
if (title != state.title) title = state.title
send.isEnabled = state.canSend
sendIcon.isEnabled = state.canSend
}
override fun setDraft(draft: String) {
message.setText(draft)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.compose, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.call -> callIntent.onNext(Unit)
R.id.archive -> archiveIntent.onNext(Unit)
R.id.delete -> deleteIntent.onNext(Unit)
else -> return super.onOptionsItemSelected(item)
}
return true
}
}
@@ -0,0 +1,35 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import data.model.Contact
import data.model.Message
import io.realm.RealmResults
data class ComposeState(
val hasError: Boolean = false,
val editingMode: Boolean = false,
val contacts: List<Contact> = ArrayList(),
val contactsVisible: Boolean = false,
val selectedContacts: List<Contact> = ArrayList(),
val title: String = "",
val archived: Boolean = false,
val messages: RealmResults<Message>? = null,
val canSend: Boolean = false
)
@@ -0,0 +1,45 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import data.model.Contact
import data.model.Message
import presentation.common.base.QkView
import io.reactivex.Observable
import io.reactivex.subjects.Subject
interface ComposeView : QkView<ComposeState> {
val queryChangedIntent: Observable<CharSequence>
val chipSelectedIntent: Subject<Contact>
val chipDeletedIntent: Subject<Contact>
val menuReadyIntent: Observable<Unit>
val callIntent: Subject<Unit>
val archiveIntent: Subject<Unit>
val deleteIntent: Subject<Unit>
val copyTextIntent: Subject<Message>
val forwardMessageIntent: Subject<Message>
val deleteMessageIntent: Subject<Message>
val textChangedIntent: Observable<CharSequence>
val attachIntent: Observable<Unit>
val sendIntent: Observable<Unit>
fun setDraft(draft: String)
}
@@ -0,0 +1,240 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.content.Context
import com.moez.QKSMS.R
import common.di.appComponent
import common.util.ClipboardUtils
import common.util.extensions.asObservable
import common.util.extensions.makeToast
import common.util.filter.ContactFilter
import data.model.Contact
import data.model.Conversation
import data.repository.ContactRepository
import data.repository.MessageRepository
import interactor.*
import presentation.common.Navigator
import presentation.common.base.QkViewModel
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.Observables
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.withLatestFrom
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import javax.inject.Inject
class ComposeViewModel(threadId: Long, var draft: String)
: QkViewModel<ComposeView, ComposeState>(ComposeState(editingMode = threadId == 0L)) {
@Inject lateinit var context: Context
@Inject lateinit var contactFilter: ContactFilter
@Inject lateinit var contactsRepo: ContactRepository
@Inject lateinit var messageRepo: MessageRepository
@Inject lateinit var navigator: Navigator
@Inject lateinit var syncContacts: ContactSync
@Inject lateinit var markArchived: MarkArchived
@Inject lateinit var markUnarchived: MarkUnarchived
@Inject lateinit var deleteConversation: DeleteConversation
@Inject lateinit var sendMessage: SendMessage
@Inject lateinit var markRead: MarkRead
@Inject lateinit var deleteMessage: DeleteMessage
private val contacts: List<Contact> by lazy { contactsRepo.getContacts() }
private val contactsReducer: Subject<(List<Contact>) -> List<Contact>> = PublishSubject.create()
private val selectedContacts: Observable<List<Contact>>
private val conversation: Observable<Conversation>
init {
appComponent.inject(this)
selectedContacts = contactsReducer
.scan(listOf<Contact>(), { previousState, reducer -> reducer(previousState) })
.doOnNext { contacts -> newState { it.copy(selectedContacts = contacts) } }
val initialConversation: Observable<Conversation> = when (threadId) {
0L -> Observable.empty()
else -> messageRepo.getConversationAsync(threadId).asObservable()
}
// Map the selected contacts to a conversation so that we can display the message history
val selectedConversation = selectedContacts
.map { contacts -> contacts.map { it.numbers.firstOrNull()?.address ?: "" } }
.flatMapMaybe { addresses -> messageRepo.getOrCreateConversation(addresses) }
// Merges two potential conversation sources (threadId from constructor and contact selection) into a single
// stream of conversations. If the conversation was deleted, notify the activity to shut down
conversation = initialConversation
.filter { conversation -> conversation.isLoaded }
.doOnNext { conversation ->
if (!conversation.isValid) {
newState { it.copy(hasError = true) }
}
}
.mergeWith(selectedConversation)
.filter { conversation -> conversation.isValid }
.filter { conversation -> conversation.id != 0L }
.distinctUntilChanged()
.doOnNext { conversation ->
newState { it.copy(title = conversation.getTitle(), archived = conversation.archived) }
}
disposables += sendMessage
disposables += markRead
disposables += markArchived
disposables += markUnarchived
disposables += deleteConversation
disposables += conversation.subscribe()
// When the conversation changes, update the messages for the adapter
// When the message list changes, make sure to mark them read
disposables += conversation
.distinctUntilChanged()
.observeOn(AndroidSchedulers.mainThread())
.map { conversation -> messageRepo.getMessages(conversation.id) }
.doOnNext { messages -> newState { it.copy(messages = messages) } }
.flatMap { messages -> messages.asObservable() }
.withLatestFrom(conversation, { messages, conversation ->
markRead.execute(conversation.id)
messages
})
.subscribe()
if (threadId == 0L) {
syncContacts.execute(Unit)
}
}
override fun bindView(view: ComposeView) {
super.bindView(view)
if (draft.isNotEmpty()) {
view.setDraft(draft)
draft = ""
}
// Set the contact suggestions list to visible at all times when in editing mode and there are no contacts
// selected yet, and also visible while in editing mode and there is text entered in the query field
intents += Observables
.combineLatest(view.queryChangedIntent, selectedContacts, { query, selectedContacts ->
selectedContacts.isEmpty() || query.isNotEmpty()
})
.skipUntil(state.filter { state -> state.editingMode == true })
.takeUntil(state.filter { state -> state.editingMode == false })
.distinctUntilChanged()
.subscribe { contactsVisible -> newState { it.copy(contactsVisible = contactsVisible && it.editingMode) } }
// Update the list of contact suggestions based on the query input, while also filtering out any contacts
// that have already been selected
intents += Observables
.combineLatest(view.queryChangedIntent, selectedContacts, { query, selectedContacts ->
contacts
.filterNot { contact -> selectedContacts.contains(contact) }
.filter { contact -> contactFilter.filter(contact, query) }
})
.skipUntil(state.filter { state -> state.editingMode == true })
.takeUntil(state.filter { state -> state.editingMode == false })
.subscribeOn(Schedulers.computation())
.subscribe { contacts -> newState { it.copy(contacts = contacts) } }
// Update the list of selected contacts when a new contact is selected or an existing one is deselected
intents += Observable.merge(
view.chipDeletedIntent.doOnNext { contact ->
contactsReducer.onNext { contacts -> contacts.filterNot { it == contact } }
},
view.chipSelectedIntent.doOnNext { contact ->
contactsReducer.onNext { contacts -> contacts.toMutableList().apply { add(contact) } }
})
.skipUntil(state.filter { state -> state.editingMode == true })
.takeUntil(state.filter { state -> state.editingMode == false })
.subscribe()
// When the menu is loaded, trigger a new state so that the menu options can be rendered correctly
intents += view.menuReadyIntent.subscribe {
newState { it.copy() }
}
// Open the phone dialer if the call button is clicked
intents += view.callIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.map { conversation -> conversation.recipients.first() }
.map { recipient -> recipient.address }
.subscribe { address -> navigator.makePhoneCall(address) }
// Toggle the archived state of the conversation
intents += view.archiveIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.subscribe { conversation ->
when (conversation.archived) {
true -> markUnarchived.execute(conversation.id, { context.makeToast(R.string.toast_unarchived) })
false -> markArchived.execute(conversation.id, { context.makeToast(R.string.toast_archived) })
}
}
// Delete the conversation
intents += view.deleteIntent
.withLatestFrom(conversation, { _, conversation -> conversation })
.subscribe { conversation -> deleteConversation.execute(conversation.id) }
// Add an attachment
intents += view.attachIntent
.subscribe { context.makeToast(R.string.compose_attach_unsupported) }
// Enable the send button when there is text input into the new message body, disable otherwise
intents += view.textChangedIntent.subscribe { text ->
newState { it.copy(canSend = text.isNotEmpty()) }
}
// Send a message when the send button is clicked, and disable editing mode if it's enabled
intents += view.sendIntent
.withLatestFrom(view.textChangedIntent, { _, body -> body })
.map { body -> body.toString() }
.withLatestFrom(conversation, { body, conversation ->
val threadId = conversation.id
val address = conversation.recipients.first()?.address.orEmpty()
sendMessage.execute(SendMessage.Params(threadId, address, body))
view.setDraft("")
})
.withLatestFrom(state, {_, state ->
if (state.editingMode) {
newState { it.copy(editingMode = false) }
}
})
.subscribe()
// Copy the body of the selected message into the clipboard
intents += view.copyTextIntent.subscribe { message ->
ClipboardUtils.copy(context, message.body)
context.makeToast(R.string.toast_copied)
}
// Forward the message
intents += view.forwardMessageIntent.subscribe { message ->
navigator.showCompose(message.body)
}
// Delete the selected message
intents += view.deleteMessageIntent.subscribe { message ->
deleteMessage.execute(message.id)
}
}
}
@@ -0,0 +1,135 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.app.Activity
import android.graphics.Rect
import android.os.Build
import android.support.annotation.RequiresApi
import android.view.*
import android.view.accessibility.AccessibilityEvent
class ComposeWindowCallback(private val localCallback: Window.Callback, private val activity: Activity) : Window.Callback {
override fun dispatchKeyEvent(keyEvent: KeyEvent): Boolean {
return localCallback.dispatchKeyEvent(keyEvent)
}
override fun dispatchKeyShortcutEvent(keyEvent: KeyEvent): Boolean {
return localCallback.dispatchKeyShortcutEvent(keyEvent)
}
override fun dispatchTouchEvent(motionEvent: MotionEvent): Boolean {
if (motionEvent.action == MotionEvent.ACTION_DOWN) {
val v = activity.currentFocus
when (v) {
is DetailedChipView -> {
val rect = Rect().apply { v.getGlobalVisibleRect(this) }
if (!rect.contains(motionEvent.rawX.toInt(), motionEvent.rawY.toInt())) {
v.hide()
return true
}
}
}
}
return localCallback.dispatchTouchEvent(motionEvent)
}
override fun dispatchTrackballEvent(motionEvent: MotionEvent): Boolean {
return localCallback.dispatchTrackballEvent(motionEvent)
}
override fun dispatchGenericMotionEvent(motionEvent: MotionEvent): Boolean {
return localCallback.dispatchGenericMotionEvent(motionEvent)
}
override fun dispatchPopulateAccessibilityEvent(accessibilityEvent: AccessibilityEvent): Boolean {
return localCallback.dispatchPopulateAccessibilityEvent(accessibilityEvent)
}
override fun onCreatePanelView(i: Int): View? {
return localCallback.onCreatePanelView(i)
}
override fun onCreatePanelMenu(i: Int, menu: Menu): Boolean {
return localCallback.onCreatePanelMenu(i, menu)
}
override fun onPreparePanel(i: Int, view: View, menu: Menu): Boolean {
return localCallback.onPreparePanel(i, view, menu)
}
override fun onMenuOpened(i: Int, menu: Menu): Boolean {
return localCallback.onMenuOpened(i, menu)
}
override fun onMenuItemSelected(i: Int, menuItem: MenuItem): Boolean {
return localCallback.onMenuItemSelected(i, menuItem)
}
override fun onWindowAttributesChanged(layoutParams: WindowManager.LayoutParams) {
localCallback.onWindowAttributesChanged(layoutParams)
}
override fun onContentChanged() {
localCallback.onContentChanged()
}
override fun onWindowFocusChanged(b: Boolean) {
localCallback.onWindowFocusChanged(b)
}
override fun onAttachedToWindow() {
localCallback.onAttachedToWindow()
}
override fun onDetachedFromWindow() {
localCallback.onDetachedFromWindow()
}
override fun onPanelClosed(i: Int, menu: Menu) {
localCallback.onPanelClosed(i, menu)
}
override fun onSearchRequested(): Boolean {
return localCallback.onSearchRequested()
}
@RequiresApi(api = Build.VERSION_CODES.M)
override fun onSearchRequested(searchEvent: SearchEvent): Boolean {
return localCallback.onSearchRequested(searchEvent)
}
override fun onWindowStartingActionMode(callback: ActionMode.Callback): ActionMode? {
return localCallback.onWindowStartingActionMode(callback)
}
@RequiresApi(api = Build.VERSION_CODES.M)
override fun onWindowStartingActionMode(callback: ActionMode.Callback, i: Int): ActionMode? {
return localCallback.onWindowStartingActionMode(callback, i)
}
override fun onActionModeStarted(actionMode: ActionMode) {
localCallback.onActionModeStarted(actionMode)
}
override fun onActionModeFinished(actionMode: ActionMode) {
localCallback.onActionModeFinished(actionMode)
}
}
@@ -0,0 +1,60 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.feature.compose
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R
import data.model.Contact
import presentation.common.base.QkAdapter
import presentation.common.base.QkViewHolder
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.contact_list_item.view.*
import javax.inject.Inject
class ContactAdapter @Inject constructor(private val context: Context) : QkAdapter<Contact>() {
val contactSelected: Subject<Contact> = PublishSubject.create()
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): QkViewHolder {
val layoutRes = R.layout.contact_list_item
val layoutInflater = LayoutInflater.from(context)
val view = layoutInflater.inflate(layoutRes, parent, false)
return QkViewHolder(view)
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val contact = getItem(position)
val view = holder.itemView
view.clicks().subscribe { contactSelected.onNext(contact) }
view.avatar.contact = contact
view.name.text = contact.name
view.address.text = contact.numbers.map { it.address }.toString()
}
override fun areItemsTheSame(old: Contact, new: Contact): Boolean {
return old.lookupKey == new.lookupKey
}
}
@@ -0,0 +1,91 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.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 common.di.appComponent
import common.util.Colors
import common.util.extensions.setBackgroundTint
import data.model.Contact
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import kotlinx.android.synthetic.main.contact_chip_detailed.view.*
import javax.inject.Inject
class DetailedChipView(context: Context) : RelativeLayout(context) {
@Inject lateinit var colors: Colors
private val disposables = CompositeDisposable()
init {
View.inflate(context, R.layout.contact_chip_detailed, this)
appComponent.inject(this)
setOnClickListener { hide() }
visibility = View.GONE
isFocusable = true
isFocusableInTouchMode = true
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
disposables += colors.theme
.subscribe { color -> card.setBackgroundTint(color) }
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
disposables.clear()
}
fun setContact(contact: Contact) {
avatar.contact = contact
name.text = contact.name
info.text = contact.numbers.map { it.address }.toString()
}
fun show() {
startAnimation(AlphaAnimation(0f, 1f).apply { duration = 200 })
visibility = View.VISIBLE
requestFocus()
isClickable = true
}
fun hide() {
startAnimation(AlphaAnimation(1f, 0f).apply { duration = 200 })
visibility = View.GONE
clearFocus()
isClickable = false
}
fun setOnDeleteListener(listener: (View) -> Unit) {
delete.setOnClickListener(listener)
}
}
@@ -0,0 +1,173 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package presentation.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 com.jakewharton.rxbinding2.view.RxView
import com.moez.QKSMS.R
import common.util.Colors
import common.util.DateFormatter
import common.util.extensions.dpToPx
import common.util.extensions.setBackgroundTint
import common.util.extensions.setPadding
import common.util.extensions.setVisible
import data.model.Contact
import data.model.Message
import data.model.PhoneNumber
import presentation.common.base.QkViewHolder
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import io.realm.RealmRecyclerViewAdapter
import kotlinx.android.synthetic.main.message_list_item_in.view.*
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class MessagesAdapter @Inject constructor(
private val context: Context,
private val colors: Colors,
private val dateFormatter: DateFormatter)
: RealmRecyclerViewAdapter<Message, QkViewHolder>(null, true) {
companion object {
private val VIEWTYPE_ME = -1
private val TIMESTAMP_THRESHOLD = 10
}
val longClicks: Subject<Message> = PublishSubject.create<Message>()
private val people = ArrayList<String>()
private val disposables = CompositeDisposable()
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): QkViewHolder {
val layoutInflater = LayoutInflater.from(context)
val view: View
when (viewType) {
VIEWTYPE_ME -> {
view = layoutInflater.inflate(R.layout.message_list_item_out, parent, false)
disposables += colors.bubble
.subscribe { color -> view.messageBackground.setBackgroundTint(color) }
}
else -> {
view = layoutInflater.inflate(R.layout.message_list_item_in, parent, false)
disposables += colors.theme
.subscribe { color -> view.messageBackground.setBackgroundTint(color) }
}
}
if (viewType != VIEWTYPE_ME) {
view.avatar.contact = Contact().apply {
numbers.add(PhoneNumber().apply { address = people[viewType] })
}
}
return QkViewHolder(view)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView?) {
super.onDetachedFromRecyclerView(recyclerView)
disposables.clear()
}
override fun onBindViewHolder(viewHolder: QkViewHolder, position: Int) {
val message = getItem(position)!!
val view = viewHolder.itemView
RxView.clicks(view).subscribe { Timber.v(message.toString()) }
RxView.longClicks(view).subscribe { longClicks.onNext(message) }
bindGrouping(view, position)
val age = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - message.date)
view.status?.text = when {
message.isSending() -> context.getString(R.string.message_status_sending)
message.isDelivered() && age <= TIMESTAMP_THRESHOLD -> context.getString(R.string.message_status_delivered)
message.isFailedMessage() -> context.getString(R.string.message_status_failed)
else -> null
}
view.status?.setVisible(!view.status?.text.isNullOrBlank())
view.body.text = message.body
view.timestamp.text = dateFormatter.getMessageTimestamp(message.date)
}
private fun bindGrouping(view: View, position: Int) {
val message = getItem(position)!!
val previous = if (position == 0) null else getItem(position - 1)
val next = if (position == itemCount - 1) null else getItem(position + 1)
val diff = TimeUnit.MILLISECONDS.toMinutes(message.date - (previous?.date ?: 0))
val sent = message.isMe()
val canGroupWithPrevious = canGroup(message, previous)
val canGroupWithNext = canGroup(message, next)
view.timestamp.visibility = if (diff < TIMESTAMP_THRESHOLD) View.GONE else View.VISIBLE
when {
!canGroupWithPrevious && canGroupWithNext -> {
view.setPadding(bottom = 2.dpToPx(context))
view.messageBackground.setBackgroundResource(if (sent) R.drawable.message_out_first else R.drawable.message_in_first)
view.avatar?.visibility = View.INVISIBLE
}
canGroupWithPrevious && canGroupWithNext -> {
view.setPadding(bottom = 2.dpToPx(context))
view.messageBackground.setBackgroundResource(if (sent) R.drawable.message_out_middle else R.drawable.message_in_middle)
view.avatar?.visibility = View.INVISIBLE
}
canGroupWithPrevious && !canGroupWithNext -> {
view.setPadding(bottom = 16.dpToPx(context))
view.messageBackground.setBackgroundResource(if (sent) R.drawable.message_out_last else R.drawable.message_in_last)
view.avatar?.visibility = View.VISIBLE
}
else -> {
view.setPadding(bottom = 16.dpToPx(context))
view.messageBackground.setBackgroundResource(R.drawable.message_only)
view.avatar?.visibility = View.VISIBLE
}
}
}
private fun canGroup(message: Message, other: Message?): Boolean {
if (other == null) return false
val diff = TimeUnit.MILLISECONDS.toMinutes(Math.abs(message.date - other.date))
return message.isMe() == other.isMe() && diff < TIMESTAMP_THRESHOLD
}
override fun getItemViewType(position: Int): Int {
val message = getItem(position)!!
if (message.isMe()) {
return VIEWTYPE_ME
}
if (!people.contains(message.address)) {
people.add(message.address)
}
return people.indexOf(message.address)
}
}