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