From 1c08c0dc20ba12dfadb5c732dd19753d6e4cff13 Mon Sep 17 00:00:00 2001 From: octoshrimpy Date: Sun, 14 Jun 2026 20:26:05 -0400 Subject: [PATCH] refactor(reactions): shrink reaction SMS payload and dedupe swipe code Prepares the send-reactions feature for public release by cutting the per-reaction SMS size and removing duplicated swipe-action code. Payload (EmojiReactionRepositoryImpl): - Stop re-embedding the replied-to text in the hidden payload; it already shows in the visible fallback line. The reaction target is resolved by sender address + timestamp, and the text-fallback matcher now recovers the quote from the visible line. - Encode the payload at 3 bits per invisible char (8-symbol alphabet) instead of 1, and word-cap the visible quote. A reaction's invisible run drops from ~1,200 chars (~10-20 SMS segments) to ~83 (1-2 segments). Deduplication: - Extract SwipeItemTouchCallback base; ConversationItemTouchCallback and MessageItemTouchCallback become thin subclasses (removes dead fields). - Extract BaseSwipeActionsPresenter and share SwipeActionsView/State; delete the cloned MessageSwipeActions View/State. Centralize the message swipe-action icon map. - Merge the two near-identical reaction-send streams in ComposeViewModel. Minor: enumerate the full emoji set off the main thread in EmojiPicker; reuse a single Handler for the reaction pulse in MessagesAdapter. Co-Authored-By: Claude Opus 4.8 --- .../repository/EmojiReactionRepositoryImpl.kt | 96 ++++++++--- .../com/moez/QKSMS/common/util/EmojiPicker.kt | 72 +++++--- .../common/util/SwipeItemTouchCallback.kt | 160 ++++++++++++++++++ .../QKSMS/feature/compose/ComposeViewModel.kt | 39 +---- .../compose/MessageItemTouchCallback.kt | 138 ++------------- .../QKSMS/feature/compose/MessagesAdapter.kt | 5 +- .../ConversationItemTouchCallback.kt | 139 +++------------ .../swipe/BaseSwipeActionsPresenter.kt | 79 +++++++++ ...onsState.kt => MessageSwipeActionIcons.kt} | 18 +- .../swipe/MessageSwipeActionsController.kt | 12 +- .../swipe/MessageSwipeActionsPresenter.kt | 53 +----- .../settings/swipe/MessageSwipeActionsView.kt | 33 ---- .../settings/swipe/SwipeActionsPresenter.kt | 46 +---- 13 files changed, 429 insertions(+), 461 deletions(-) create mode 100644 presentation/src/main/java/com/moez/QKSMS/common/util/SwipeItemTouchCallback.kt create mode 100644 presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/BaseSwipeActionsPresenter.kt rename presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/{MessageSwipeActionsState.kt => MessageSwipeActionIcons.kt} (57%) delete mode 100644 presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/MessageSwipeActionsView.kt diff --git a/data/src/main/java/com/moez/QKSMS/repository/EmojiReactionRepositoryImpl.kt b/data/src/main/java/com/moez/QKSMS/repository/EmojiReactionRepositoryImpl.kt index aec2f3e2..1cbab656 100644 --- a/data/src/main/java/com/moez/QKSMS/repository/EmojiReactionRepositoryImpl.kt +++ b/data/src/main/java/com/moez/QKSMS/repository/EmojiReactionRepositoryImpl.kt @@ -28,6 +28,7 @@ import dev.octoshrimpy.quik.util.EmojiPatternStrings import io.realm.Realm import io.realm.Sort import timber.log.Timber +import java.io.ByteArrayOutputStream import javax.inject.Inject class EmojiReactionRepositoryImpl @Inject constructor( @@ -42,11 +43,30 @@ class EmojiReactionRepositoryImpl @Inject constructor( // by the iOS/Google tapback patterns, and won't appear in normal message text. private const val ZW_START = '\u2061' // function application private const val ZW_END = '\u2064' // invisible plus - private const val ZW_ZERO = '\u2062' // invisible times - private const val ZW_ONE = '\u2063' // invisible separator + // Alphabet for the payload: 8 distinct BMP default-ignorable code points, so each char + // carries 3 bits (vs 1 bit for a two-symbol scheme) and the invisible run is ~1/3 as long. + // All are non-combining, non-bidi, render nothing, survive SMS UCS-2 transport verbatim, + // and are distinct from the sentinels and the U+200A..U+200D pattern chars. (16 symbols / + // 4 bits would need code points that risk a visible glyph or U+FFFD substitution on the + // receiver, so 8 symbols / 3 bits is the densest safe choice.) + private val ZW_ALPHABET = charArrayOf( + '\u2060', // word joiner + '\u2062', // invisible times + '\u2063', // invisible separator + '\u206a', // inhibit symmetric swapping (deprecated format) + '\u206b', // activate symmetric swapping + '\u206c', // inhibit arabic form shaping + '\u206d', // activate arabic form shaping + '\u206e', // national digit shapes + ) + private const val ZW_BITS_PER_CHAR = 3 + private val ZW_INDEX: Map = + ZW_ALPHABET.withIndex().associate { (i, c) -> c to i } private const val PAYLOAD_FIELD_SEPARATOR = '\u001f' // unit separator - private const val MAX_PAYLOAD_TEXT = 120 + // The replied-to text is shown only in the visible fallback line (not duplicated into the + // payload); cap it so reactions to long messages stay within a couple of SMS segments. + private const val MAX_VISIBLE_WORDS = 20 } // We use an ordered map to make sure we can test tapback regexes before generic ones @@ -171,38 +191,53 @@ class EmojiReactionRepositoryImpl @Inject constructor( override fun buildReactionBody(emoji: String, targetMessage: Message): String { val senderAddress = targetMessage.address val timestampMs = targetMessage.date - val originalText = targetMessage.getText(false).trim() + val originalText = capWords(targetMessage.getText(false).trim()) // Visible, iOS-style fallback so non-quik clients see a clean, readable line. val human = if (originalText.isEmpty()) "Reacted $emoji to a message" else "Reacted $emoji to \"$originalText\"" - // Machine-readable payload, hidden in zero-width characters and parsed only by quik. - // originalText is capped to keep the invisible payload (and thus the SMS) reasonably small. - val payload = listOf(emoji, senderAddress, timestampMs.toString(), originalText.take(MAX_PAYLOAD_TEXT)) + // Hidden machine payload, parsed only by quik. The target is resolved by sender address + + // timestamp, so the body text is NOT duplicated here (it stays only in the visible line + // above) to keep the SMS short. + val payload = listOf(emoji, senderAddress, timestampMs.toString()) .joinToString(PAYLOAD_FIELD_SEPARATOR.toString()) return human + encodeQuikPayload(payload) } + /** Cap [text] to [MAX_VISIBLE_WORDS] words, appending an ellipsis when truncated. */ + private fun capWords(text: String): String { + val words = text.split(Regex("\\s+")).filter { it.isNotEmpty() } + return if (words.size <= MAX_VISIBLE_WORDS) text.trim() + else words.take(MAX_VISIBLE_WORDS).joinToString(" ") + "…" + } + /** - * Encode a UTF-8 string into an invisible run of zero-width characters, wrapped in sentinels. - * Each byte becomes 8 zero-width bits ([ZW_ZERO]/[ZW_ONE]). + * Encode a UTF-8 string into an invisible run wrapped in sentinels. The byte stream is emitted + * [ZW_BITS_PER_CHAR] bits at a time, each group mapped to one [ZW_ALPHABET] char. */ private fun encodeQuikPayload(payload: String): String { val sb = StringBuilder() sb.append(ZW_START) + var buffer = 0 + var bits = 0 for (byte in payload.toByteArray(Charsets.UTF_8)) { - val value = byte.toInt() and 0xFF - for (bit in 7 downTo 0) - sb.append(if ((value shr bit) and 1 == 1) ZW_ONE else ZW_ZERO) + buffer = (buffer shl 8) or (byte.toInt() and 0xFF) + bits += 8 + while (bits >= ZW_BITS_PER_CHAR) { + bits -= ZW_BITS_PER_CHAR + sb.append(ZW_ALPHABET[(buffer shr bits) and 0x7]) + } } + if (bits > 0) // flush the final partial group, zero-padded on the right + sb.append(ZW_ALPHABET[(buffer shl (ZW_BITS_PER_CHAR - bits)) and 0x7]) sb.append(ZW_END) return sb.toString() } /** - * Extract and decode a quik zero-width payload from a message body, or null if absent/invalid. + * Extract and decode a quik invisible payload from a message body, or null if absent/invalid. */ private fun decodeQuikPayload(body: String): String? { val start = body.indexOf(ZW_START) @@ -210,17 +245,20 @@ class EmojiReactionRepositoryImpl @Inject constructor( val end = body.indexOf(ZW_END, start + 1) if (end == -1) return null - val bits = body.substring(start + 1, end).filter { it == ZW_ZERO || it == ZW_ONE } - if (bits.isEmpty() || bits.length % 8 != 0) return null - - val bytes = ByteArray(bits.length / 8) - for (i in bytes.indices) { - var value = 0 - for (bit in 0 until 8) - value = (value shl 1) or (if (bits[i * 8 + bit] == ZW_ONE) 1 else 0) - bytes[i] = value.toByte() + var buffer = 0 + var bits = 0 + val bytes = ByteArrayOutputStream() + for (i in start + 1 until end) { + val symbol = ZW_INDEX[body[i]] ?: continue // ignore any stray non-alphabet chars + buffer = (buffer shl ZW_BITS_PER_CHAR) or symbol + bits += ZW_BITS_PER_CHAR + if (bits >= 8) { + bits -= 8 + bytes.write((buffer shr bits) and 0xFF) + } } - return String(bytes, Charsets.UTF_8) + // trailing < 8 bits are zero padding from the encoder and are dropped + return bytes.toByteArray().takeIf { it.isNotEmpty() }?.let { String(it, Charsets.UTF_8) } } private fun parseQuikReaction(body: String): ParsedEmojiReaction? { @@ -229,12 +267,22 @@ class EmojiReactionRepositoryImpl @Inject constructor( if (parts.size < 3) return null return ParsedEmojiReaction( emoji = parts[0], - originalMessage = parts.getOrElse(3) { "" }, + // original text now lives only in the visible line; recover it for the text-fallback + // matcher (the address + timestamp fast path handles the common case) + originalMessage = extractVisibleQuotedText(body), quikSenderAddress = parts[1].ifEmpty { null }, quikTimestamp = parts[2].toLongOrNull(), ) } + /** Pull the quoted text out of the visible `Reacted to ""` fallback line. */ + private fun extractVisibleQuotedText(body: String): String { + val visible = body.substringBefore(ZW_START) + val open = visible.indexOf('"') + val close = visible.lastIndexOf('"') + return if (open != -1 && close > open) visible.substring(open + 1, close) else "" + } + private fun parseRemoval(body: String): ParsedEmojiReaction? { for ((pattern, parser) in removalPatterns) { val match = pattern.find(body) ?: continue diff --git a/presentation/src/main/java/com/moez/QKSMS/common/util/EmojiPicker.kt b/presentation/src/main/java/com/moez/QKSMS/common/util/EmojiPicker.kt index a0e4dd0c..60971a23 100644 --- a/presentation/src/main/java/com/moez/QKSMS/common/util/EmojiPicker.kt +++ b/presentation/src/main/java/com/moez/QKSMS/common/util/EmojiPicker.kt @@ -29,6 +29,9 @@ import com.google.android.material.bottomsheet.BottomSheetDialog import dev.octoshrimpy.quik.R import dev.octoshrimpy.quik.common.util.extensions.dpToPx import dev.octoshrimpy.quik.common.util.extensions.resolveThemeColor +import io.reactivex.Single +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.schedulers.Schedulers /** * A lightweight, dependency-free emoji picker. Renders a themed, scrollable grid of emoji in a @@ -80,6 +83,36 @@ object EmojiPicker { val sheet = BottomSheetDialog(context) + // Show the common emoji immediately; the full set probes thousands of code points for + // glyphs, so it's enumerated off the main thread and appended when ready — opening the + // sheet never blocks the UI thread. + val items = ArrayList(commonEmojis) + + val gridAdapter = object : RecyclerView.Adapter() { + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = + object : RecyclerView.ViewHolder(TextView(context).apply { + textSize = 22f + gravity = Gravity.CENTER + includeFontPadding = false + setTextColor(textColor) + setBackgroundResource(R.drawable.ripple) + layoutParams = RecyclerView.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, cell + ) + }) {} + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val emoji = items[position] + (holder.itemView as TextView).text = emoji + holder.itemView.setOnClickListener { + onPicked(emoji) + sheet.dismiss() + } + } + + override fun getItemCount() = items.size + } + val recycler = RecyclerView(context).apply { setBackgroundColor(backgroundColor) layoutManager = GridLayoutManager(context, span) @@ -87,32 +120,23 @@ object EmojiPicker { ViewGroup.LayoutParams.MATCH_PARENT, (context.resources.displayMetrics.heightPixels * 0.5f).toInt() ) - adapter = object : RecyclerView.Adapter() { - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = - object : RecyclerView.ViewHolder(TextView(context).apply { - textSize = 22f - gravity = Gravity.CENTER - includeFontPadding = false - setTextColor(textColor) - setBackgroundResource(R.drawable.ripple) - layoutParams = RecyclerView.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, cell - ) - }) {} - - override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { - val emoji = emojis[position] - (holder.itemView as TextView).text = emoji - holder.itemView.setOnClickListener { - onPicked(emoji) - sheet.dismiss() - } - } - - override fun getItemCount() = emojis.size - } + adapter = gridAdapter } + // emojis starts with commonEmojis (distinct), so only the generated tail is appended + val load = Single.fromCallable { emojis } + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe { full -> + val tail = full.drop(items.size) + if (tail.isNotEmpty()) { + val start = items.size + items.addAll(tail) + gridAdapter.notifyItemRangeInserted(start, tail.size) + } + } + + sheet.setOnDismissListener { load.dispose() } sheet.setContentView(recycler) sheet.show() } diff --git a/presentation/src/main/java/com/moez/QKSMS/common/util/SwipeItemTouchCallback.kt b/presentation/src/main/java/com/moez/QKSMS/common/util/SwipeItemTouchCallback.kt new file mode 100644 index 00000000..bf2c108a --- /dev/null +++ b/presentation/src/main/java/com/moez/QKSMS/common/util/SwipeItemTouchCallback.kt @@ -0,0 +1,160 @@ +/* + * Copyright (C) 2017 Moez Bhatti + * + * 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 . + */ +package dev.octoshrimpy.quik.common.util + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Rect +import androidx.core.graphics.drawable.toBitmap +import androidx.recyclerview.widget.ItemTouchHelper +import androidx.recyclerview.widget.RecyclerView +import dev.octoshrimpy.quik.common.util.extensions.dpToPx +import io.reactivex.Observable +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.rxkotlin.Observables +import io.reactivex.rxkotlin.plusAssign +import io.reactivex.schedulers.Schedulers +import io.reactivex.subjects.PublishSubject +import io.reactivex.subjects.Subject +import kotlin.math.max +import kotlin.math.min + +/** + * Shared swipe-to-action behaviour for the conversations list and the messages list: draws the + * themed background and action icon while a row is swiped, and emits `(itemId, direction)` on + * release. Subclasses supply which prefs drive the left/right actions, how an action maps to an + * icon, and (optionally) what to do after a swipe completes. + */ +abstract class SwipeItemTouchCallback( + colors: Colors, + disposables: CompositeDisposable, + private val context: Context +) : ItemTouchHelper.SimpleCallback(0, 0) { + + val swipes: Subject> = PublishSubject.create() + + /** + * Setting the adapter allows us to animate back to the original position + */ + var adapter: RecyclerView.Adapter<*>? = null + + private val backgroundPaint = Paint() + protected var rightAction = 0 + protected var leftAction = 0 + private var swipeRightIcon: Bitmap? = null + private var swipeLeftIcon: Bitmap? = null + + private val iconLength = 24.dpToPx(context) + + /** Action value that means "no swipe action" (0 for both lists). */ + protected abstract val noneAction: Int + + protected abstract fun rightActionObservable(): Observable + protected abstract fun leftActionObservable(): Observable + protected abstract fun iconForAction(action: Int, tint: Int): Bitmap? + + init { + disposables += colors.themeObservable() + .doOnNext { theme -> backgroundPaint.color = theme.theme } + .subscribeOn(Schedulers.io()) + .subscribe() + + disposables += Observables + .combineLatest(rightActionObservable(), leftActionObservable(), colors.themeObservable() + ) { right, left, theme -> + rightAction = right + swipeRightIcon = iconForAction(right, theme.textPrimary) + leftAction = left + swipeLeftIcon = iconForAction(left, theme.textPrimary) + setDefaultSwipeDirs((if (right == noneAction) 0 else ItemTouchHelper.RIGHT) + or (if (left == noneAction) 0 else ItemTouchHelper.LEFT)) + } + .subscribeOn(Schedulers.io()) + .subscribe() + } + + override fun onMove( + recyclerView: RecyclerView, + viewHolder: RecyclerView.ViewHolder, + target: RecyclerView.ViewHolder + ): Boolean { + return false + } + + override fun onChildDraw( + c: Canvas, + recyclerView: RecyclerView, + viewHolder: RecyclerView.ViewHolder, + dX: Float, + dY: Float, + actionState: Int, + isCurrentlyActive: Boolean + ) { + if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { + val itemView = viewHolder.itemView + + if (dX > 0) { + c.drawRect(itemView.left.toFloat(), itemView.top.toFloat(), + dX, itemView.bottom.toFloat(), backgroundPaint) + + swipeRightIcon?.let { icon -> + val availablePx = dX.toInt() - iconLength + if (availablePx > 0) { + val src = Rect(0, 0, min(availablePx, icon.width), icon.height) + val dstTop = itemView.top + (itemView.bottom - itemView.top - icon.height) / 2 + val dst = Rect(iconLength, dstTop, iconLength + src.width(), dstTop + src.height()) + c.drawBitmap(icon, src, dst, null) + } + } + } else if (dX < 0) { + c.drawRect(itemView.right.toFloat() + dX, itemView.top.toFloat(), + itemView.right.toFloat(), itemView.bottom.toFloat(), backgroundPaint) + + swipeLeftIcon?.let { icon -> + val availablePx = -dX.toInt() - iconLength + if (availablePx > 0) { + val src = Rect(max(0, icon.width - availablePx), 0, icon.width, icon.height) + val dstTop = itemView.top + (itemView.bottom - itemView.top - icon.height) / 2 + val dst = Rect(itemView.right - iconLength - src.width(), dstTop, + itemView.right - iconLength, dstTop + src.height()) + c.drawBitmap(icon, src, dst, null) + } + } + } + + super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) + } + } + + override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { + swipes.onNext(Pair(viewHolder.itemId, direction)) + + // Default: nothing is removed by a swipe, so always animate back to neutral + adapter?.notifyItemChanged(viewHolder.adapterPosition) + } + + /** Convert a drawable resource into a tinted, icon-sized bitmap. */ + protected fun actionBitmap(@androidx.annotation.DrawableRes res: Int?, tint: Int): Bitmap? = + res?.let(context.resources::getDrawable) + ?.apply { setTint(tint) } + ?.toBitmap(iconLength, iconLength) + +} diff --git a/presentation/src/main/java/com/moez/QKSMS/feature/compose/ComposeViewModel.kt b/presentation/src/main/java/com/moez/QKSMS/feature/compose/ComposeViewModel.kt index 069f0bf7..04ffd80c 100644 --- a/presentation/src/main/java/com/moez/QKSMS/feature/compose/ComposeViewModel.kt +++ b/presentation/src/main/java/com/moez/QKSMS/feature/compose/ComposeViewModel.kt @@ -789,10 +789,13 @@ class ComposeViewModel @Inject constructor( .autoDisposable(view.scope()) .subscribe { messageId -> view.showReactionPicker(messageId) } - // Send a reaction: build a quik-encoded body and send it as a normal message. The sent - // message comes back to this device and is parsed as a reaction (isEmojiReaction = true), - // so it is hidden from the conversation automatically. - view.sendReactionIntent + // Send a reaction — from the picker (sendReactionIntent) or the configured default reaction + // on double-tap. Build a quik-encoded body and send it as a normal message; the sent + // message comes back to this device, is parsed as a reaction (isEmojiReaction = true), and + // is hidden from the conversation automatically. + Observable.merge( + view.sendReactionIntent, + view.doubleTapMessageIntent.map { messageId -> Pair(messageId, prefs.defaultReactionEmoji.get()) }) // permission checks touch the UI, so keep them on the main thread .observeOn(AndroidSchedulers.mainThread()) .filter { @@ -822,34 +825,6 @@ class ComposeViewModel @Inject constructor( messageRepo.sendNewMessages(subId, addresses, body, emptyList(), sendAsGroup) } - // Double-tap a message sends the configured default reaction - view.doubleTapMessageIntent - .observeOn(AndroidSchedulers.mainThread()) - .filter { - when { - !permissionManager.isDefaultSms() -> { view.requestDefaultSms(); false } - !permissionManager.hasSendSms() -> { view.requestSmsPermission(); false } - else -> true - } - } - .observeOn(Schedulers.io()) - .withLatestFrom(state, conversation) { messageId, state, conversation -> - Triple(messageId, state, conversation) - } - .autoDisposable(view.scope()) - .subscribe { (messageId, state, conversation) -> - val targetMessage = messageRepo.getMessage(messageId) ?: return@subscribe - val addresses = conversation.recipients.map { it.address } - if (addresses.isEmpty()) return@subscribe - - val subId = state.subscription?.subscriptionId ?: -1 - val sendAsGroup = addresses.size > 1 - val emoji = prefs.defaultReactionEmoji.get() - val body = reactions.buildReactionBody(emoji, targetMessage) - - messageRepo.sendNewMessages(subId, addresses, body, emptyList(), sendAsGroup) - } - // Configurable message swipe actions view.swipeMessageIntent .observeOn(AndroidSchedulers.mainThread()) diff --git a/presentation/src/main/java/com/moez/QKSMS/feature/compose/MessageItemTouchCallback.kt b/presentation/src/main/java/com/moez/QKSMS/feature/compose/MessageItemTouchCallback.kt index f3844773..fa9c5cc8 100644 --- a/presentation/src/main/java/com/moez/QKSMS/feature/compose/MessageItemTouchCallback.kt +++ b/presentation/src/main/java/com/moez/QKSMS/feature/compose/MessageItemTouchCallback.kt @@ -20,141 +20,29 @@ package dev.octoshrimpy.quik.feature.compose import android.content.Context import android.graphics.Bitmap -import android.graphics.Canvas -import android.graphics.Paint -import android.graphics.Rect -import androidx.core.graphics.drawable.toBitmap -import androidx.recyclerview.widget.ItemTouchHelper -import androidx.recyclerview.widget.RecyclerView -import dev.octoshrimpy.quik.R import dev.octoshrimpy.quik.common.util.Colors -import dev.octoshrimpy.quik.common.util.extensions.dpToPx +import dev.octoshrimpy.quik.common.util.SwipeItemTouchCallback +import dev.octoshrimpy.quik.feature.settings.swipe.messageSwipeActionIcon import dev.octoshrimpy.quik.util.Preferences +import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable -import io.reactivex.rxkotlin.Observables -import io.reactivex.rxkotlin.plusAssign -import io.reactivex.schedulers.Schedulers -import io.reactivex.subjects.PublishSubject -import io.reactivex.subjects.Subject import javax.inject.Inject -import kotlin.math.max -import kotlin.math.min class MessageItemTouchCallback @Inject constructor( colors: Colors, disposables: CompositeDisposable, - prefs: Preferences, - private val context: Context -) : ItemTouchHelper.SimpleCallback(0, 0) { + private val prefs: Preferences, + context: Context +) : SwipeItemTouchCallback(colors, disposables, context) { - val swipes: Subject> = PublishSubject.create() + override val noneAction = Preferences.MESSAGE_SWIPE_ACTION_NONE - /** - * Setting the adapter allows us to animate back to the original position - */ - var adapter: RecyclerView.Adapter<*>? = null + override fun rightActionObservable(): Observable = prefs.messageSwipeRight.asObservable() + override fun leftActionObservable(): Observable = prefs.messageSwipeLeft.asObservable() - private val backgroundPaint = Paint() - private var rightAction = 0 - private var swipeRightIcon: Bitmap? = null - private var leftAction = 0 - private var swipeLeftIcon: Bitmap? = null - - private val iconLength = 24.dpToPx(context) - - init { - disposables += colors.themeObservable() - .doOnNext { theme -> backgroundPaint.color = theme.theme } - .subscribeOn(Schedulers.io()) - .subscribe() - - disposables += Observables - .combineLatest(prefs.messageSwipeRight.asObservable(), prefs.messageSwipeLeft.asObservable(), colors.themeObservable() - ) { right, left, theme -> - rightAction = right - swipeRightIcon = iconForAction(right, theme.textPrimary) - leftAction = left - swipeLeftIcon = iconForAction(left, theme.textPrimary) - setDefaultSwipeDirs((if (right == Preferences.MESSAGE_SWIPE_ACTION_NONE) 0 else ItemTouchHelper.RIGHT) - or (if (left == Preferences.MESSAGE_SWIPE_ACTION_NONE) 0 else ItemTouchHelper.LEFT)) - } - .subscribeOn(Schedulers.io()) - .subscribe() - } - - override fun onMove( - recyclerView: RecyclerView, - viewHolder: RecyclerView.ViewHolder, - target: RecyclerView.ViewHolder - ): Boolean { - return false - } - - override fun onChildDraw( - c: Canvas, - recyclerView: RecyclerView, - viewHolder: RecyclerView.ViewHolder, - dX: Float, - dY: Float, - actionState: Int, - isCurrentlyActive: Boolean - ) { - if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { - val itemView = viewHolder.itemView - - if (dX > 0) { - c.drawRect(itemView.left.toFloat(), itemView.top.toFloat(), - dX, itemView.bottom.toFloat(), backgroundPaint) - - swipeRightIcon?.let { icon -> - val availablePx = dX.toInt() - iconLength - if (availablePx > 0) { - val src = Rect(0, 0, min(availablePx, icon.width), icon.height) - val dstTop = itemView.top + (itemView.bottom - itemView.top - icon.height) / 2 - val dst = Rect(iconLength, dstTop, iconLength + src.width(), dstTop + src.height()) - c.drawBitmap(icon, src, dst, null) - } - } - } else if (dX < 0) { - c.drawRect(itemView.right.toFloat() + dX, itemView.top.toFloat(), - itemView.right.toFloat(), itemView.bottom.toFloat(), backgroundPaint) - - swipeLeftIcon?.let { icon -> - val availablePx = -dX.toInt() - iconLength - if (availablePx > 0) { - val src = Rect(max(0, icon.width - availablePx), 0, icon.width, icon.height) - val dstTop = itemView.top + (itemView.bottom - itemView.top - icon.height) / 2 - val dst = Rect(itemView.right - iconLength - src.width(), dstTop, - itemView.right - iconLength, dstTop + src.height()) - c.drawBitmap(icon, src, dst, null) - } - } - } - - super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) - } - } - - override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { - swipes.onNext(Pair(viewHolder.itemId, direction)) - - // Messages are never archived/removed by a swipe, so always snap back to neutral - adapter?.notifyItemChanged(viewHolder.adapterPosition) - } - - private fun iconForAction(action: Int, tint: Int): Bitmap? { - val res = when (action) { - Preferences.MESSAGE_SWIPE_ACTION_REACT -> R.drawable.ic_favorite_black_24dp - Preferences.MESSAGE_SWIPE_ACTION_REPLY -> R.drawable.ic_reply_white_24dp - Preferences.MESSAGE_SWIPE_ACTION_COPY -> R.drawable.ic_content_copy_black_24dp - Preferences.MESSAGE_SWIPE_ACTION_FORWARD -> R.drawable.ic_forward_black_24dp - Preferences.MESSAGE_SWIPE_ACTION_DELETE -> R.drawable.ic_delete_white_24dp - else -> null - } - - return res?.let(context.resources::getDrawable) - ?.apply { setTint(tint) } - ?.toBitmap(iconLength, iconLength) - } + override fun iconForAction(action: Int, tint: Int): Bitmap? = + actionBitmap(messageSwipeActionIcon(action).takeIf { it != 0 }, tint) + // Messages are never archived/removed by a swipe, so the base onSwiped (always snap back to + // neutral) is exactly what we want. } diff --git a/presentation/src/main/java/com/moez/QKSMS/feature/compose/MessagesAdapter.kt b/presentation/src/main/java/com/moez/QKSMS/feature/compose/MessagesAdapter.kt index 7aa89b18..fea6671e 100644 --- a/presentation/src/main/java/com/moez/QKSMS/feature/compose/MessagesAdapter.kt +++ b/presentation/src/main/java/com/moez/QKSMS/feature/compose/MessagesAdapter.kt @@ -123,6 +123,8 @@ class MessagesAdapter @Inject constructor( private var pendingReactionPulse = false private var reactionPulseOrder = 0 private val pulsedReactionIds = mutableSetOf() + private val mainHandler = Handler(Looper.getMainLooper()) + private val clearReactionPulse = Runnable { pendingReactionPulse = false } // click events passed back to compose view model val partClicks: Subject = PublishSubject.create() @@ -148,7 +150,8 @@ class MessagesAdapter @Inject constructor( if (value?.first?.lastMessage?.isEmojiReaction == true && !pendingReactionPulse) { pendingReactionPulse = true reactionPulseOrder = 0 - Handler(Looper.getMainLooper()).postDelayed({ pendingReactionPulse = false }, 1500) + mainHandler.removeCallbacks(clearReactionPulse) + mainHandler.postDelayed(clearReactionPulse, 1500) } updateData(value?.second) diff --git a/presentation/src/main/java/com/moez/QKSMS/feature/conversations/ConversationItemTouchCallback.kt b/presentation/src/main/java/com/moez/QKSMS/feature/conversations/ConversationItemTouchCallback.kt index e32320b7..3736202e 100644 --- a/presentation/src/main/java/com/moez/QKSMS/feature/conversations/ConversationItemTouchCallback.kt +++ b/presentation/src/main/java/com/moez/QKSMS/feature/conversations/ConversationItemTouchCallback.kt @@ -20,146 +20,47 @@ package dev.octoshrimpy.quik.feature.conversations import android.content.Context import android.graphics.Bitmap -import android.graphics.Canvas -import android.graphics.Paint -import android.graphics.Rect -import androidx.core.graphics.drawable.toBitmap import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import dev.octoshrimpy.quik.R import dev.octoshrimpy.quik.common.util.Colors -import dev.octoshrimpy.quik.common.util.extensions.dpToPx +import dev.octoshrimpy.quik.common.util.SwipeItemTouchCallback import dev.octoshrimpy.quik.util.Preferences +import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable -import io.reactivex.rxkotlin.Observables -import io.reactivex.rxkotlin.plusAssign -import io.reactivex.schedulers.Schedulers -import io.reactivex.subjects.PublishSubject -import io.reactivex.subjects.Subject import javax.inject.Inject -import kotlin.math.max -import kotlin.math.min class ConversationItemTouchCallback @Inject constructor( colors: Colors, disposables: CompositeDisposable, - prefs: Preferences, - private val context: Context -) : ItemTouchHelper.SimpleCallback(0, 0) { + private val prefs: Preferences, + context: Context +) : SwipeItemTouchCallback(colors, disposables, context) { - val swipes: Subject> = PublishSubject.create() + override val noneAction = Preferences.SWIPE_ACTION_NONE - /** - * Setting the adapter allows us to animate back to the original position - */ - var adapter: RecyclerView.Adapter<*>? = null + override fun rightActionObservable(): Observable = prefs.swipeRight.asObservable() + override fun leftActionObservable(): Observable = prefs.swipeLeft.asObservable() - private val backgroundPaint = Paint() - private var rightAction = 0 - private var swipeRightIcon: Bitmap? = null - private var leftAction = 0 - private var swipeLeftIcon: Bitmap? = null - - private val iconLength = 24.dpToPx(context) - - init { - disposables += colors.themeObservable() - .doOnNext { theme -> backgroundPaint.color = theme.theme } - .subscribeOn(Schedulers.io()) - .subscribe() - - disposables += Observables - .combineLatest(prefs.swipeRight.asObservable(), prefs.swipeLeft.asObservable(), colors.themeObservable() - ) { right, left, theme -> - rightAction = right - swipeRightIcon = iconForAction(right, theme.textPrimary) - leftAction = left - swipeLeftIcon = iconForAction(left, theme.textPrimary) - setDefaultSwipeDirs((if (right == Preferences.SWIPE_ACTION_NONE) 0 else ItemTouchHelper.RIGHT) - or (if (left == Preferences.SWIPE_ACTION_NONE) 0 else ItemTouchHelper.LEFT)) - } - .subscribeOn(Schedulers.io()) - .subscribe() - } - - override fun onMove( - recyclerView: RecyclerView, - viewHolder: RecyclerView.ViewHolder, - target: RecyclerView.ViewHolder - ): Boolean { - return false - } - - override fun onChildDraw( - c: Canvas, - recyclerView: RecyclerView, - viewHolder: RecyclerView.ViewHolder, - dX: Float, - dY: Float, - actionState: Int, - isCurrentlyActive: Boolean - ) { - if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { - val itemView = viewHolder.itemView - - if (dX > 0) { - c.drawRect(itemView.left.toFloat(), itemView.top.toFloat(), - dX, itemView.bottom.toFloat(), backgroundPaint) - - swipeRightIcon?.let { icon -> - val availablePx = dX.toInt() - iconLength - if (availablePx > 0) { - val src = Rect(0, 0, min(availablePx, icon.width), icon.height) - val dstTop = itemView.top + (itemView.bottom - itemView.top - icon.height) / 2 - val dst = Rect(iconLength, dstTop, iconLength + src.width(), dstTop + src.height()) - c.drawBitmap(icon, src, dst, null) - } - } - } else if (dX < 0) { - c.drawRect(itemView.right.toFloat() + dX, itemView.top.toFloat(), - itemView.right.toFloat(), itemView.bottom.toFloat(), backgroundPaint) - - swipeLeftIcon?.let { icon -> - val availablePx = -dX.toInt() - iconLength - if (availablePx > 0) { - val src = Rect(max(0, icon.width - availablePx), 0, icon.width, icon.height) - val dstTop = itemView.top + (itemView.bottom - itemView.top - icon.height) / 2 - val dst = Rect(itemView.right - iconLength - src.width(), dstTop, - itemView.right - iconLength, dstTop + src.height()) - c.drawBitmap(icon, src, dst, null) - } - } - } - - super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) - } - } + override fun iconForAction(action: Int, tint: Int): Bitmap? = actionBitmap(when (action) { + Preferences.SWIPE_ACTION_ARCHIVE -> R.drawable.ic_archive_white_24dp + Preferences.SWIPE_ACTION_DELETE -> R.drawable.ic_delete_white_24dp + Preferences.SWIPE_ACTION_BLOCK -> R.drawable.ic_block_white_24dp + Preferences.SWIPE_ACTION_CALL -> R.drawable.ic_call_white_24dp + Preferences.SWIPE_ACTION_READ -> R.drawable.ic_check_white_24dp + Preferences.SWIPE_ACTION_UNREAD -> R.drawable.ic_markunread_black_24dp + Preferences.SWIPE_ACTION_SPEAK -> R.drawable.ic_speaker_black_24dp + else -> null + }, tint) override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { swipes.onNext(Pair(viewHolder.itemId, direction)) - // This will trigger the animation back to neutral state + // Archive removes the row, so only animate back to neutral for the other actions val action = if (direction == ItemTouchHelper.RIGHT) rightAction else leftAction if (action != Preferences.SWIPE_ACTION_ARCHIVE) { adapter?.notifyItemChanged(viewHolder.adapterPosition) } } - private fun iconForAction(action: Int, tint: Int): Bitmap? { - val res = when (action) { - Preferences.SWIPE_ACTION_ARCHIVE -> R.drawable.ic_archive_white_24dp - Preferences.SWIPE_ACTION_DELETE -> R.drawable.ic_delete_white_24dp - Preferences.SWIPE_ACTION_BLOCK -> R.drawable.ic_block_white_24dp - Preferences.SWIPE_ACTION_CALL -> R.drawable.ic_call_white_24dp - Preferences.SWIPE_ACTION_READ -> R.drawable.ic_check_white_24dp - Preferences.SWIPE_ACTION_UNREAD -> R.drawable.ic_markunread_black_24dp - Preferences.SWIPE_ACTION_SPEAK -> R.drawable.ic_speaker_black_24dp - else -> null - } - - return res?.let(context.resources::getDrawable) - ?.apply { setTint(tint) } - ?.toBitmap(iconLength, iconLength) - } - -} \ No newline at end of file +} diff --git a/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/BaseSwipeActionsPresenter.kt b/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/BaseSwipeActionsPresenter.kt new file mode 100644 index 00000000..ac7bc043 --- /dev/null +++ b/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/BaseSwipeActionsPresenter.kt @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2017 Moez Bhatti + * + * 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 . + */ +package dev.octoshrimpy.quik.feature.settings.swipe + +import android.content.Context +import androidx.annotation.ArrayRes +import androidx.annotation.DrawableRes +import com.f2prateek.rx.preferences2.Preference +import com.uber.autodispose.android.lifecycle.scope +import com.uber.autodispose.autoDisposable +import dev.octoshrimpy.quik.common.base.QkPresenter +import io.reactivex.rxkotlin.plusAssign + +/** + * Shared presenter for the two "swipe actions" settings screens (conversations and messages). The + * screens are identical apart from which prefs back the left/right action, the labels array, and + * how an action maps to an icon, so subclasses supply only those. + */ +abstract class BaseSwipeActionsPresenter( + context: Context, + @ArrayRes labelsArrayRes: Int, + private val rightPref: Preference, + private val leftPref: Preference +) : QkPresenter(SwipeActionsState()) { + + private val actionLabels = context.resources.getStringArray(labelsArrayRes) + + init { + disposables += rightPref.asObservable() + .subscribe { action -> newState { copy(rightLabel = actionLabels[action], rightIcon = iconForAction(action)) } } + + disposables += leftPref.asObservable() + .subscribe { action -> newState { copy(leftLabel = actionLabels[action], leftIcon = iconForAction(action)) } } + } + + override fun bindIntents(view: SwipeActionsView) { + super.bindIntents(view) + + view.actionClicks() + .map { action -> + when (action) { + SwipeActionsView.Action.RIGHT -> rightPref.get() + SwipeActionsView.Action.LEFT -> leftPref.get() + } + } + .autoDisposable(view.scope()) + .subscribe(view::showSwipeActions) + + view.actionSelected() + .withLatestFrom(view.actionClicks()) { actionId, action -> + when (action) { + SwipeActionsView.Action.RIGHT -> rightPref.set(actionId) + SwipeActionsView.Action.LEFT -> leftPref.set(actionId) + } + } + .autoDisposable(view.scope()) + .subscribe() + } + + @DrawableRes + protected abstract fun iconForAction(action: Int): Int + +} diff --git a/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/MessageSwipeActionsState.kt b/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/MessageSwipeActionIcons.kt similarity index 57% rename from presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/MessageSwipeActionsState.kt rename to presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/MessageSwipeActionIcons.kt index 25a533eb..3aca19fb 100644 --- a/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/MessageSwipeActionsState.kt +++ b/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/MessageSwipeActionIcons.kt @@ -20,11 +20,15 @@ package dev.octoshrimpy.quik.feature.settings.swipe import androidx.annotation.DrawableRes import dev.octoshrimpy.quik.R +import dev.octoshrimpy.quik.util.Preferences -data class MessageSwipeActionsState( - @DrawableRes val rightIcon: Int = R.drawable.ic_favorite_black_24dp, - val rightLabel: String = "", - - @DrawableRes val leftIcon: Int = R.drawable.ic_reply_white_24dp, - val leftLabel: String = "" -) +/** Drawable shown for a message swipe [action], or 0 when there is no icon. */ +@DrawableRes +fun messageSwipeActionIcon(action: Int): Int = when (action) { + Preferences.MESSAGE_SWIPE_ACTION_REACT -> R.drawable.ic_favorite_black_24dp + Preferences.MESSAGE_SWIPE_ACTION_REPLY -> R.drawable.ic_reply_white_24dp + Preferences.MESSAGE_SWIPE_ACTION_COPY -> R.drawable.ic_content_copy_black_24dp + Preferences.MESSAGE_SWIPE_ACTION_FORWARD -> R.drawable.ic_forward_black_24dp + Preferences.MESSAGE_SWIPE_ACTION_DELETE -> R.drawable.ic_delete_white_24dp + else -> 0 +} diff --git a/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/MessageSwipeActionsController.kt b/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/MessageSwipeActionsController.kt index 324c55d2..9b572471 100644 --- a/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/MessageSwipeActionsController.kt +++ b/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/MessageSwipeActionsController.kt @@ -39,7 +39,7 @@ import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.Subject import javax.inject.Inject -class MessageSwipeActionsController : QkController(), MessageSwipeActionsView { +class MessageSwipeActionsController : QkController(), SwipeActionsView { override fun inflateBinding(inflater: LayoutInflater, container: ViewGroup): SwipeActionsControllerBinding = SwipeActionsControllerBinding.inflate(inflater, container, false) @@ -51,7 +51,7 @@ class MessageSwipeActionsController : QkController = PublishSubject.create() + private val actionClicks: Subject = PublishSubject.create() init { appComponent.inject(this) @@ -71,8 +71,8 @@ class MessageSwipeActionsController : QkController = actionClicks + override fun actionClicks(): Observable = actionClicks override fun actionSelected(): Observable = actionsDialog.adapter.menuItemClicks @@ -93,7 +93,7 @@ class MessageSwipeActionsController : QkController(MessageSwipeActionsState()) { - - init { - val actionLabels = context.resources.getStringArray(R.array.settings_message_swipe_actions) - - disposables += prefs.messageSwipeRight.asObservable() - .subscribe { action -> newState { copy(rightLabel = actionLabels[action], rightIcon = iconForAction(action)) } } - - disposables += prefs.messageSwipeLeft.asObservable() - .subscribe { action -> newState { copy(leftLabel = actionLabels[action], leftIcon = iconForAction(action)) } } - } - - override fun bindIntents(view: MessageSwipeActionsView) { - super.bindIntents(view) - - view.actionClicks() - .map { action -> - when (action) { - MessageSwipeActionsView.Action.RIGHT -> prefs.messageSwipeRight.get() - MessageSwipeActionsView.Action.LEFT -> prefs.messageSwipeLeft.get() - } - } - .autoDisposable(view.scope()) - .subscribe(view::showSwipeActions) - - view.actionSelected() - .withLatestFrom(view.actionClicks()) { actionId, action -> - when (action) { - MessageSwipeActionsView.Action.RIGHT -> prefs.messageSwipeRight.set(actionId) - MessageSwipeActionsView.Action.LEFT -> prefs.messageSwipeLeft.set(actionId) - } - } - .autoDisposable(view.scope()) - .subscribe() - } + prefs: Preferences +) : BaseSwipeActionsPresenter( + context, R.array.settings_message_swipe_actions, prefs.messageSwipeRight, prefs.messageSwipeLeft +) { @DrawableRes - private fun iconForAction(action: Int) = when (action) { - Preferences.MESSAGE_SWIPE_ACTION_REACT -> R.drawable.ic_favorite_black_24dp - Preferences.MESSAGE_SWIPE_ACTION_REPLY -> R.drawable.ic_reply_white_24dp - Preferences.MESSAGE_SWIPE_ACTION_COPY -> R.drawable.ic_content_copy_black_24dp - Preferences.MESSAGE_SWIPE_ACTION_FORWARD -> R.drawable.ic_forward_black_24dp - Preferences.MESSAGE_SWIPE_ACTION_DELETE -> R.drawable.ic_delete_white_24dp - else -> 0 - } + override fun iconForAction(action: Int) = messageSwipeActionIcon(action) } diff --git a/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/MessageSwipeActionsView.kt b/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/MessageSwipeActionsView.kt deleted file mode 100644 index 7e2c56f5..00000000 --- a/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/MessageSwipeActionsView.kt +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2017 Moez Bhatti - * - * 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 . - */ -package dev.octoshrimpy.quik.feature.settings.swipe - -import dev.octoshrimpy.quik.common.base.QkViewContract -import io.reactivex.Observable - -interface MessageSwipeActionsView : QkViewContract { - - enum class Action { LEFT, RIGHT } - - fun actionClicks(): Observable - fun actionSelected(): Observable - - fun showSwipeActions(selected: Int) - -} diff --git a/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/SwipeActionsPresenter.kt b/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/SwipeActionsPresenter.kt index 6d4e729a..83e623ff 100644 --- a/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/SwipeActionsPresenter.kt +++ b/presentation/src/main/java/com/moez/QKSMS/feature/settings/swipe/SwipeActionsPresenter.kt @@ -20,55 +20,17 @@ package dev.octoshrimpy.quik.feature.settings.swipe import android.content.Context import androidx.annotation.DrawableRes -import com.uber.autodispose.android.lifecycle.scope -import com.uber.autodispose.autoDisposable import dev.octoshrimpy.quik.R -import dev.octoshrimpy.quik.common.base.QkPresenter import dev.octoshrimpy.quik.util.Preferences -import io.reactivex.rxkotlin.plusAssign import javax.inject.Inject class SwipeActionsPresenter @Inject constructor( context: Context, - private val prefs: Preferences -) : QkPresenter(SwipeActionsState()) { - - init { - val actionLabels = context.resources.getStringArray(R.array.settings_swipe_actions) - - disposables += prefs.swipeRight.asObservable() - .subscribe { action -> newState { copy(rightLabel = actionLabels[action], rightIcon = iconForAction(action)) } } - - disposables += prefs.swipeLeft.asObservable() - .subscribe { action -> newState { copy(leftLabel = actionLabels[action], leftIcon = iconForAction(action)) } } - } - - override fun bindIntents(view: SwipeActionsView) { - super.bindIntents(view) - - view.actionClicks() - .map { action -> - when (action) { - SwipeActionsView.Action.RIGHT -> prefs.swipeRight.get() - SwipeActionsView.Action.LEFT -> prefs.swipeLeft.get() - } - } - .autoDisposable(view.scope()) - .subscribe(view::showSwipeActions) - - view.actionSelected() - .withLatestFrom(view.actionClicks()) { actionId, action -> - when (action) { - SwipeActionsView.Action.RIGHT -> prefs.swipeRight.set(actionId) - SwipeActionsView.Action.LEFT -> prefs.swipeLeft.set(actionId) - } - } - .autoDisposable(view.scope()) - .subscribe() - } + prefs: Preferences +) : BaseSwipeActionsPresenter(context, R.array.settings_swipe_actions, prefs.swipeRight, prefs.swipeLeft) { @DrawableRes - private fun iconForAction(action: Int) = when (action) { + override fun iconForAction(action: Int) = when (action) { Preferences.SWIPE_ACTION_ARCHIVE -> R.drawable.ic_archive_white_24dp Preferences.SWIPE_ACTION_DELETE -> R.drawable.ic_delete_white_24dp Preferences.SWIPE_ACTION_BLOCK -> R.drawable.ic_block_white_24dp @@ -79,4 +41,4 @@ class SwipeActionsPresenter @Inject constructor( else -> 0 } -} \ No newline at end of file +}