From 2eb522f5600700cd7a2b7ff78ef200f3aa4bef83 Mon Sep 17 00:00:00 2001 From: ttabouch12 Date: Tue, 10 Nov 2026 07:45:14 +0300 Subject: [PATCH] SimBridge 2.4.0: Messages actions, faster translation, battery time, auto hotspot Main phone: - Conversations: configurable swipe actions with Undo for delete, multi-select toolbar (pin, archive, read/unread, delete, block), pinned and archived conversations, filters, search inside messages. - Chat: tappable links, e-mail addresses, phone numbers and codes; multi-select on messages (copy, star, forward, details, delete); in-chat search; send later (hold Send) with a queue shown above the composer. - Message store v4: star column, conversation flags, scheduled texts. - Call translation: live captions while speaking, streamed translation, recognition and translation on separate workers, shorter end-of-speech pause for long sentences. - Dashboard shows the SIM phone's time left or time to full. SIM phone: - Hotspot turns on when Wi-Fi stays lost, and after a start without Wi-Fi. - BatteryEstimate: time left from the measured drain, with a unit test. - Removes the duplicate 20 % low-battery alert. Not built yet: written without the Android toolchain in this session. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01A6dfuLYcfqCCHsvZhJ8pKM --- CHANGELOG.md | 29 ++ README.md | 1 + app/build.gradle.kts | 4 +- .../voicesipagent/app/CompanionFeatures.kt | 35 +++ .../voicesipagent/app/GatewayControl.kt | 40 ++- .../voicesipagent/app/GatewayRuntime.kt | 7 +- .../voicesipagent/app/BatteryEstimateTest.kt | 30 +++ phone/build.gradle.kts | 4 +- .../io/github/simbridge/CallTranslator.kt | 93 ++++++- .../kotlin/io/github/simbridge/LinkCore.kt | 17 ++ .../kotlin/io/github/simbridge/LinkService.kt | 4 + .../kotlin/io/github/simbridge/Linkify.kt | 40 +++ .../io/github/simbridge/MessageStore.kt | 101 ++++++- .../io/github/simbridge/PhoneControl.kt | 5 + .../main/kotlin/io/github/simbridge/Prefs.kt | 15 +- .../main/kotlin/io/github/simbridge/Speech.kt | 74 +++++- .../io/github/simbridge/ui/ChatScreen.kt | 190 +++++++++++-- .../simbridge/ui/ConversationsScreen.kt | 251 ++++++++++++++++-- .../io/github/simbridge/ui/SettingsScreen.kt | 28 ++ .../io/github/simbridge/ui/SimPhoneScreen.kt | 10 + phone/src/main/res/values-ar/strings.xml | 35 +++ phone/src/main/res/values-es/strings.xml | 35 +++ phone/src/main/res/values-fa/strings.xml | 35 +++ phone/src/main/res/values-fr/strings.xml | 35 +++ phone/src/main/res/values-ru/strings.xml | 35 +++ phone/src/main/res/values-tr/strings.xml | 35 +++ phone/src/main/res/values/strings.xml | 35 +++ 27 files changed, 1147 insertions(+), 76 deletions(-) create mode 100644 app/src/test/kotlin/io/github/sparkcyf/voicesipagent/app/BatteryEstimateTest.kt create mode 100644 phone/src/main/kotlin/io/github/simbridge/Linkify.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 860e5c2..e514b40 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,34 @@ # Changelog +## SimBridge 2.4.0 + +Update both apps. Pairing is kept. + +### Main phone +- **Messages work like Google Messages / Gmail:** + - **Swipe** a conversation: read / unread, archive, delete or pin. Choose what each direction does + in Settings > Messages. Delete shows **Undo**. + - **Select several** (long-press, then tap): pin, archive, read / unread, delete, block, select all. + - **Pinned** conversations stay on top; **Archived** ones leave the list until a new text arrives. + - **Filters:** All, Unread, Archived, Starred. **Search** also looks inside messages; a + conversation has its own search too. + - **Links, e-mail addresses and phone numbers** in texts open when tapped; one-time codes copy. + - **Long-press a message:** copy, star, forward, details, delete (several at once). + - **Send later:** hold Send and pick a time. Waiting texts show above the keyboard and can be + cancelled; they go out when the SIM phone is reachable. +- **Faster call translation:** + - Words appear **while they are spoken** (cloud speech), and the translation is written out as it + arrives instead of all at once. + - The next sentence is recognized while the previous one is translated. + - Long sentences end on a shorter pause; the default pause is now "Fast". +- **Battery time left** for the SIM phone on the dashboard, from its real drain (or time to full). + +### SIM phone (gateway) +- **Hotspot comes on by itself when Wi-Fi is lost** (with home/work Wi-Fi set up and its switch on), + also after a restart away from home, so the main phone can always reach it. +- Time-left estimate from the measured drain of the current discharge. +- The 20 % low-battery alert was sent twice; now once at 20 % and once at 10 %. + ## SimBridge 2.3.0 Update both apps. Pairing is kept. diff --git a/README.md b/README.md index c3ee9bf..bb00d94 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,7 @@ main phone only ever uses Wi-Fi. See the [disclaimer](DISCLAIMER.md). | 🎧 **HD voice** | 16 kHz wideband audio between the phones (L16), falling back to normal phone quality (G.711) when needed. | | 🔒 **Encrypted and paired** | Pair once by scanning a QR code. Signalling runs over **TLS** pinned to the SIM phone's key, audio over **SRTP**, and every call or text needs the paired password. Mobile-data and internet addresses are refused. | | 💬 **Texts, pictures and group chats** | A Google Messages-style app: conversations, contact photos, bubbles, notifications with **Reply** and **Mark as read**, **Sent / Delivered** reports, picture messages (MMS) and **group texts**. | +| 👆 **Swipe, select, pin, archive, search** | Swipe a conversation (you choose what each direction does), select several for one action, pin, archive, star, search inside messages, tap links and phone numbers, and **send later** by holding Send. | | 📥 **System SMS integration (optional)** | Make SimBridge the **default SMS app**: "Message" buttons in Contacts and other apps open it, the Phone app's *Reply with message* sends through the SIM, and texts are saved to Android's SMS database. Or keep Google Messages as default and just copy relayed texts into it (read-only). | | 📵 **Missed calls while offline** | Calls the SIM phone gets while the main phone is out of reach are added to the Phone app's history with a *Call back* notification. | | 🚫 **Call blocking** | Block numbers (and hidden callers). The SIM phone rejects them before they ring. With SimBridge as the default SMS app, numbers blocked in the Phone app are included too. | diff --git a/app/build.gradle.kts b/app/build.gradle.kts index a9ab8fe..5a12596 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -15,8 +15,8 @@ android { applicationId = "io.github.simbridge.gateway" minSdk = 30 targetSdk = 36 - versionCode = 440 - versionName = "2.3.0" + versionCode = 450 + versionName = "2.4.0" // Filter all transitive JNI libraries as well as PJSIP's own module outputs. ndk { //abiFilters += listOf("arm64-v8a", "x86_64") diff --git a/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/CompanionFeatures.kt b/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/CompanionFeatures.kt index ff80620..17ce5db 100644 --- a/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/CompanionFeatures.kt +++ b/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/CompanionFeatures.kt @@ -133,6 +133,41 @@ object SmsSender { } } +/** + * Time until empty, from the real drain of the current discharge. Percent readings are whole + * numbers, so only the moments the percent drops are used (the battery is then exactly at that + * level), and the rate comes from the last [WINDOW_MS] when that holds enough drops, so a recent + * change in use (hotspot on, a long call) shows up without one noisy step swinging the answer. + */ +object BatteryEstimate { + private const val WINDOW_MS = 3 * 3_600_000L + private const val KEEP_MS = 24 * 3_600_000L + /** (time, percent) at each drop while discharging; times from a clock that runs during sleep. */ + private val drops = ArrayDeque>() + private var lastPct = -1 + + @Synchronized fun note(nowMs: Long, pct: Int, charging: Boolean) { + if (charging || (lastPct >= 0 && pct > lastPct)) drops.clear() + else if (lastPct >= 0 && pct < lastPct) drops.addLast(nowMs to pct) + lastPct = if (charging) -1 else pct + while (drops.isNotEmpty() && nowMs - drops.first().first > KEEP_MS) drops.removeFirst() + } + + /** Minutes until empty, or null until at least 2 % has drained over 10 minutes or more. */ + @Synchronized fun minutesLeft(nowMs: Long): Int? { + val last = drops.lastOrNull() ?: return null + val recent = drops.filter { nowMs - it.first <= WINDOW_MS } + val first = (if (recent.size >= 4) recent else drops).first() + val drained = first.second - last.second + val took = last.first - first.first + if (drained < 2 || took < 10 * 60_000L) return null + val msPerPct = took.toDouble() / drained + // At the last drop the battery was exactly at last.second; time has passed since. + val left = last.second * msPerPct - (nowMs - last.first) + return (left / 60_000).toInt().coerceAtLeast(0) + } +} + object BatteryInfo { data class State(val percent: Int, val charging: Boolean) fun read(ctx: Context): State? { diff --git a/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayControl.kt b/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayControl.kt index be38dfc..f1290f9 100644 --- a/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayControl.kt +++ b/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayControl.kt @@ -196,7 +196,12 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) { @SuppressLint("MissingPermission") fun status(): JSONObject { val o = JSONObject().put("op", "status").put("at", System.currentTimeMillis()) - BatteryInfo.read(app)?.let { o.put("battery", it.percent).put("charging", it.charging) } + BatteryInfo.read(app)?.let { b -> + o.put("battery", b.percent).put("charging", b.charging) + if (b.charging) runCatching { app.getSystemService(android.os.BatteryManager::class.java).computeChargeTimeRemaining() } + .getOrNull()?.takeIf { it > 0 }?.let { o.put("chargeMin", (it / 60_000).toInt()) } + else BatteryEstimate.minutesLeft(android.os.SystemClock.elapsedRealtime())?.let { o.put("batteryMin", it) } + } o.put("powerSaver", rt.companionPower.value).put("quiet", rt.quietFlags.value) o.put("uptimeMin", SystemClock.elapsedRealtime() / 60_000) o.put("version", runCatching { app.packageManager.getPackageInfo(app.packageName, 0).versionName }.getOrNull() ?: "") @@ -421,22 +426,37 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) { private var wifiWatch: android.net.ConnectivityManager.NetworkCallback? = null + /** Called once when the gateway starts. */ + fun start() { + watchWifiLoss() + // After a restart away from every saved place: make sure the main phone can reach us. + main.postDelayed({ rt.worker { hotspotIfNoWifi("started without Wi-Fi") } }, 45_000) + } + + /** "Hotspot when Wi-Fi is lost" is on (the Places switch) and at least one place is saved. */ + private fun autoHotspot(): Boolean = runCatching { + val p = JSONObject(prefs.getString("places", "{}")!!) + p.optBoolean("auto", true) && (p.optJSONArray("list")?.length() ?: 0) > 0 + }.getOrDefault(false) + + private fun hotspotIfNoWifi(why: String) { + if (!autoHotspot() || hotspotOn()) return + val ssid = privilegedRaw("wifi-ssid", "") + if (ssid.startsWith("error") || ssid.isNotEmpty()) return + prefs.edit().remove("at_place").apply() + AppLog.i("control: $why, hotspot on") + privileged("hotspot", "on") + } + private fun watchWifiLoss() { if (wifiWatch != null) return val cm = app.getSystemService(android.net.ConnectivityManager::class.java) val req = android.net.NetworkRequest.Builder().addTransportType(android.net.NetworkCapabilities.TRANSPORT_WIFI).build() wifiWatch = object : android.net.ConnectivityManager.NetworkCallback() { override fun onLost(network: android.net.Network) { - val auto = runCatching { JSONObject(prefs.getString("places", "{}")!!).optBoolean("auto", true) }.getOrDefault(true) - if (prefs.getString("at_place", "").isNullOrEmpty() || !auto) return + if (!autoHotspot()) return // Brief drops happen; only act if Wi-Fi stays gone. - main.postDelayed({ rt.worker { - if (privilegedRaw("wifi-ssid", "").isEmpty()) { - prefs.edit().remove("at_place").apply() - AppLog.i("control: left place, hotspot back on") - privileged("hotspot", "on") - } - } }, 20_000) + main.postDelayed({ rt.worker { hotspotIfNoWifi("Wi-Fi lost") } }, 20_000) } } runCatching { cm.registerNetworkCallback(req, wifiWatch!!) } diff --git a/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayRuntime.kt b/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayRuntime.kt index ab4ecc9..b979a4a 100644 --- a/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayRuntime.kt +++ b/app/src/main/kotlin/io/github/sparkcyf/voicesipagent/app/GatewayRuntime.kt @@ -201,6 +201,7 @@ class GatewayRuntime private constructor(context: Context) { if (started) return@execute started = true watchBattery() + control.start() cellular.onCallsChanged = { snapshot -> _health.update { it.copy(calls = snapshot, inCallServiceBound = CellularEndpoint.isInCallServiceBound) } worker.execute { @@ -911,8 +912,8 @@ class GatewayRuntime private constructor(context: Context) { } /** - * Low-battery alerts to the main phone: once at 20 % and once at 10 % per discharge, reset when - * the charger is connected. Sent as a gateway text, so it waits in the queue if the link is down. + * Feeds the time-left estimate, and sends a second low-battery alert at 10 % (the first, at + * 20 %, comes from [GatewayAlerts]). Reset when the charger is connected. */ private fun watchBattery() { val prefs = app.getSharedPreferences("control", Context.MODE_PRIVATE) @@ -923,11 +924,11 @@ class GatewayRuntime private constructor(context: Context) { if (level < 0) return val pct = level * 100 / scale val plugged = i.getIntExtra(android.os.BatteryManager.EXTRA_PLUGGED, 0) != 0 + BatteryEstimate.note(android.os.SystemClock.elapsedRealtime(), pct, plugged) val warned = prefs.getInt("battery_warned", 100) when { plugged -> if (warned != 100) prefs.edit().putInt("battery_warned", 100).apply() pct <= 10 && warned > 10 -> { prefs.edit().putInt("battery_warned", 10).apply(); alerts.post("🪫 The SIM phone battery is at $pct %. Plug it in soon, or calls and texts stop.") } - pct <= 20 && warned > 20 -> { prefs.edit().putInt("battery_warned", 20).apply(); alerts.post("🔋 The SIM phone battery is at $pct %.") } } } }, android.content.IntentFilter(android.content.Intent.ACTION_BATTERY_CHANGED)) diff --git a/app/src/test/kotlin/io/github/sparkcyf/voicesipagent/app/BatteryEstimateTest.kt b/app/src/test/kotlin/io/github/sparkcyf/voicesipagent/app/BatteryEstimateTest.kt new file mode 100644 index 0000000..5c35d0d --- /dev/null +++ b/app/src/test/kotlin/io/github/sparkcyf/voicesipagent/app/BatteryEstimateTest.kt @@ -0,0 +1,30 @@ +package io.github.sparkcyf.voicesipagent.app + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class BatteryEstimateTest { + private val min = 60_000L + + @Test + fun timeLeftFollowsTheRealDrain() { + var t = 0L + BatteryEstimate.note(t, 80, charging = true) // reset + BatteryEstimate.note(t, 80, charging = false) + // 1 % every 30 minutes, down to 76 %. + for (p in 79 downTo 76) { t += 30 * min; BatteryEstimate.note(t, p, charging = false) } + // 76 % at 30 min each, minus the 10 minutes since the last drop. + assertEquals(76 * 30 - 10, BatteryEstimate.minutesLeft(t + 10 * min)) + } + + @Test + fun noGuessFromOneDropOrAfterCharging() { + BatteryEstimate.note(0, 90, charging = true) + BatteryEstimate.note(0, 90, charging = false) + BatteryEstimate.note(5 * min, 89, charging = false) + assertNull(BatteryEstimate.minutesLeft(6 * min)) + BatteryEstimate.note(7 * min, 89, charging = true) + assertNull(BatteryEstimate.minutesLeft(8 * min)) + } +} diff --git a/phone/build.gradle.kts b/phone/build.gradle.kts index d80998b..7f9727d 100644 --- a/phone/build.gradle.kts +++ b/phone/build.gradle.kts @@ -14,8 +14,8 @@ android { applicationId = "io.github.simbridge" minSdk = 34 targetSdk = 36 - versionCode = 240 - versionName = "2.3.0" + versionCode = 250 + versionName = "2.4.0" } // Same signing source as the gateway app: a git-ignored signing.properties in the project root. val localSigning = Properties().apply { diff --git a/phone/src/main/kotlin/io/github/simbridge/CallTranslator.kt b/phone/src/main/kotlin/io/github/simbridge/CallTranslator.kt index 6857798..1f76428 100644 --- a/phone/src/main/kotlin/io/github/simbridge/CallTranslator.kt +++ b/phone/src/main/kotlin/io/github/simbridge/CallTranslator.kt @@ -29,6 +29,17 @@ object Captions { fun update(id: Long, translated: String) { main.post { val i = lines.indexOfFirst { it.id == id }; if (i >= 0) lines[i] = lines[i].copy(translated = translated) } } + /** The line being spoken right now (one per direction); the final caption replaces it. */ + fun live(fromCaller: Boolean, heard: String, translated: String?) { + main.post { + val c = Caption(if (fromCaller) LIVE_CALLER else LIVE_ME, fromCaller, heard, translated) + val i = lines.indexOfFirst { it.id == c.id } + if (i >= 0) lines[i] = c else lines += c + } + } + fun endLive(fromCaller: Boolean) { main.post { lines.removeAll { it.id == if (fromCaller) LIVE_CALLER else LIVE_ME } } } + private const val LIVE_CALLER = -1L + private const val LIVE_ME = -2L fun say(s: String) { main.post { info = s } } fun showMode(m: TranslateMode) { main.post { mode = m } } fun clear() { main.post { lines.clear(); info = "" } } @@ -44,8 +55,25 @@ class CallTranslator(private val ctx: Context, private val prefs: Prefs, private private val speech = Speech(ctx, prefs) private val callerJobs = Executors.newSingleThreadExecutor() private val myJobs = Executors.newSingleThreadExecutor() - private val theirs = Segmenter(rate, prefs.pauseMs) { pcm -> runCatching { callerJobs.execute { handle(pcm, fromCaller = true) } } } - private val mine = Segmenter(rate, prefs.pauseMs) { pcm -> runCatching { myJobs.execute { handle(pcm, fromCaller = false) } } } + // Translation and speech of a finished line run apart from recognition, so the next + // sentence is already being recognized while this one is translated. + private val callerMt = Executors.newSingleThreadExecutor() + private val myMt = Executors.newSingleThreadExecutor() + // Live captions: what is being said right now, before the sentence ends. + private val liveJobs = Executors.newSingleThreadExecutor() + private val liveBusy = java.util.concurrent.atomic.AtomicBoolean() + private val live = prefs.liveCaptions && speech.canLive + /** Sentence counters (caller, me): a live result for a sentence that already ended is dropped. */ + private val callerGen = AtomicLong() + private val myGen = AtomicLong() + private val theirs = Segmenter(rate, prefs.pauseMs, onPartial = if (live) ({ pcm: ShortArray -> partial(pcm, fromCaller = true) }) else null) { pcm -> + callerGen.incrementAndGet() + runCatching { callerJobs.execute { handle(pcm, fromCaller = true) } } + } + private val mine = Segmenter(rate, prefs.pauseMs, onPartial = if (live) ({ pcm: ShortArray -> partial(pcm, fromCaller = false) }) else null) { pcm -> + myGen.incrementAndGet() + runCatching { myJobs.execute { handle(pcm, fromCaller = false) } } + } /** Translated speech for the caller, and for me, in call-sized frames (up to 60 s each). */ private val toCaller = LinkedBlockingQueue(3000) private val toMe = LinkedBlockingQueue(3000) @@ -87,24 +115,55 @@ class CallTranslator(private val ctx: Context, private val prefs: Prefs, private } fun close() { - callerJobs.shutdownNow(); myJobs.shutdownNow() + callerJobs.shutdownNow(); myJobs.shutdownNow(); callerMt.shutdownNow(); myMt.shutdownNow(); liveJobs.shutdownNow() synchronized(this) { voice?.shutdown(); voice = null } } @Synchronized private fun voice(): Voice = voice ?: Voice(ctx).also { voice = it } + /** Audio thread: the sentence so far. One live job at a time; extra ones are skipped. */ + private fun partial(pcm: ShortArray, fromCaller: Boolean) { + if (mode == TranslateMode.OFF || !liveBusy.compareAndSet(false, true)) return + val gen = if (fromCaller) callerGen else myGen + val g = gen.get() + runCatching { + liveJobs.execute { + try { + val from = if (fromCaller) callerLang else myLang + val to = if (fromCaller) myLang else callerLang + val heard = speech.transcribeLive(pcm, rate, from)?.trim().orEmpty() + if (heard.isNotEmpty() && !Speech.isJunk(heard) && gen.get() == g) { + Captions.live(fromCaller, heard, null) + speech.translateLive(heard, from, to) { soFar -> if (gen.get() == g) Captions.live(fromCaller, heard, soFar) } + } + } finally { + liveBusy.set(false) + } + } + }.onFailure { liveBusy.set(false) } + } + private fun handle(pcm: ShortArray, fromCaller: Boolean) { if (mode == TranslateMode.OFF) return val from = if (fromCaller) callerLang else myLang - val to = if (fromCaller) myLang else callerLang val t0 = System.currentTimeMillis() val heard = speech.transcribe(pcm, rate, from)?.trim().orEmpty() val t1 = System.currentTimeMillis() + Captions.endLive(fromCaller) if (heard.isEmpty() || Speech.isJunk(heard)) return val id = seq.incrementAndGet() Captions.add(Caption(id, fromCaller, heard, null)) // show what was heard right away + val audioMs = pcm.size * 1000L / rate + runCatching { (if (fromCaller) callerMt else myMt).execute { finish(id, heard, fromCaller, audioMs, t1 - t0) } } + } + + /** Translates one recognized line (shown as it is written) and speaks it where asked. */ + private fun finish(id: Long, heard: String, fromCaller: Boolean, audioMs: Long, sttMs: Long) { + val from = if (fromCaller) callerLang else myLang + val to = if (fromCaller) myLang else callerLang + val t1 = System.currentTimeMillis() val context = synchronized(recent) { recent.toList() } - val said = speech.translate(heard, from, to, context)?.trim() + val said = speech.translate(heard, from, to, context) { soFar -> Captions.update(id, soFar) }?.trim() val t2 = System.currentTimeMillis() Captions.update(id, said ?: "(not translated)") synchronized(recent) { recent.addLast(heard); while (recent.size > 3) recent.removeFirst() } @@ -121,7 +180,7 @@ class CallTranslator(private val ctx: Context, private val prefs: Prefs, private if (out != null) enqueue(out, target) } } - Log.i("translate: ${if (fromCaller) "caller" else "me"} audio=${pcm.size * 1000L / rate}ms stt=${t1 - t0}ms mt=${t2 - t1}ms tts=${tts}ms") + Log.i("translate: ${if (fromCaller) "caller" else "me"} audio=${audioMs}ms stt=${sttMs}ms mt=${t2 - t1}ms tts=${tts}ms") } private fun enqueue(out: ShortArray, q: LinkedBlockingQueue) { @@ -137,9 +196,11 @@ class CallTranslator(private val ctx: Context, private val prefs: Prefs, private /** * Cuts 20 ms frames into utterances by loudness: starts on speech (with 300 ms lead-in), - * ends after [pauseMs] of quiet or 15 s. The noise floor adapts so line hiss doesn't count as speech. + * ends after [pauseMs] of quiet (350 ms once a sentence runs past 4 s) or 12 s. The noise floor adapts so line hiss doesn't count as speech. */ -class Segmenter(private val rate: Int, private val pauseMs: Int, private val onUtterance: (ShortArray) -> Unit) { +class Segmenter(private val rate: Int, private val pauseMs: Int, private val onPartial: ((ShortArray) -> Unit)? = null, + private val onUtterance: (ShortArray) -> Unit) { + private var nextPartialMs = FIRST_PARTIAL_MS private val lead = ArrayDeque() private val out = ArrayList() private var speaking = false @@ -156,15 +217,21 @@ class Segmenter(private val rate: Int, private val pauseMs: Int, private val onU if (!loud) floor = floor * 0.95 + level * 0.05 lead.addLast(f) while (lead.size * ms > 300) lead.removeFirst() - if (loud) { speaking = true; loudMs = ms; quietMs = 0; out.addAll(lead); lead.clear() } + if (loud) { speaking = true; loudMs = ms; quietMs = 0; nextPartialMs = FIRST_PARTIAL_MS; out.addAll(lead); lead.clear() } return } out += f if (loud) { loudMs += ms; quietMs = 0 } else quietMs += ms - if (quietMs >= pauseMs || out.size * ms >= 15_000) { + val lenMs = out.size * ms + // A long sentence ends on a shorter pause, so its translation doesn't wait for a full stop. + val pause = if (lenMs > 4000) minOf(pauseMs, 350) else pauseMs + if (quietMs >= pause || lenMs >= 12_000) { if (loudMs >= 300) onUtterance(Pcm.concat(out)) speaking = false out.clear() + } else if (onPartial != null && loud && lenMs >= nextPartialMs) { + nextPartialMs = lenMs + PARTIAL_EVERY_MS + onPartial(Pcm.concat(out)) } } @@ -174,7 +241,11 @@ class Segmenter(private val rate: Int, private val pauseMs: Int, private val onU return sqrt(s / max(1, f.size)) } - private companion object { const val MIN_LEVEL = 300.0 } + private companion object { + const val MIN_LEVEL = 300.0 + const val FIRST_PARTIAL_MS = 2000 + const val PARTIAL_EVERY_MS = 3000 + } } /** Small PCM16 helpers: join, resample, WAV in and out. */ diff --git a/phone/src/main/kotlin/io/github/simbridge/LinkCore.kt b/phone/src/main/kotlin/io/github/simbridge/LinkCore.kt index eaa0f36..2b632c4 100644 --- a/phone/src/main/kotlin/io/github/simbridge/LinkCore.kt +++ b/phone/src/main/kotlin/io/github/simbridge/LinkCore.kt @@ -335,6 +335,23 @@ class LinkCore(val context: Context) { SystemSms.delete(context, store.deleteConversation(key)) } + /** Deletes single messages here, their files, and their copies in the system Messages app. */ + fun deleteMessages(ids: Collection) { + val sys = ids.mapNotNull { store.systemId(it) } + store.deleteMessages(ids).forEach { if (it.att.isNotBlank()) Mms.deleteFiles(context, it.att) } + SystemSms.delete(context, sys) + } + + /** Sends the scheduled texts that are due. Waits while the SIM phone is out of reach. */ + fun sendDueScheduled() { + if (status.value.state != LinkState.CONNECTED) return + store.scheduled(System.currentTimeMillis()).forEach { s -> + store.unschedule(s.id) + sendText(s.address, s.body, if (s.sim > 0) s.sim else simFor(s.address)) + Log.i("scheduled text sent") + } + } + /** Marks a conversation read here and in the system Messages app. */ fun markRead(key: String) { SystemSms.markRead(context, store.markRead(key)) diff --git a/phone/src/main/kotlin/io/github/simbridge/LinkService.kt b/phone/src/main/kotlin/io/github/simbridge/LinkService.kt index 889ec04..f7043fc 100644 --- a/phone/src/main/kotlin/io/github/simbridge/LinkService.kt +++ b/phone/src/main/kotlin/io/github/simbridge/LinkService.kt @@ -56,6 +56,9 @@ class LinkService : Service() { val nm = getSystemService(NotificationManager::class.java) core.status.collect { nm.notify(Notifier.ID_STATUS, core.notifier.statusNotification(it)) } } + if (schedJob == null) schedJob = scope.launch { + while (true) { runCatching { core.sendDueScheduled() }; kotlinx.coroutines.delay(20_000) } + } if (widgetJob == null) widgetJob = scope.launch { kotlinx.coroutines.flow.combine(core.status, core.control.status) { _, _ -> }.collect { LinkWidget.update(this@LinkService) } } @@ -81,6 +84,7 @@ class LinkService : Service() { private var placesJob: kotlinx.coroutines.Job? = null private var widgetJob: kotlinx.coroutines.Job? = null + private var schedJob: kotlinx.coroutines.Job? = null override fun onDestroy() { if (instance === this) instance = null diff --git a/phone/src/main/kotlin/io/github/simbridge/Linkify.kt b/phone/src/main/kotlin/io/github/simbridge/Linkify.kt new file mode 100644 index 0000000..455e790 --- /dev/null +++ b/phone/src/main/kotlin/io/github/simbridge/Linkify.kt @@ -0,0 +1,40 @@ +package io.github.simbridge + +/** Finds the tappable parts of a text: web links, e-mail addresses, phone numbers and one-time codes. */ +object Linkify { + enum class Kind { URL, EMAIL, PHONE, CODE } + + /** [target] is what opens (a full URL, mailto: or tel:) or, for a code, what is copied. */ + data class Span(val start: Int, val end: Int, val kind: Kind, val target: String) + + private val EMAIL = Regex("[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,}") + private const val TLDS = "com|net|org|io|co|me|app|dev|info|biz|gov|edu|ly|gl|tr|uk|de|fr|es|ru|ir|ae|sa|eu|us|ca|in|nl|it" + private val URL = Regex( + "(?i)(?\"]+" + // explicit links + "|[a-z0-9-]+(?:\\.[a-z0-9-]+)*\\.(?:$TLDS)(?![a-z0-9-])(?:/[^\\s<>\"]*)?" + // bank.com.tr, bit.ly/x + "|[a-z0-9-]+(?:\\.[a-z0-9-]+)+/[^\\s<>\"]+)") // any.host/path + private val PHONE = Regex("(? { + val out = ArrayList() + fun free(s: Int, e: Int) = out.none { s < it.end && it.start < e } + EMAIL.findAll(text).forEach { m -> out += Span(m.range.first, m.range.last + 1, Kind.EMAIL, "mailto:" + m.value) } + URL.findAll(text).forEach { m -> + // Sentence punctuation after a link is not part of it. + val v = m.value.trimEnd('.', ',', ';', ':', '!', '?', ')', ']', '\'', '"') + val s = m.range.first; val e = s + v.length + if (v.length > 3 && free(s, e)) out += Span(s, e, Kind.URL, if (v.startsWith("http", true)) v else "https://$v") + } + PHONE.findAll(text).forEach { m -> + val digits = m.value.count { it.isDigit() } + val s = m.range.first; val e = m.range.last + 1 + if (digits in 8..15 && free(s, e)) out += Span(s, e, Kind.PHONE, "tel:" + m.value.filter { it.isDigit() || it == '+' }) + } + Otp.find(text)?.let { code -> + // The code may be written "123 456" in the text. + val m = Regex("(? = _version @@ -42,8 +47,17 @@ class MessageStore(context: Context) : SQLiteOpenHelper(context, "messages.db", override fun onCreate(db: SQLiteDatabase) { db.execSQL("CREATE TABLE m (id INTEGER PRIMARY KEY AUTOINCREMENT, k TEXT NOT NULL, addr TEXT NOT NULL, " + "body TEXT NOT NULL, ts INTEGER NOT NULL, out INTEGER NOT NULL, status INTEGER NOT NULL, rd INTEGER NOT NULL, " + - "sys INTEGER NOT NULL DEFAULT 0, sim INTEGER NOT NULL DEFAULT 0, att TEXT NOT NULL DEFAULT '')") + "sys INTEGER NOT NULL DEFAULT 0, sim INTEGER NOT NULL DEFAULT 0, att TEXT NOT NULL DEFAULT '', " + + "star INTEGER NOT NULL DEFAULT 0)") db.execSQL("CREATE INDEX m_k ON m(k, ts)") + extraTables(db) + } + + /** Per-conversation flags (pinned, archived) and texts scheduled for later. */ + private fun extraTables(db: SQLiteDatabase) { + db.execSQL("CREATE TABLE IF NOT EXISTS c (k TEXT PRIMARY KEY, pinned INTEGER NOT NULL DEFAULT 0, archived INTEGER NOT NULL DEFAULT 0)") + db.execSQL("CREATE TABLE IF NOT EXISTS sched (id INTEGER PRIMARY KEY AUTOINCREMENT, addr TEXT NOT NULL, body TEXT NOT NULL, " + + "at INTEGER NOT NULL, sim INTEGER NOT NULL DEFAULT 0)") } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { @@ -52,6 +66,10 @@ class MessageStore(context: Context) : SQLiteOpenHelper(context, "messages.db", db.execSQL("ALTER TABLE m ADD COLUMN sim INTEGER NOT NULL DEFAULT 0") db.execSQL("ALTER TABLE m ADD COLUMN att TEXT NOT NULL DEFAULT ''") } + if (oldVersion < 4) { + db.execSQL("ALTER TABLE m ADD COLUMN star INTEGER NOT NULL DEFAULT 0") + extraTables(db) + } } /** Remembers the matching row in Android's SMS database (see [SystemSms]). */ @@ -80,6 +98,8 @@ class MessageStore(context: Context) : SQLiteOpenHelper(context, "messages.db", put("out", if (outgoing) 1 else 0); put("status", status); put("rd", if (read) 1 else 0) put("sim", sim); put("att", att) }) + // A new incoming text brings an archived conversation back to the list. + if (!outgoing) writableDatabase.execSQL("UPDATE c SET archived=0 WHERE k=?", arrayOf(keyOf(address))) changed() return id } @@ -126,11 +146,79 @@ class MessageStore(context: Context) : SQLiteOpenHelper(context, "messages.db", while (it.moveToNext()) sys += it.getLong(0) } writableDatabase.delete("m", "k=?", arrayOf(key)) + writableDatabase.delete("c", "k=?", arrayOf(key)) changed() return sys } + // ------------------------------------------------------------ flags, single messages, search + + private fun flag(keys: Collection, column: String, on: Boolean) { + val db = writableDatabase + keys.forEach { k -> + db.execSQL("INSERT OR IGNORE INTO c (k) VALUES (?)", arrayOf(k)) + db.execSQL("UPDATE c SET $column=? WHERE k=?", arrayOf(if (on) 1 else 0, k)) + } + changed() + } + + fun setPinned(keys: Collection, on: Boolean) = flag(keys, "pinned", on) + fun setArchived(keys: Collection, on: Boolean) = flag(keys, "archived", on) + + /** Marks a conversation unread again (its latest incoming message). */ + fun markUnread(key: String) { + writableDatabase.execSQL("UPDATE m SET rd=0 WHERE id=(SELECT MAX(id) FROM m WHERE k=? AND out=0)", arrayOf(key)) + changed() + } + + fun setStarred(ids: Collection, on: Boolean) { + ids.forEach { writableDatabase.execSQL("UPDATE m SET star=? WHERE id=?", arrayOf(if (on) 1 else 0, it)) } + changed() + } + + /** Deletes single messages; returns their rows (for the system SMS copies and attachment files). */ + fun deleteMessages(ids: Collection): List { + val gone = ids.mapNotNull { get(it) } + ids.forEach { writableDatabase.delete("m", "id=?", arrayOf(it.toString())) } + changed() + return gone + } + + /** Messages containing [query] (newest first), or the starred ones when [starred]. */ + fun search(query: String, starred: Boolean = false, limit: Int = 60): List { + val like = "%" + query.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%" + val where = if (starred) "star=1 AND body LIKE ? ESCAPE '\\'" else "body LIKE ? ESCAPE '\\'" + return readableDatabase.rawQuery("SELECT * FROM m WHERE $where ORDER BY ts DESC LIMIT $limit", arrayOf(like)).use { c -> + ArrayList().apply { while (c.moveToNext()) add(c.msg()) } + } + } + + // ------------------------------------------------------------ scheduled texts + + fun schedule(address: String, body: String, at: Long, sim: Int): Long { + val id = writableDatabase.insert("sched", null, ContentValues().apply { + put("addr", address); put("body", body); put("at", at); put("sim", sim) + }) + changed() + return id + } + + /** Scheduled texts, soonest first; only those due by [dueBy] when given. */ + fun scheduled(dueBy: Long = Long.MAX_VALUE): List = + readableDatabase.rawQuery("SELECT id, addr, body, at, sim FROM sched WHERE at<=? ORDER BY at", arrayOf(dueBy.toString())).use { c -> + ArrayList().apply { while (c.moveToNext()) add(Scheduled(c.getLong(0), c.getString(1), c.getString(2), c.getLong(3), c.getInt(4))) } + } + + fun unschedule(id: Long) { + writableDatabase.delete("sched", "id=?", arrayOf(id.toString())) + changed() + } + fun conversations(): List { + val flags = HashMap>() + readableDatabase.rawQuery("SELECT k, pinned, archived FROM c WHERE pinned=1 OR archived=1", null).use { + while (it.moveToNext()) flags[it.getString(0)] = (it.getInt(1) == 1) to (it.getInt(2) == 1) + } val unread = HashMap() readableDatabase.rawQuery("SELECT k, COUNT(*) FROM m WHERE rd=0 GROUP BY k", null).use { while (it.moveToNext()) unread[it.getString(0)] = it.getInt(1) @@ -140,10 +228,12 @@ class MessageStore(context: Context) : SQLiteOpenHelper(context, "messages.db", "ON m.id = t.mid ORDER BY m.ts DESC", null).use { while (it.moveToNext()) { val msg = it.msg() - out += Conversation(msg.key, msg.address, msg, unread[msg.key] ?: 0) + val f = flags[msg.key] + out += Conversation(msg.key, msg.address, msg, unread[msg.key] ?: 0, f?.first == true, f?.second == true) } } - return out + // Pinned conversations first; the newest-first order is kept inside each group. + return out.sortedByDescending { it.pinned } } fun thread(key: String): List { @@ -168,6 +258,7 @@ class MessageStore(context: Context) : SQLiteOpenHelper(context, "messages.db", read = getInt(getColumnIndexOrThrow("rd")) == 1, sim = getInt(getColumnIndexOrThrow("sim")), att = getString(getColumnIndexOrThrow("att")) ?: "", + starred = getInt(getColumnIndexOrThrow("star")) == 1, ) companion object { diff --git a/phone/src/main/kotlin/io/github/simbridge/PhoneControl.kt b/phone/src/main/kotlin/io/github/simbridge/PhoneControl.kt index 2ddb03b..11a995b 100644 --- a/phone/src/main/kotlin/io/github/simbridge/PhoneControl.kt +++ b/phone/src/main/kotlin/io/github/simbridge/PhoneControl.kt @@ -23,6 +23,9 @@ data class GatewayStatus( val at: Long, val battery: Int?, val charging: Boolean, + /** Minutes until empty (from real drain) or until full; null while not known yet. */ + val batteryMin: Int? = null, + val chargeMin: Int? = null, val powerSaver: Boolean, val dataOn: Boolean, val hotspot: Boolean, @@ -44,6 +47,8 @@ data class GatewayStatus( at = System.currentTimeMillis(), battery = if (o.has("battery")) o.optInt("battery") else null, charging = o.optBoolean("charging"), + batteryMin = if (o.has("batteryMin")) o.optInt("batteryMin") else null, + chargeMin = if (o.has("chargeMin")) o.optInt("chargeMin") else null, powerSaver = o.optBoolean("powerSaver"), dataOn = o.optBoolean("dataOn"), hotspot = o.optBoolean("hotspot"), diff --git a/phone/src/main/kotlin/io/github/simbridge/Prefs.kt b/phone/src/main/kotlin/io/github/simbridge/Prefs.kt index e140297..bb1578b 100644 --- a/phone/src/main/kotlin/io/github/simbridge/Prefs.kt +++ b/phone/src/main/kotlin/io/github/simbridge/Prefs.kt @@ -89,6 +89,14 @@ class Prefs(context: Context) { get() = p.getBoolean("places_auto", false) set(v) = p.edit().putBoolean("places_auto", v).apply() + /** What a swipe on a conversation does: "read", "archive", "delete", "pin" or "none". */ + var swipeRight: String + get() = p.getString("swipe_right", "read")!! + set(v) = p.edit().putString("swipe_right", v).apply() + var swipeLeft: String + get() = p.getString("swipe_left", "archive")!! + set(v) = p.edit().putString("swipe_left", v).apply() + /** Copy one-time codes from texts to the clipboard automatically. */ var otpCopy: Boolean get() = p.getBoolean("otp_copy", true) @@ -185,9 +193,14 @@ class Prefs(context: Context) { /** Translation: quiet time that ends a sentence. Shorter is faster but may split sentences. */ var pauseMs: Int - get() = p.getInt("pause_ms", 600) + get() = p.getInt("pause_ms", 450) set(v) = p.edit().putInt("pause_ms", v).apply() + /** Translation: show words while they are still being spoken (cloud speech only). */ + var liveCaptions: Boolean + get() = p.getBoolean("live_captions", true) + set(v) = p.edit().putBoolean("live_captions", v).apply() + /** Translation: also read the caller's translated words to me in the earpiece. */ var speakToMe: Boolean get() = p.getBoolean("speak_to_me", false) diff --git a/phone/src/main/kotlin/io/github/simbridge/Speech.kt b/phone/src/main/kotlin/io/github/simbridge/Speech.kt index 6b5538d..0f1501b 100644 --- a/phone/src/main/kotlin/io/github/simbridge/Speech.kt +++ b/phone/src/main/kotlin/io/github/simbridge/Speech.kt @@ -53,6 +53,40 @@ object Langs { */ class Speech(private val ctx: Context, private val prefs: Prefs) { private val cloudSpeech get() = !prefs.translateOnDevice && prefs.groqKey.isNotBlank() + /** Live (while-speaking) captions need the cloud recognizer: the on-device one is too slow for it. */ + val canLive get() = cloudSpeech + + // Live captions are extras: they stay inside a share of the free tier's requests per minute + // and stop for a while after any failure, so the final captions always get through. + private val speechCalls = ArrayDeque() + @Volatile private var liveOffUntil = 0L + + @Synchronized private fun noteSpeechCall(): Int { + val now = System.currentTimeMillis() + speechCalls.addLast(now) + while (speechCalls.isNotEmpty() && now - speechCalls.first() > 60_000) speechCalls.removeFirst() + return speechCalls.size + } + + @Synchronized private fun liveBudget(): Boolean { + val now = System.currentTimeMillis() + return now > liveOffUntil && speechCalls.count { now - it <= 60_000 } < LIVE_PER_MIN + } + + /** Words so far of a sentence still being spoken; null when skipped or failed (never falls back). */ + fun transcribeLive(pcm: ShortArray, rate: Int, lang: String): String? { + if (!cloudSpeech || !liveBudget()) return null + return runCatching { groqTranscribe(pcm, rate, lang) } + .onFailure { liveOffUntil = System.currentTimeMillis() + 30_000; Log.w("translate: live caption skipped (${it.message})") }.getOrNull() + } + + /** Cloud translation of a live line, streamed into [onPartial]; quiet on failure. */ + fun translateLive(text: String, from: String, to: String, onPartial: (String) -> Unit) { + val e = prefs.translateEngine + val key = prefs.keyFor(e) + if (prefs.translateOnDevice || e == Engine.ON_DEVICE || key.isBlank() || !liveBudget()) return + runCatching { chat(e, key, text, from, to, emptyList(), onPartial) }.onFailure { liveOffUntil = System.currentTimeMillis() + 30_000 } + } fun transcribe(pcm: ShortArray, rate: Int, lang: String): String? { if (cloudSpeech) runCatching { return groqTranscribe(pcm, rate, lang) } @@ -60,11 +94,18 @@ class Speech(private val ctx: Context, private val prefs: Prefs) { return OnDeviceStt.transcribe(ctx, pcm, rate, lang) } - /** [context]: the last few lines of the call, so short fragments translate correctly. */ - fun translate(text: String, from: String, to: String, context: List): String? { + /** + * [context]: the last few lines of the call, so short fragments translate correctly. + * [onPartial] gets the translation as it is written (cloud engines stream it word by word). + */ + fun translate(text: String, from: String, to: String, context: List, onPartial: ((String) -> Unit)? = null): String? { val e = prefs.translateEngine val key = prefs.keyFor(e) - if (!prefs.translateOnDevice && e != Engine.ON_DEVICE && key.isNotBlank()) runCatching { return chat(e, key, text, from, to, context) } + if (!prefs.translateOnDevice && e != Engine.ON_DEVICE && key.isNotBlank()) runCatching { + // Streamed first; if a provider's stream is odd, ask once more the plain way. + return if (onPartial == null) chat(e, key, text, from, to, context, null) + else runCatching { chat(e, key, text, from, to, context, onPartial) }.getOrElse { chat(e, key, text, from, to, context, null) } + } .onFailure { Log.w("translate: cloud translation failed, using on-device", it); Captions.say("Cloud translation failed (${it.message}); using on-device") } return OfflineTranslate.translate(ctx, text, from, to) } @@ -85,6 +126,7 @@ class Speech(private val ctx: Context, private val prefs: Prefs) { } private fun groqTranscribe(pcm: ShortArray, rate: Int, lang: String): String { + noteSpeechCall() val boundary = "simbridge" + System.nanoTime() val c = post(Engine.GROQ_120B.base + "audio/transcriptions", prefs.groqKey, "multipart/form-data; boundary=$boundary") c.outputStream.use { o -> @@ -101,7 +143,8 @@ class Speech(private val ctx: Context, private val prefs: Prefs) { return JSONObject(read(c)).getString("text") } - private fun chat(e: Engine, key: String, text: String, from: String, to: String, context: List): String { + private fun chat(e: Engine, key: String, text: String, from: String, to: String, context: List, + onPartial: ((String) -> Unit)?): String { val model = prefs.translateModel.ifBlank { e.model } val earlier = if (context.isEmpty()) "" else "\nEarlier in this call (context only, do not translate):\n" + context.joinToString("\n") @@ -115,8 +158,29 @@ class Speech(private val ctx: Context, private val prefs: Prefs) { "keep meaning and tone, fix obvious recognition mistakes, keep names and numbers. Reply with the translation only.$earlier")) .put(JSONObject().put("role", "user").put("content", text))) if (model.contains("gpt-oss")) body.put("reasoning_effort", "low") + if (onPartial != null) body.put("stream", true) val c = post(e.base + "chat/completions", key, "application/json") c.outputStream.use { it.write(body.toString().toByteArray()) } + if (onPartial != null) { + // Server-sent events: one "data: {json}" line per piece of text, then "data: [DONE]". + val code = c.responseCode + if (code !in 200..299) throw IOException("HTTP $code ${c.errorStream?.use { it.bufferedReader().readText() }.orEmpty().take(160)}") + val sb = StringBuilder() + c.inputStream.bufferedReader().use { r -> + while (true) { + val line = r.readLine() ?: break + if (!line.startsWith("data:")) continue + val data = line.substring(5).trim() + if (data == "[DONE]") break + val delta = runCatching { JSONObject(data).getJSONArray("choices").getJSONObject(0).optJSONObject("delta") }.getOrNull() ?: continue + if (delta.isNull("content")) continue + val piece = delta.optString("content") + if (piece.isNotEmpty()) { sb.append(piece); onPartial(sb.toString()) } + } + } + if (sb.isBlank()) throw IOException("empty stream") + return sb.toString() + } return JSONObject(read(c)).getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content") } @@ -141,6 +205,8 @@ class Speech(private val ctx: Context, private val prefs: Prefs) { } companion object { + private const val LIVE_PER_MIN = 12 + /** Lines Whisper invents from silence or noise (video-subtitle habits). */ private val junk = listOf("altyazı", "izlediğiniz için", "abone ol", "thank you for watching", "thanks for watching", "subtitles by", "amara.org") diff --git a/phone/src/main/kotlin/io/github/simbridge/ui/ChatScreen.kt b/phone/src/main/kotlin/io/github/simbridge/ui/ChatScreen.kt index a98c887..2bf0104 100644 --- a/phone/src/main/kotlin/io/github/simbridge/ui/ChatScreen.kt +++ b/phone/src/main/kotlin/io/github/simbridge/ui/ChatScreen.kt @@ -1,5 +1,22 @@ package io.github.simbridge.ui +import androidx.compose.foundation.background +import androidx.compose.material.icons.automirrored.filled.Forward +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.Schedule +import androidx.compose.material.icons.filled.Star +import androidx.compose.material.icons.outlined.Delete +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material.icons.outlined.StarBorder +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.TextButton +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLinkStyles +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.style.TextDecoration import io.github.simbridge.R import androidx.compose.ui.res.stringResource import android.Manifest @@ -43,7 +60,6 @@ import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.FilledIconButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme @@ -89,6 +105,11 @@ fun ChatScreen(core: LinkCore, key: String, address: String, initialDraft: Strin var msgs by remember { mutableStateOf(emptyList()) } var draft by remember(key) { mutableStateOf(initialDraft) } var menu by remember { mutableStateOf(false) } + // Long-press a bubble to select it; then tap others (copy, star, forward, details, delete). + var picked by remember(key) { mutableStateOf(emptySet()) } + var details by remember { mutableStateOf(null) } + var find by remember(key) { mutableStateOf(null) } + var scheduleAsk by remember { mutableStateOf(false) } var pending by remember(key) { mutableStateOf(emptyList()) } val group = io.github.simbridge.Group.isGroup(address) val picker = androidx.activity.compose.rememberLauncherForActivityResult( @@ -111,10 +132,33 @@ fun ChatScreen(core: LinkCore, key: String, address: String, initialDraft: Strin if (msgs.any { !it.read }) withContext(Dispatchers.IO) { core.markRead(key) } core.notifier.cancel(key) } - val items = remember(msgs) { buildItems(msgs) } + val items = remember(msgs, find) { buildItems(find?.takeIf { it.isNotBlank() }?.let { q -> msgs.filter { it.body.contains(q, true) } } ?: msgs) } + val scheduled = remember(version, key) { core.store.scheduled().filter { io.github.simbridge.MessageStore.keyOf(it.address) == key } } + androidx.activity.compose.BackHandler(enabled = picked.isNotEmpty() || find != null) { picked = emptySet(); find = null } Scaffold( topBar = { + if (picked.isNotEmpty()) { + val sel = msgs.filter { it.id in picked } + TopAppBar( + navigationIcon = { IconButton({ picked = emptySet() }) { Icon(Icons.Filled.Close, stringResource(R.string.cancel)) } }, + title = { Text(picked.size.toString()) }, + actions = { + IconButton({ copy(ctx, sel.joinToString("\n") { it.body }); picked = emptySet() }) { + Icon(Icons.Filled.ContentCopy, stringResource(R.string.copy)) } + IconButton({ core.store.setStarred(picked, !sel.all { it.starred }); picked = emptySet() }) { + Icon(if (sel.all { it.starred }) Icons.Filled.Star else Icons.Outlined.StarBorder, stringResource(R.string.act_star)) } + IconButton({ + runCatching { ctx.startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain") + .putExtra(Intent.EXTRA_TEXT, sel.joinToString("\n") { it.body }), null)) } + picked = emptySet() + }) { Icon(Icons.AutoMirrored.Filled.Forward, stringResource(R.string.act_forward)) } + if (sel.size == 1) IconButton({ details = sel.first(); picked = emptySet() }) { + Icon(Icons.Outlined.Info, stringResource(R.string.act_details)) } + IconButton({ core.deleteMessages(picked); picked = emptySet() }) { Icon(Icons.Outlined.Delete, stringResource(R.string.delete)) } + }, + ) + } else Column { TopAppBar( navigationIcon = { IconButton(onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.back)) } }, title = { @@ -132,6 +176,7 @@ fun ChatScreen(core: LinkCore, key: String, address: String, initialDraft: Strin if (!gateway && !group && address.any { it.isDigit() }) IconButton({ call(ctx, address) }) { Icon(Icons.Filled.Call, stringResource(R.string.call)) } IconButton({ menu = true }) { Icon(Icons.Filled.MoreVert, stringResource(R.string.more)) } DropdownMenu(menu, { menu = false }) { + DropdownMenuItem(text = { Text(stringResource(R.string.search_chat)) }, onClick = { menu = false; find = "" }) DropdownMenuItem(text = { Text(stringResource(R.string.copy_number)) }, onClick = { menu = false; copy(ctx, address) }) DropdownMenuItem(text = { Text(stringResource(R.string.delete_conv)) }, onClick = { menu = false; core.deleteConversation(key); onBack() @@ -140,9 +185,26 @@ fun ChatScreen(core: LinkCore, key: String, address: String, initialDraft: Strin }, colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.surface), ) + find?.let { q -> + TextField(q, { find = it }, singleLine = true, modifier = Modifier.fillMaxWidth(), + placeholder = { Text(stringResource(R.string.search_chat)) }, + trailingIcon = { IconButton({ find = null }) { Icon(Icons.Filled.Close, stringResource(R.string.clear)) } }) + } + } }, bottomBar = { - if (!gateway) Composer(draft, { draft = it }, connected = status.state == LinkState.CONNECTED, + if (!gateway) Column { + scheduled.forEach { sc -> + Row(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainerHigh).padding(start = 16.dp), + verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Filled.Schedule, null, Modifier.size(18.dp), tint = MaterialTheme.colorScheme.primary) + Text(scheduleTime(sc.at) + " · " + sc.body, Modifier.weight(1f).padding(horizontal = 8.dp), + style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis) + IconButton({ core.store.unschedule(sc.id) }) { Icon(Icons.Filled.Close, stringResource(R.string.cancel)) } + } + } + Composer(draft, { draft = it }, connected = status.state == LinkState.CONNECTED, + onSchedule = { if (draft.isNotBlank() && pending.isEmpty()) scheduleAsk = true }, pending = pending, onAttach = { picker.launch(androidx.activity.result.PickVisualMediaRequest( androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia.ImageOnly)) @@ -153,6 +215,7 @@ fun ChatScreen(core: LinkCore, key: String, address: String, initialDraft: Strin text.isNotEmpty() -> { core.sendText(address, text); draft = "" } } } + } }, ) { pad -> LazyColumn( @@ -167,18 +230,107 @@ fun ChatScreen(core: LinkCore, key: String, address: String, initialDraft: Strin Text(dayHeader(item.time), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } - is Item.Bubble -> Bubble(item, core, group, - onRetry = { core.retry(item.msg) }, - onCopy = { copy(ctx, item.msg.body) }) + is Item.Bubble -> Bubble(item, core, group, selected = item.msg.id in picked, + onClick = { + val id = item.msg.id + when { + picked.isNotEmpty() -> picked = if (id in picked) picked - id else picked + id + item.msg.status == Msg.FAILED -> core.retry(item.msg) + } + }, + onLongClick = { val id = item.msg.id; picked = if (id in picked) picked - id else picked + id }, + onCopy = { copy(ctx, it) }) } } } } + details?.let { m -> DetailsDialog(m) { details = null } } + if (scheduleAsk) ScheduleDialog(onPick = { t -> + core.store.schedule(address, draft.trim(), t, core.simFor(address)); draft = ""; scheduleAsk = false + }, onDismiss = { scheduleAsk = false }) +} + +/** "Tue 14:30" for today/this week, else with the date. */ +private fun scheduleTime(t: Long): String = + java.text.SimpleDateFormat(if (sameDay(t, System.currentTimeMillis())) "HH:mm" else "EEE d MMM, HH:mm", java.util.Locale.getDefault()).format(java.util.Date(t)) + +@Composable +private fun DetailsDialog(m: Msg, onDismiss: () -> Unit) { + val whenText = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.MEDIUM, java.text.DateFormat.SHORT).format(java.util.Date(m.time)) + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.act_details)) }, + text = { + Text(listOfNotNull( + stringResource(if (m.att.isNotBlank()) R.string.details_mms else R.string.details_sms), + (if (m.outgoing) stringResource(R.string.details_to) else stringResource(R.string.details_from)) + " " + m.address, + whenText, + if (m.sim > 0) "SIM ${m.sim}" else null, + if (m.outgoing) stringResource(when (m.status) { + Msg.DELIVERED -> R.string.details_delivered; Msg.FAILED -> R.string.details_failed + Msg.SENDING -> R.string.sending; else -> R.string.details_sent + }) else null, + ).joinToString("\n")) + }, + confirmButton = { TextButton(onDismiss) { Text(stringResource(R.string.ok)) } }, + ) +} + +/** Pick when a text goes out: a few usual times, or any date and time. */ +@Composable +private fun ScheduleDialog(onPick: (Long) -> Unit, onDismiss: () -> Unit) { + val ctx = LocalContext.current + val now = System.currentTimeMillis() + fun at(dayOffset: Int, hour: Int) = java.util.Calendar.getInstance().apply { + add(java.util.Calendar.DAY_OF_YEAR, dayOffset) + set(java.util.Calendar.HOUR_OF_DAY, hour); set(java.util.Calendar.MINUTE, 0); set(java.util.Calendar.SECOND, 0) + }.timeInMillis + val choices = listOf(now + 3_600_000L, at(0, 18), at(1, 8), at(1, 13)).filter { it > now + 60_000 } + AlertDialog( + onDismissRequest = onDismiss, + icon = { Icon(Icons.Filled.Schedule, null) }, + title = { Text(stringResource(R.string.schedule_title)) }, + text = { + Column { + choices.forEach { t -> TextButton({ onPick(t) }) { Text(scheduleTime(t)) } } + TextButton({ + val c = java.util.Calendar.getInstance() + android.app.DatePickerDialog(ctx, { _, y, mo, d -> + android.app.TimePickerDialog(ctx, { _, h, mi -> + c.set(y, mo, d, h, mi, 0) + if (c.timeInMillis > System.currentTimeMillis()) onPick(c.timeInMillis) + else Toast.makeText(ctx, ctx.getString(R.string.schedule_past), Toast.LENGTH_SHORT).show() + }, c.get(java.util.Calendar.HOUR_OF_DAY), c.get(java.util.Calendar.MINUTE), true).show() + }, c.get(java.util.Calendar.YEAR), c.get(java.util.Calendar.MONTH), c.get(java.util.Calendar.DAY_OF_MONTH)).show() + }) { Text(stringResource(R.string.schedule_pick)) } + } + }, + confirmButton = {}, + dismissButton = { TextButton(onDismiss) { Text(stringResource(R.string.cancel)) } }, + ) +} + +/** The message text with links, e-mail addresses and phone numbers that open, and codes that copy. */ +@Composable +private fun linked(text: String, onCopy: (String) -> Unit): AnnotatedString { + val copyNow by rememberUpdatedState(onCopy) + return remember(text) { + buildAnnotatedString { + append(text) + val styles = TextLinkStyles(SpanStyle(textDecoration = TextDecoration.Underline)) + io.github.simbridge.Linkify.spans(text).forEach { sp -> + if (sp.kind == io.github.simbridge.Linkify.Kind.CODE) + addLink(LinkAnnotation.Clickable(tag = "code", styles = styles, linkInteractionListener = { copyNow(sp.target) }), sp.start, sp.end) + else addLink(LinkAnnotation.Url(sp.target, styles), sp.start, sp.end) + } + } + } } @OptIn(ExperimentalFoundationApi::class) @Composable -private fun Bubble(item: Item.Bubble, core: LinkCore, group: Boolean, onRetry: () -> Unit, onCopy: () -> Unit) { +private fun Bubble(item: Item.Bubble, core: LinkCore, group: Boolean, selected: Boolean, + onClick: () -> Unit, onLongClick: () -> Unit, onCopy: (String) -> Unit) { val m = item.msg val ctx = LocalContext.current val mms = remember(m.att) { io.github.simbridge.MmsInfo.parse(m.att) } @@ -197,7 +349,8 @@ private fun Bubble(item: Item.Bubble, core: LinkCore, group: Boolean, onRetry: ( else -> MaterialTheme.colorScheme.onSurface } Column( - Modifier.fillMaxWidth().padding(top = if (item.joinAbove) 2.dp else 8.dp), + Modifier.fillMaxWidth().background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent) + .padding(top = if (item.joinAbove) 2.dp else 8.dp), horizontalAlignment = if (m.outgoing) Alignment.End else Alignment.Start, ) { if (group && !m.outgoing && !item.joinAbove) mms?.from?.let { f -> @@ -210,14 +363,13 @@ private fun Bubble(item: Item.Bubble, core: LinkCore, group: Boolean, onRetry: ( tint = MaterialTheme.colorScheme.error) Surface( shape = shape, color = bg, contentColor = fg, - modifier = Modifier.widthIn(max = 300.dp).combinedClickable( - onClick = { if (failed) onRetry() }, onLongClick = onCopy), + modifier = Modifier.widthIn(max = 300.dp).combinedClickable(onClick = onClick, onLongClick = onLongClick), ) { - Text(m.body, Modifier.padding(horizontal = 16.dp, vertical = 10.dp), style = MaterialTheme.typography.bodyLarge) + Text(linked(m.body, onCopy), Modifier.padding(horizontal = 16.dp, vertical = 10.dp), style = MaterialTheme.typography.bodyLarge) } } - if (item.showStatus || failed) { - val label = when { + if (item.showStatus || failed || m.starred) { + val label = (if (m.starred) "★ " else "") + when { failed -> stringResource(R.string.not_sent_retry) m.status == Msg.SENDING -> stringResource(R.string.sending) m.status == Msg.DELIVERED -> "Delivered · ${clockTime(m.time)}" @@ -230,8 +382,9 @@ private fun Bubble(item: Item.Bubble, core: LinkCore, group: Boolean, onRetry: ( } } +@OptIn(ExperimentalFoundationApi::class) @Composable -private fun Composer(text: String, onText: (String) -> Unit, connected: Boolean, +private fun Composer(text: String, onText: (String) -> Unit, connected: Boolean, onSchedule: () -> Unit, pending: List, onAttach: () -> Unit, onRemove: (io.github.simbridge.Attachment) -> Unit, onSend: () -> Unit) { val ctx = LocalContext.current @@ -265,8 +418,13 @@ private fun Composer(text: String, onText: (String) -> Unit, connected: Boolean, focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent), modifier = Modifier.weight(1f), ) - FilledIconButton(onClick = onSend, enabled = text.isNotBlank() || pending.isNotEmpty(), modifier = Modifier.size(56.dp)) { - Icon(Icons.AutoMirrored.Filled.Send, stringResource(R.string.send)) + // Tap sends; hold to choose a later time. + val canSend = text.isNotBlank() || pending.isNotEmpty() + Box(Modifier.size(56.dp).clip(androidx.compose.foundation.shape.CircleShape) + .background(if (canSend) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceContainerHighest) + .combinedClickable(enabled = canSend, onClick = onSend, onLongClick = onSchedule), contentAlignment = Alignment.Center) { + Icon(Icons.AutoMirrored.Filled.Send, stringResource(R.string.send), + tint = if (canSend) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant) } } } diff --git a/phone/src/main/kotlin/io/github/simbridge/ui/ConversationsScreen.kt b/phone/src/main/kotlin/io/github/simbridge/ui/ConversationsScreen.kt index 427b5c5..21425dc 100644 --- a/phone/src/main/kotlin/io/github/simbridge/ui/ConversationsScreen.kt +++ b/phone/src/main/kotlin/io/github/simbridge/ui/ConversationsScreen.kt @@ -1,5 +1,34 @@ package io.github.simbridge.ui +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.rememberScrollState +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material.icons.filled.PushPin +import androidx.compose.material.icons.outlined.Archive +import androidx.compose.material.icons.outlined.MarkEmailRead +import androidx.compose.material.icons.outlined.MarkEmailUnread +import androidx.compose.material.icons.outlined.PushPin +import androidx.compose.material.icons.outlined.Unarchive +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.SnackbarDuration +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SnackbarResult +import androidx.compose.material3.SwipeToDismissBox +import androidx.compose.material3.SwipeToDismissBoxValue +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.rememberSwipeToDismissBoxState +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalContext +import kotlinx.coroutines.launch import io.github.simbridge.R import androidx.compose.ui.res.stringResource import android.net.Uri @@ -70,16 +99,47 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext private data class ConvRow(val conv: Conversation, val name: String, val photo: Uri?) +private data class Hit(val msg: Msg, val name: String) +private enum class Filter(val label: Int) { + ALL(R.string.filter_all), UNREAD(R.string.filter_unread), ARCHIVED(R.string.filter_archived), STARRED(R.string.filter_starred) +} -@OptIn(ExperimentalFoundationApi::class) +/** Swipe and toolbar actions on conversations. */ +internal object ConvAction { + const val READ = "read"; const val ARCHIVE = "archive"; const val DELETE = "delete"; const val PIN = "pin"; const val NONE = "none" + val all = listOf(READ, ARCHIVE, DELETE, PIN, NONE) + fun label(a: String) = when (a) { + READ -> R.string.act_read; ARCHIVE -> R.string.act_archive; DELETE -> R.string.delete; PIN -> R.string.act_pin + else -> R.string.act_none + } + fun icon(a: String): ImageVector? = when (a) { + READ -> Icons.Outlined.MarkEmailRead; ARCHIVE -> Icons.Outlined.Archive; DELETE -> Icons.Outlined.Delete + PIN -> Icons.Outlined.PushPin; else -> null + } +} + +@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class) @Composable fun ConversationsScreen(core: LinkCore, onOpen: (String, String) -> Unit, onNew: () -> Unit, onSettings: () -> Unit) { + val ctx = LocalContext.current val version by core.store.version.collectAsState() val status by core.status.collectAsState() var rows by remember { mutableStateOf(emptyList()) } var loaded by remember { mutableStateOf(false) } var query by remember { mutableStateOf("") } - var toDelete by remember { mutableStateOf(null) } + var filter by remember { mutableStateOf(Filter.ALL) } + var hits by remember { mutableStateOf(emptyList()) } + // Long-press selects; while anything is selected a tap selects too (like Gmail and Google Messages). + var selected by remember { mutableStateOf(emptySet()) } + // Deleted conversations stay hidden until the Undo bar is gone, then they are really deleted. + var hidden by remember { mutableStateOf(emptySet()) } + var blockAsk by remember { mutableStateOf(false) } + var menu by remember { mutableStateOf(false) } + val snack = remember { SnackbarHostState() } + val scope = rememberCoroutineScope() + val swipeRight = core.prefs.swipeRight + val swipeLeft = core.prefs.swipeLeft + LaunchedEffect(version) { rows = withContext(Dispatchers.IO) { core.store.conversations().map { c -> @@ -87,20 +147,90 @@ fun ConversationsScreen(core: LinkCore, onOpen: (String, String) -> Unit, onNew: ConvRow(c, info?.name ?: c.address, info?.photo) } } + selected = selected.filter { k -> rows.any { it.conv.key == k } }.toSet() loaded = true } - val shown = remember(rows, query) { - if (query.isBlank()) rows else rows.filter { - it.name.contains(query, true) || it.conv.address.contains(query) || it.conv.last.body.contains(query, true) + // Text inside messages (and the starred ones), under the matching conversations. + LaunchedEffect(version, query, filter) { + val q = query.trim() + hits = if (q.length >= 2 || filter == Filter.STARRED) withContext(Dispatchers.IO) { + core.store.search(q, starred = filter == Filter.STARRED).map { Hit(it, core.contacts.lookup(it.address)?.name ?: it.address) } + } else emptyList() + } + val shown = remember(rows, query, filter, hidden) { + rows.filter { r -> + r.conv.key !in hidden && when (filter) { + Filter.ALL -> !r.conv.archived + Filter.UNREAD -> r.conv.unread > 0 && !r.conv.archived + Filter.ARCHIVED -> r.conv.archived + Filter.STARRED -> false + } && (query.isBlank() || r.name.contains(query, true) || r.conv.address.contains(query) || r.conv.last.body.contains(query, true)) + } + } + + fun delete(keys: Set) { + if (keys.isEmpty()) return + hidden = hidden + keys + scope.launch { + var undone = false + try { + undone = snack.showSnackbar(ctx.getString(R.string.conv_deleted, keys.size), ctx.getString(R.string.undo), + duration = SnackbarDuration.Short) == SnackbarResult.ActionPerformed + } finally { + // Also when this screen closes first: the delete was asked for and not undone. + if (!undone) keys.forEach { core.deleteConversation(it) } + hidden = hidden - keys + } + } + } + + fun act(action: String, keys: Set) { + val sel = rows.filter { it.conv.key in keys } + when (action) { + ConvAction.READ -> if (sel.any { it.conv.unread > 0 }) sel.forEach { core.markRead(it.conv.key); core.notifier.cancel(it.conv.key) } + else sel.forEach { core.store.markUnread(it.conv.key) } + ConvAction.ARCHIVE -> core.store.setArchived(keys, !sel.all { it.conv.archived }) + ConvAction.PIN -> core.store.setPinned(keys, !sel.all { it.conv.pinned }) + ConvAction.DELETE -> delete(keys) } + selected = emptySet() } + + BackHandler(enabled = selected.isNotEmpty()) { selected = emptySet() } val listState = rememberLazyListState() val expanded by remember { derivedStateOf { listState.firstVisibleItemIndex == 0 } } Scaffold( - topBar = { SearchBar(query, { query = it }, onSettings) }, + topBar = { + if (selected.isEmpty()) Column(Modifier.background(MaterialTheme.colorScheme.surface)) { + SearchBar(query, { query = it }, onSettings) + Row(Modifier.horizontalScroll(rememberScrollState()).padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Filter.entries.forEach { f -> FilterChip(filter == f, { filter = f }, label = { Text(stringResource(f.label)) }) } + } + } else TopAppBar( + navigationIcon = { IconButton({ selected = emptySet() }) { Icon(Icons.Filled.Close, stringResource(R.string.cancel)) } }, + title = { Text(selected.size.toString()) }, + actions = { + val sel = rows.filter { it.conv.key in selected } + IconButton({ act(ConvAction.PIN, selected) }) { Icon(Icons.Outlined.PushPin, stringResource(R.string.act_pin)) } + IconButton({ act(ConvAction.ARCHIVE, selected) }) { + Icon(if (sel.all { it.conv.archived }) Icons.Outlined.Unarchive else Icons.Outlined.Archive, stringResource(R.string.act_archive)) + } + IconButton({ act(ConvAction.READ, selected) }) { + Icon(if (sel.any { it.conv.unread > 0 }) Icons.Outlined.MarkEmailRead else Icons.Outlined.MarkEmailUnread, stringResource(R.string.act_read)) + } + IconButton({ act(ConvAction.DELETE, selected) }) { Icon(Icons.Outlined.Delete, stringResource(R.string.delete)) } + IconButton({ menu = true }) { Icon(Icons.Filled.MoreVert, stringResource(R.string.more)) } + DropdownMenu(menu, { menu = false }) { + DropdownMenuItem(text = { Text(stringResource(R.string.select_all)) }, onClick = { menu = false; selected = shown.map { it.conv.key }.toSet() }) + DropdownMenuItem(text = { Text(stringResource(R.string.block)) }, onClick = { menu = false; blockAsk = true }) + } + }, + ) + }, + snackbarHost = { SnackbarHost(snack) }, floatingActionButton = { - ExtendedFloatingActionButton( + if (selected.isEmpty()) ExtendedFloatingActionButton( onClick = onNew, expanded = expanded, icon = { Icon(Icons.AutoMirrored.Filled.Chat, null) }, text = { Text(stringResource(R.string.start_chat)) }, @@ -109,27 +239,99 @@ fun ConversationsScreen(core: LinkCore, onOpen: (String, String) -> Unit, onNew: ) { pad -> LazyColumn(Modifier.fillMaxSize(), state = listState, contentPadding = PaddingValues(top = pad.calculateTopPadding(), bottom = 96.dp)) { item { StatusBanner(status, onSettings) } - if (loaded && shown.isEmpty()) item { EmptyState(query.isNotBlank()) } + if (loaded && shown.isEmpty() && hits.isEmpty()) item { EmptyState(query.isNotBlank() || filter != Filter.ALL) } items(shown, key = { it.conv.key }) { r -> - ConversationRow(r, Modifier.combinedClickable( - onClick = { onOpen(r.conv.key, r.conv.address) }, - onLongClick = { toDelete = r }, - )) + val picked = r.conv.key in selected + SwipeRow(swipeRight, swipeLeft, enabled = selected.isEmpty(), unread = r.conv.unread > 0, onAction = { act(it, setOf(r.conv.key)) }) { + ConversationRow(r, picked, Modifier.combinedClickable( + onClick = { + if (selected.isEmpty()) onOpen(r.conv.key, r.conv.address) + else selected = if (picked) selected - r.conv.key else selected + r.conv.key + }, + onLongClick = { selected = if (picked) selected - r.conv.key else selected + r.conv.key }, + )) + } + } + if (hits.isNotEmpty()) { + item { + Text(stringResource(R.string.search_in_messages), Modifier.padding(start = 16.dp, top = 16.dp, bottom = 4.dp), + style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary) + } + items(hits, key = { "h${it.msg.id}" }) { h -> + Row(Modifier.fillMaxWidth().clickable { onOpen(h.msg.key, h.msg.address) }.padding(horizontal = 16.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(h.name, style = MaterialTheme.typography.titleSmall, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text((if (h.msg.starred) "★ " else "") + h.msg.body, style = MaterialTheme.typography.bodyMedium, maxLines = 2, + overflow = TextOverflow.Ellipsis, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Spacer(Modifier.width(8.dp)) + Text(shortTime(h.msg.time), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } } } } - toDelete?.let { r -> + if (blockAsk) { + val numbers = rows.filter { it.conv.key in selected && !isGateway(it.conv.address) && !io.github.simbridge.Group.isGroup(it.conv.address) } + .map { it.conv.address } AlertDialog( - onDismissRequest = { toDelete = null }, - icon = { Icon(Icons.Outlined.Delete, null) }, - title = { Text(stringResource(R.string.delete_conv_q)) }, - text = { Text(stringResource(R.string.delete_conv_text, r.name)) }, - confirmButton = { TextButton({ core.deleteConversation(r.conv.key); toDelete = null }) { Text(stringResource(R.string.delete)) } }, - dismissButton = { TextButton({ toDelete = null }) { Text(stringResource(R.string.cancel)) } }, + onDismissRequest = { blockAsk = false }, + title = { Text(stringResource(R.string.block_q)) }, + text = { Text(numbers.joinToString("\n")) }, + confirmButton = { + TextButton({ + core.prefs.blocked = core.prefs.blocked + numbers + core.blockRulesChanged() + blockAsk = false; selected = emptySet() + }, enabled = numbers.isNotEmpty()) { Text(stringResource(R.string.block)) } + }, + dismissButton = { TextButton({ blockAsk = false }) { Text(stringResource(R.string.cancel)) } }, ) } } +/** A conversation row that can be swiped either way; the action runs and the row slides back. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun SwipeRow(right: String, left: String, enabled: Boolean, unread: Boolean, onAction: (String) -> Unit, content: @Composable () -> Unit) { + val fire by rememberUpdatedState(onAction) + val r by rememberUpdatedState(right) + val l by rememberUpdatedState(left) + val state = rememberSwipeToDismissBoxState() + // A full swipe runs the action, then the row slides back (when the action removes the row, + // the list drops it anyway). + LaunchedEffect(state.currentValue) { + when (state.currentValue) { + SwipeToDismissBoxValue.StartToEnd -> fire(r) + SwipeToDismissBoxValue.EndToStart -> fire(l) + else -> return@LaunchedEffect + } + state.snapTo(SwipeToDismissBoxValue.Settled) + } + SwipeToDismissBox( + state = state, + enableDismissFromStartToEnd = enabled && right != ConvAction.NONE, + enableDismissFromEndToStart = enabled && left != ConvAction.NONE, + backgroundContent = { + val dir = state.dismissDirection + val action = when (dir) { SwipeToDismissBoxValue.StartToEnd -> right; SwipeToDismissBoxValue.EndToStart -> left; else -> ConvAction.NONE } + val color = when (action) { + ConvAction.DELETE -> MaterialTheme.colorScheme.errorContainer + ConvAction.ARCHIVE -> MaterialTheme.colorScheme.tertiaryContainer + ConvAction.READ -> MaterialTheme.colorScheme.primaryContainer + ConvAction.PIN -> MaterialTheme.colorScheme.secondaryContainer + else -> Color.Transparent + } + Box(Modifier.fillMaxSize().background(color).padding(horizontal = 24.dp), + contentAlignment = if (dir == SwipeToDismissBoxValue.EndToStart) Alignment.CenterEnd else Alignment.CenterStart) { + val icon = if (action == ConvAction.READ && !unread) Icons.Outlined.MarkEmailUnread else ConvAction.icon(action) + icon?.let { Icon(it, stringResource(ConvAction.label(action))) } + } + }, + ) { content() } +} + @Composable private fun SearchBar(query: String, onQuery: (String) -> Unit, onSettings: () -> Unit) { Surface(color = MaterialTheme.colorScheme.surface) { @@ -179,11 +381,15 @@ private fun StatusBanner(s: LinkStatus, onSettings: () -> Unit) { } @Composable -private fun ConversationRow(r: ConvRow, modifier: Modifier) { +private fun ConversationRow(r: ConvRow, picked: Boolean, modifier: Modifier) { val unread = r.conv.unread > 0 val m = r.conv.last - Row(modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically) { - Avatar(r.name, r.photo, gateway = isGateway(r.conv.address)) + // Opaque, so the swipe colour only shows where the row has moved away. + Row(modifier.fillMaxWidth().background(if (picked) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surface) + .padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically) { + if (picked) Box(Modifier.size(48.dp).background(MaterialTheme.colorScheme.primary, CircleShape), contentAlignment = Alignment.Center) { + Icon(Icons.Filled.Check, null, tint = MaterialTheme.colorScheme.onPrimary) + } else Avatar(r.name, r.photo, gateway = isGateway(r.conv.address)) Spacer(Modifier.width(16.dp)) Column(Modifier.weight(1f)) { Text(r.name, style = MaterialTheme.typography.titleMedium, @@ -207,6 +413,7 @@ private fun ConversationRow(r: ConvRow, modifier: Modifier) { color = if (unread) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, fontWeight = if (unread) FontWeight.Bold else FontWeight.Normal) if (unread) Badge(containerColor = MaterialTheme.colorScheme.primary) { Text(r.conv.unread.toString()) } + if (r.conv.pinned) Icon(Icons.Filled.PushPin, stringResource(R.string.act_pin), Modifier.size(14.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant) } } } diff --git a/phone/src/main/kotlin/io/github/simbridge/ui/SettingsScreen.kt b/phone/src/main/kotlin/io/github/simbridge/ui/SettingsScreen.kt index 04751e0..f909ec2 100644 --- a/phone/src/main/kotlin/io/github/simbridge/ui/SettingsScreen.kt +++ b/phone/src/main/kotlin/io/github/simbridge/ui/SettingsScreen.kt @@ -252,6 +252,12 @@ fun SettingsScreen(core: LinkCore, onSimPhone: () -> Unit = {}, onBlocked: () -> color = MaterialTheme.colorScheme.onSurfaceVariant) } } + Card(Icons.Filled.Sms, stringResource(R.string.set_swipe), stringResource(R.string.set_swipe_text), ok = true) { + Column { + SwipePicker(stringResource(R.string.set_swipe_right), core.prefs.swipeRight) { core.prefs.swipeRight = it } + SwipePicker(stringResource(R.string.set_swipe_left), core.prefs.swipeLeft) { core.prefs.swipeLeft = it } + } + } var otp by remember { mutableStateOf(core.prefs.otpCopy) } Card(Icons.Filled.Sms, stringResource(R.string.set_otp), stringResource(R.string.set_otp_text), ok = true) { Row(verticalAlignment = Alignment.CenterVertically) { @@ -425,6 +431,8 @@ private fun TranslationCard(core: LinkCore) { if (bubble && !overlayOk) TextButton({ runCatching { ctx.startActivity(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + ctx.packageName))) } }) { Text(stringResource(R.string.set_tr_bubble_allow)) } + var liveCap by remember { mutableStateOf(prefs.liveCaptions) } + SwitchRow(stringResource(R.string.set_tr_live), liveCap) { liveCap = it; prefs.liveCaptions = it } SwitchRow(stringResource(R.string.set_tr_speak_me), speakToMe) { speakToMe = it; prefs.speakToMe = it } SwitchRow(stringResource(R.string.set_tr_large), large) { large = it; prefs.captionLarge = it } SwitchRow(stringResource(R.string.set_translate_offline), onDevice) { @@ -469,3 +477,23 @@ private fun LangPicker(label: String, code: String, modifier: Modifier, pick: (S } } } + +/** One swipe direction on a conversation and what it does. */ +@Composable +private fun SwipePicker(label: String, value: String, set: (String) -> Unit) { + var current by remember { mutableStateOf(value) } + var open by remember { mutableStateOf(false) } + Row(verticalAlignment = Alignment.CenterVertically) { + Text(label, Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge) + Box { + TextButton({ open = true }) { Text(stringResource(ConvAction.label(current))) } + androidx.compose.material3.DropdownMenu(open, { open = false }) { + ConvAction.all.forEach { a -> + androidx.compose.material3.DropdownMenuItem(text = { Text(stringResource(ConvAction.label(a))) }, + onClick = { current = a; set(a); open = false }) + } + } + } + } +} + diff --git a/phone/src/main/kotlin/io/github/simbridge/ui/SimPhoneScreen.kt b/phone/src/main/kotlin/io/github/simbridge/ui/SimPhoneScreen.kt index 6e0d238..5cf4cc1 100644 --- a/phone/src/main/kotlin/io/github/simbridge/ui/SimPhoneScreen.kt +++ b/phone/src/main/kotlin/io/github/simbridge/ui/SimPhoneScreen.kt @@ -408,6 +408,9 @@ private fun Hero(s: GatewayStatus?, online: Boolean, detail: String) { Spacer(Modifier.height(10.dp)) Text(if (s?.battery != null) "${s.battery}%" else "—", style = MaterialTheme.typography.displaySmall, fontWeight = FontWeight.Bold) Muted(stringResource(if (s?.charging == true) R.string.dash_charging else R.string.dash_battery)) + // Time left from the SIM phone's real drain (or to a full charge). + val mins = if (s?.charging == true) s.chargeMin else s?.batteryMin + if (mins != null) Muted(stringResource(if (s?.charging == true) R.string.dash_full_in else R.string.dash_time_left, duration(mins))) Spacer(Modifier.height(10.dp)) Box(Modifier.background(if (online) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.errorContainer, RoundedCornerShape(50)).padding(horizontal = 10.dp, vertical = 4.dp)) { @@ -574,3 +577,10 @@ private fun Bars(level: Int) { } } } + +/** "2 d 4 h", "14 h 20 min" or "35 min". */ +internal fun duration(minutes: Int): String = when { + minutes >= 48 * 60 -> "${minutes / 1440} d ${minutes % 1440 / 60} h" + minutes >= 60 -> "${minutes / 60} h ${minutes % 60} min" + else -> "$minutes min" +} diff --git a/phone/src/main/res/values-ar/strings.xml b/phone/src/main/res/values-ar/strings.xml index 809f57a..63d0415 100644 --- a/phone/src/main/res/values-ar/strings.xml +++ b/phone/src/main/res/values-ar/strings.xml @@ -266,4 +266,39 @@ رقم خاص معاودة الاتصال اتصال SimBridge وبطارية هاتف SIM وإشارته + يتبقى نحو %1$s + يكتمل الشحن خلال %1$s + الكل + غير مقروءة + المؤرشفة + المميزة بنجمة + مقروء / غير مقروء + أرشفة + تثبيت + لا شيء + تمييز بنجمة + إعادة توجيه + التفاصيل + تحديد الكل + تم حذف %1$d + تراجع + في الرسائل + حظر هذه الأرقام؟ + نسخ + بحث في المحادثة + رسالة نصية + رسالة مصورة + إلى: + من: + تم التسليم + لم تُرسل + أُرسلت + إرسال لاحقًا + اختيار التاريخ والوقت + هذا الوقت قد مضى + إجراءات السحب + ما يفعله سحب المحادثة. + السحب لليمين + السحب لليسار + عرض الكلمات أثناء نطقها diff --git a/phone/src/main/res/values-es/strings.xml b/phone/src/main/res/values-es/strings.xml index 98c2c2c..023a85f 100644 --- a/phone/src/main/res/values-es/strings.xml +++ b/phone/src/main/res/values-es/strings.xml @@ -266,4 +266,39 @@ Número privado Devolver llamada Enlace SimBridge, batería y señal del teléfono SIM + Quedan unas %1$s + Carga completa en %1$s + Todos + No leídos + Archivados + Destacados + Leído / no leído + Archivar + Fijar + Nada + Destacar + Reenviar + Detalles + Seleccionar todo + %1$d eliminada(s) + Deshacer + En los mensajes + ¿Bloquear estos números? + Copiar + Buscar en la conversación + Mensaje de texto + Mensaje con imagen + Para: + De: + Entregado + No enviado + Enviado + Enviar más tarde + Elegir fecha y hora + Esa hora ya pasó + Acciones al deslizar + Qué hace deslizar una conversación. + Deslizar a la derecha + Deslizar a la izquierda + Mostrar las palabras mientras se dicen diff --git a/phone/src/main/res/values-fa/strings.xml b/phone/src/main/res/values-fa/strings.xml index 19765a4..c9ad5b1 100644 --- a/phone/src/main/res/values-fa/strings.xml +++ b/phone/src/main/res/values-fa/strings.xml @@ -266,4 +266,39 @@ شماره ناشناس تماس مجدد اتصال SimBridge، باتری و آنتن گوشی سیم‌کارت + حدود %1$s باقی مانده + شارژ کامل تا %1$s دیگر + همه + خوانده‌نشده + بایگانی‌شده + ستاره‌دار + خوانده / نخوانده + بایگانی + سنجاق + هیچ + ستاره + هدایت + جزئیات + انتخاب همه + %1$d مورد حذف شد + واگرد + در پیام‌ها + این شماره‌ها مسدود شوند؟ + کپی + جستجو در گفتگو + پیام متنی + پیام تصویری + به: + از: + تحویل شد + ارسال نشد + ارسال شد + ارسال در زمان دیگر + انتخاب تاریخ و ساعت + این زمان گذشته است + عملکرد کشیدن + کشیدن روی گفتگو چه کاری انجام دهد. + کشیدن به راست + کشیدن به چپ + نمایش واژه‌ها هنگام گفتن diff --git a/phone/src/main/res/values-fr/strings.xml b/phone/src/main/res/values-fr/strings.xml index 2b59ac1..60371bb 100644 --- a/phone/src/main/res/values-fr/strings.xml +++ b/phone/src/main/res/values-fr/strings.xml @@ -266,4 +266,39 @@ Numéro masqué Rappeler Liaison SimBridge, batterie et signal du téléphone SIM + Environ %1$s restantes + Chargé dans %1$s + Tous + Non lus + Archivés + Favoris + Lu / non lu + Archiver + Épingler + Rien + Favori + Transférer + Détails + Tout sélectionner + %1$d supprimée(s) + Annuler + Dans les messages + Bloquer ces numéros ? + Copier + Rechercher dans la conversation + SMS + Message avec image + À : + De : + Distribué + Non envoyé + Envoyé + Envoyer plus tard + Choisir la date et l\'heure + Cette heure est passée + Actions de balayage + Ce que fait le balayage d\'une conversation. + Balayage à droite + Balayage à gauche + Afficher les mots pendant qu\'ils sont prononcés diff --git a/phone/src/main/res/values-ru/strings.xml b/phone/src/main/res/values-ru/strings.xml index 1856bef..b4b92d3 100644 --- a/phone/src/main/res/values-ru/strings.xml +++ b/phone/src/main/res/values-ru/strings.xml @@ -266,4 +266,39 @@ Скрытый номер Перезвонить Связь SimBridge, батарея и сигнал SIM-телефона + Осталось около %1$s + Зарядится через %1$s + Все + Непрочитанные + Архив + Избранные + Прочитано / не прочитано + В архив + Закрепить + Ничего + В избранное + Переслать + Сведения + Выбрать все + Удалено: %1$d + Отменить + В сообщениях + Заблокировать эти номера? + Копировать + Поиск в переписке + Текстовое сообщение + Сообщение с картинкой + Кому: + От: + Доставлено + Не отправлено + Отправлено + Отправить позже + Выбрать дату и время + Это время уже прошло + Действия при смахивании + Что делает смахивание переписки. + Смахивание вправо + Смахивание влево + Показывать слова во время речи diff --git a/phone/src/main/res/values-tr/strings.xml b/phone/src/main/res/values-tr/strings.xml index 909a15a..ceebfce 100644 --- a/phone/src/main/res/values-tr/strings.xml +++ b/phone/src/main/res/values-tr/strings.xml @@ -301,4 +301,39 @@ Gizli numara Geri ara SimBridge bağlantısı, SIM telefonun pili ve sinyali + Yaklaşık %1$s kaldı + %1$s sonra dolacak + Tümü + Okunmamış + Arşivlenen + Yıldızlı + Okundu / okunmadı + Arşivle + Sabitle + Hiçbir şey + Yıldızla + İlet + Ayrıntılar + Tümünü seç + %1$d silindi + Geri al + Mesajlarda + Bu numaralar engellensin mi? + Kopyala + Sohbette ara + Kısa mesaj + Resimli mesaj + Kime: + Kimden: + İletildi + Gönderilemedi + Gönderildi + Sonra gönder + Tarih ve saat seç + Bu saat geçti + Kaydırma işlemleri + Bir sohbeti kaydırınca ne olacağı. + Sağa kaydırma + Sola kaydırma + Sözcükleri söylenirken göster diff --git a/phone/src/main/res/values/strings.xml b/phone/src/main/res/values/strings.xml index ff68a99..c686fb7 100644 --- a/phone/src/main/res/values/strings.xml +++ b/phone/src/main/res/values/strings.xml @@ -302,4 +302,39 @@ Private number Call back SimBridge link, SIM phone battery and signal + About %1$s left + Full in %1$s + All + Unread + Archived + Starred + Read / unread + Archive + Pin + Nothing + Star + Forward + Details + Select all + %1$d deleted + Undo + In messages + Block these numbers? + Copy + Search in conversation + Text message + Picture message + To: + From: + Delivered + Not sent + Sent + Send later + Pick date and time + That time has passed + Swipe actions + What swiping a conversation does. + Swipe right + Swipe left + Show words while they are spoken