Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

refactor(android): remove code comments

wquguru6ab516be1f54
diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts
index a5c0ad2..6580ae4 100644
--- a/android/app/build.gradle.kts
+++ b/android/app/build.gradle.kts
@@ -1,20 +1,13 @@
-// The Android app. AGP 9 compiles Kotlin itself; no AndroidX, no libraries beyond :core. Its one
-// native library is our own C (src/main/jni), built with the NDK.
plugins { id("com.android.application") }
-// One version for every platform: VERSION at the repo root. versionCode must only grow: 1.2.3 → 10203.
val appVersion = rootProject.file("../VERSION").readText().trim()
val appVersionCode = appVersion.split(".").map { it.toInt() }.let { (a, b, c) -> a * 10000 + b * 100 + c }
-// Release signing: the key never enters the repo. scripts/keystore.sh makes it once
-// (~/.cicada-android/release.jks, its password in the Keychain); scripts/build.sh and CI hand it
-// over in these variables. Without them the release build stays unsigned: never the debug key.
val releaseKeystore = System.getenv("CICADA_KEYSTORE")?.let { file(it) }?.takeIf { it.isFile }
android {
namespace = "com.wquguru.cicada"
compileSdk = 36
- // 说话人识别's voiceprint library (src/main/jni): scripts/install-sdk.sh and CI install this NDK.
ndkVersion = "29.0.14206865"
defaultConfig {
applicationId = "com.wquguru.cicada"
@@ -22,25 +15,19 @@ android {
targetSdk = 36
versionCode = appVersionCode
versionName = appVersion
- // Every phone (64- and 32-bit ARM) and the arm64 or x86_64 emulator: an APK with native code
- // doesn't install on an ABI it leaves out.
ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a", "x86_64") }
}
externalNativeBuild { ndkBuild { path = file("src/main/jni/Android.mk") } }
- // The voiceprint weights stay uncompressed: NativeVoiceprints sizes the asset to know its copy is whole.
androidResources { noCompress += "bin" }
signingConfigs {
if (releaseKeystore != null) create("release") {
storeFile = releaseKeystore
- // PKCS12 has one password for the store and the key.
storePassword = System.getenv("CICADA_KEYSTORE_PASSWORD")
keyPassword = System.getenv("CICADA_KEYSTORE_PASSWORD")
keyAlias = System.getenv("CICADA_KEY_ALIAS") ?: "cicada"
}
}
buildTypes {
- // The dev build has its own id (so its own records and key), log and the debug receiver
- // that scripts/cicadactl.sh drives.
debug { applicationIdSuffix = ".dev"; versionNameSuffix = "-dev" }
release {
isMinifyEnabled = false
@@ -60,8 +47,6 @@ kotlin { jvmToolchain(21) }
dependencies { implementation(project(":core")) }
-// The UI text: the Mac's Localizable.strings (and .stringsdict, its plurals) and the Android-only Android.strings, both keyed by
-// the Chinese, into assets/Resources/<lang>.lproj/.
val copyStrings by tasks.registering(Sync::class) {
into(layout.buildDirectory.dir("generated/strings/Resources"))
for (lang in listOf("zh-Hans", "en", "ja", "ko")) {
@@ -69,8 +54,6 @@ val copyStrings by tasks.registering(Sync::class) {
from(file("src/main/strings/$lang.lproj")) { include("Android.strings"); into("$lang.lproj") }
}
}
-// 说话人识别's weights: the Linux app's linux/models/voiceprint.bin (the Mac's model, converted by
-// linux/scripts/convert-voiceprint.py), not a second copy in the repo.
val copyVoiceprint by tasks.registering(Sync::class) {
from(rootProject.file("../linux/models")) { include("voiceprint.bin") }
into(layout.buildDirectory.dir("generated/voiceprint"))
diff --git a/android/app/src/main/jni/voiceprint_jni.c b/android/app/src/main/jni/voiceprint_jni.c
index daaf6ac..11d51da 100644
--- a/android/app/src/main/jni/voiceprint_jni.c
+++ b/android/app/src/main/jni/voiceprint_jni.c
@@ -1,5 +1,3 @@
-/* NativeVoiceprints (Voiceprints.kt) → linux/native/voiceprint.c, the voiceprint model the Linux app
- * runs; the same C, so an Android voiceprint is the Mac's. Only the calls, no logic of its own. */
#include <jni.h>
#include <stdint.h>
@@ -14,12 +12,9 @@ Java_com_wquguru_cicada_NativeVoiceprints_nativeLoad(JNIEnv *env, jobject self,
if (!p) return 0;
void *m = cvp_load(p);
(*env)->ReleaseStringUTFChars(env, path, p);
- /* Voiceprints.kt reads 256 numbers: a model of another size is no model. */
return m && cvp_dims(m) == 256 ? (jlong)(intptr_t)m : 0;
}
-/* 0 with a unit-length voiceprint in `out`, -1 when too short or it failed. Threads 0: one per
- * core, at most four (voiceprint.c). */
JNIEXPORT jint JNICALL
Java_com_wquguru_cicada_NativeVoiceprints_nativeEmbed(JNIEnv *env, jobject self, jlong model, jshortArray samples,
jint n, jfloatArray out) {
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/AacEncoder.kt b/android/app/src/main/kotlin/com/wquguru/cicada/AacEncoder.kt
index 3a8b125..1a7ea08 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/AacEncoder.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/AacEncoder.kt
@@ -9,9 +9,6 @@ import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
-/// A segment as AAC-LC in ADTS frames ("audio/aac"), which Ming hears as well as WAV at ~1/10 the
-/// size. ADTS needs no muxer or temp file: each encoded frame gets a 7-byte header. Null when the
-/// device has no usable encoder; the caller then sends WAV.
object AacEncoder {
private const val BITRATE = 24_000
private const val TIMEOUT_US = 10_000L
@@ -34,7 +31,6 @@ object AacEncoder {
val info = MediaCodec.BufferInfo()
var fed = 0L
var inputDone = false
- // Bounded so a stuck codec can't hold a segment forever (~2 s without output).
var idle = 0
while (idle < 200) {
if (!inputDone) {
@@ -51,8 +47,6 @@ object AacEncoder {
codec.queueInputBuffer(i, 0, n, timeUs, if (inputDone) MediaCodec.BUFFER_FLAG_END_OF_STREAM else 0)
}
}
- // Drain everything ready without waiting while there is input left to feed:
- // waiting on each frame here made a 7 s segment take a second to encode.
while (true) {
val o = codec.dequeueOutputBuffer(info, if (inputDone) TIMEOUT_US else 0)
if (o < 0) { if (inputDone) idle++; break }
@@ -78,10 +72,9 @@ object AacEncoder {
private val FREQ_INDEX = mapOf(48000 to 3, 44100 to 4, 32000 to 5, 24000 to 6, 22050 to 7, 16000 to 8, 12000 to 9, 11025 to 10, 8000 to 11)
- /// ADTS header for one AAC-LC mono frame of `size` bytes.
private fun adts(size: Int, freq: Int): ByteArray {
val len = size + 7
- val profile = 1 // AAC LC (object type 2) minus one
+ val profile = 1
val channels = 1
return byteArrayOf(
0xFF.toByte(), 0xF1.toByte(),
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/AiCheckViews.kt b/android/app/src/main/kotlin/com/wquguru/cicada/AiCheckViews.kt
index c735313..11d118a 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/AiCheckViews.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/AiCheckViews.kt
@@ -17,22 +17,14 @@ import cicada.Strings
import cicada.Strings.L
import cicada.Strings.LF
-/// The AI service's check, step by step (AICheckView.swift): 设置 › AI 服务 and the onboarding
-/// show the same list; the home card and the 开始听 sheet say the same in fewer words. Every step
-/// that ran shows its result; the one that failed says why in one line and offers the one thing
-/// that fixes it.
object AiCheckViews {
- /// "Busy, retrying": a passing state that still deserves a word (Palette.warn on the Mac).
val warn = Color.parseColor("#8A5900")
val warnPale = Color.parseColor("#FFF4D6")
val ok = Color.parseColor("#1E7B45")
val okPale = Color.parseColor("#E3F3E8")
- /// The steps show while something is wrong or being checked; all passed folds into one line.
fun showSteps(c: AICheck) = c.running || c.failure != null || c.busy || (c.at != null && !c.passed)
- /// The list of steps. `recheck`: 重新检查 in the failed step (onboarding; the settings have
- /// their own row). `changeKey` opens the key field.
fun steps(a: Activity, ui: Ui, recheck: Boolean, changeKey: () -> Unit): LinearLayout {
val app = a.cicada
val ling = app.ling
@@ -72,7 +64,6 @@ object AiCheckViews {
return ui.text(glyph, 12f, fg, bold = true).apply { gravity = Gravity.CENTER; background = ui.rounded(bg, 11) }
}
- /// Why it failed, the proxy hint when it's the network, and the fix: one dark button, at most one other.
private fun problem(a: Activity, ui: Ui, into: LinearLayout, busy: Boolean, recheck: Boolean, changeKey: () -> Unit) {
val ling = a.cicada.ling
ling.checkMessage()?.let { into.addView(ui.text(it, 13f, if (busy) warn else Palette.link)) }
@@ -92,7 +83,6 @@ object AiCheckViews {
into.addView(buttons, ui.lp(top = 6))
}
- /// One primary fix and at most one other, by why it failed.
fun actions(a: Activity, recheck: Boolean, changeKey: () -> Unit): List<Pair<String, () -> Unit>> {
val app = a.cicada
val ling = app.ling
@@ -101,7 +91,6 @@ object AiCheckViews {
val cfg = ling.config()
val again = if (recheck) listOf(L("重新检查") to { app.recheck() }) else emptyList()
return when (f.reason) {
- // A server on the local network: the proxy help has nothing to say.
Reason.Unreachable -> if (ling.unreachableNearby()) again else listOf<Pair<String, () -> Unit>>(L("怎么设置代理") to { open(a, helpUrl()) }) + again
Reason.InvalidKey, Reason.MgmtKey ->
listOf<Pair<String, () -> Unit>>(L("更换 key") to changeKey) + (p.site?.let { listOf<Pair<String, () -> Unit>>(LF("打开 %@", p.name) to { open(a, it) }) } ?: emptyList())
@@ -115,10 +104,8 @@ object AiCheckViews {
private fun recommended(first: String?, current: String) = first?.takeIf { it != current }
- /// Where to add money: OpenRouter's credits page, else the service's own site.
fun topUp(p: cicada.Provider) = if (p.id == "openrouter") "https://openrouter.ai/settings/credits" else p.site ?: "https://zenmux.ai"
- /// The website's proxy help, in the UI language.
fun helpUrl(): String {
val prefix = when (Strings.language) { "en" -> "/en"; "ja" -> "/ja"; "ko" -> "/ko"; else -> "" }
return "https://cicada.indaloop.app$prefix/start/#proxy"
@@ -128,13 +115,10 @@ object AiCheckViews {
try { a.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } catch (_: Exception) {}
}
- /// All passed, in one line: "已连接 · 文字 1.8 秒 · 听 0.9 秒", or when the newest evidence came
- /// from a meeting, "正常 · 12 分钟前开会时用过". Null otherwise.
fun summary(c: AICheck): String? {
if (!c.passed || c.busy) return null
val at = c.at
if (c.passive && at != null) return L("正常") + " · " +
- // Under a minute ICU says "now", which reads as in use right now: "just now", as on Linux.
(if (System.currentTimeMillis() - at < 60_000) L("刚刚开会时用过") else LF("%@ 开会时用过", relative(at)))
val text = (c[StepID.Text] as? State.Ok)?.seconds
val hear = (c[StepID.Hear] as? State.Ok)?.seconds
@@ -142,7 +126,6 @@ object AiCheckViews {
return (listOf(L("已连接")) + parts).joinToString(" · ")
}
- /// "2 分钟前" in the app's language (not the phone's, which may differ).
fun relative(at: Long): String {
val f = android.icu.text.RelativeDateTimeFormatter.getInstance(android.icu.util.ULocale.forLocale(Strings.locale), null,
android.icu.text.RelativeDateTimeFormatter.Style.SHORT, android.icu.text.DisplayContext.CAPITALIZATION_NONE)
@@ -157,8 +140,6 @@ object AiCheckViews {
// MARK: Home card (there is no tray: the card sits where 有新版本 does)
- /// Title and detail when the user must fix something; null otherwise. On a phone the service
- /// hears too, so most failures stop listening, not just the notes.
fun cardWords(app: CicadaApp): Pair<String, String>? {
val ling = app.ling
val c = ling.aiCheck
@@ -186,12 +167,9 @@ object AiCheckViews {
// MARK: 开始听
- /// 开始听 stops only on a failure already known: a hear model that takes no audio, or a service
- /// that still can't be reached after one more look. Anything else (unknown, busy) just starts.
fun start(a: Activity, kind: String) {
val app = a.cicada
val ling = app.ling
- // Already looking (the re-check below takes up to 20 s offline): one sheet, not two.
if (ling.aiCheck.running) return
when (ling.aiCheck.failure?.reason) {
Reason.Deaf -> deafSheet(a, kind)
@@ -214,7 +192,6 @@ object AiCheckViews {
}
}
- /// Whether 开始听 must stop and say why first (the tile hands it to the home screen).
fun blocks(app: CicadaApp) = app.ling.aiCheck.failure?.reason.let { it == Reason.Deaf || it == Reason.Unreachable }
private fun deafSheet(a: Activity, kind: String) {
@@ -250,7 +227,6 @@ object AiCheckViews {
d.show()
}
- /// The fix on top, full width: side by side, English cut "Check Again and Start" short.
private fun buttons(ui: Ui, quiet: Pair<String, () -> Unit>, primary: Pair<String, () -> Unit>?) = ui.stack(10).apply {
if (primary != null) addView(ui.button(primary.first, "primary") { primary.second() })
addView(ui.button(quiet.first, "quiet") { quiet.second() })
@@ -258,8 +234,6 @@ object AiCheckViews {
// MARK: Proxy (read only, to word the hint; the app never sets or uses a proxy of its own)
- /// A proxy set on the network in use (Wi-Fi › 代理, or a VPN app's), or for the whole phone.
- /// A phone has no proxy app port to look for, so only "on" or "none".
fun proxyHint(context: Context): AICheck.ProxyHint {
val cm = context.getSystemService(ConnectivityManager::class.java)
val link = try { cm?.getLinkProperties(cm.activeNetwork)?.httpProxy } catch (_: Exception) { null }
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt
index 271bff8..77a527a 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt
@@ -17,16 +17,11 @@ import cicada.Strings
import cicada.Strings.L
import cicada.Strings.LF
-/// 设置 › AI 服务 (AISettings.swift, the design's Android page): which service, its key and how
-/// the check went, what works with it (现在能用的, with 听对方 first: on the ports the service
-/// hears), and the models, each a row that opens its choices. The recommended ones are already
-/// chosen, so most people never open those.
class AiServiceActivity : Activity() {
private lateinit var ui: Ui
private lateinit var page: LinearLayout
private var unobserve: (() -> Unit)? = null
private var shown: String? = null
- /// A custom service's rows that are open (翻译和纪要, 听对方, 同传声音); null until the page first decides.
private var open: MutableSet<String>? = null
override fun onCreate(savedInstanceState: Bundle?) {
@@ -55,7 +50,6 @@ class AiServiceActivity : Activity() {
val name = name(p)
if (p.id == "custom") { customPage(app, c); return }
- // The service, its key (and a custom service's address).
page.addView(ui.sectionLabel(L("服务")))
val rows = mutableListOf<View>(choiceRow(L("服务"), Providers.ALL.map { it.id to label(it) }, p.id) { app.setAiProvider(it) })
val k = ling.currentKey()
@@ -70,11 +64,9 @@ class AiServiceActivity : Activity() {
if (k == null && p.site != null) rows.add(ui.listRow(LF("打开 %@", name), null, trailing = ui.icon(R.drawable.i_external, 18, Palette.link), chevron = false) {
try { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(p.site))) } catch (_: Exception) {}
})
- // Where it broke and the one thing that fixes it; all passed folds into the key's line.
val check = ling.aiCheck
if (k != null && AiCheckViews.showSteps(check)) rows.add(AiCheckViews.steps(this, ui, recheck = false) { editKey(this, ui) })
check.balanceLine(name)?.let { low ->
- // Wraps: English runs two lines.
rows.add(LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
@@ -101,11 +93,8 @@ class AiServiceActivity : Activity() {
page.addView(ui.helper(foot).apply { setPadding(ui.dp(16), ui.dp(12), ui.dp(16), 0) })
}
- /// 现在能用的 (AISettings.swift › usage): what each part of the app uses with this service.
private fun usesRows(app: CicadaApp, c: AIConfig, name: String): List<View> {
val ling = app.ling
- // Only what the last result supports: when the service can't be reached (or the key
- // fails) nothing says "用 ZenMux"; a deaf hear model greys only what hears.
val reason = ling.aiCheck.failure?.reason
val down = ling.hasKey && reason in listOf(AICheck.Reason.Unreachable, AICheck.Reason.BadAddress, AICheck.Reason.InvalidKey,
AICheck.Reason.MgmtKey, AICheck.Reason.NoCredit)
@@ -136,7 +125,6 @@ class AiServiceActivity : Activity() {
voice != null && ling.lastVoice?.first == true -> Triple(uses, 1, LF("%@ 的声音读给对方", voice) + " · " + L("上次同传时正常"))
else -> Triple(uses, 1, if (voice != null) LF("%@ 的声音读给对方", voice) else L("手机的声音读给对方"))
}
- // 改正听错的词 (AISettings.swift's row): a text request per finished line, switched in 词表.
val fix = when {
!on -> notReady
!app.settings.fixMisheard -> Triple(L("已关"), 0, L("在“词表”里打开"))
@@ -151,7 +139,6 @@ class AiServiceActivity : Activity() {
}
}
- /// 自己选模型: the hear, text and voice models; Ling's hear model is Ming, always.
private fun modelRows(app: CicadaApp, c: AIConfig): List<View> {
val p = c.provider
val s = app.settings
@@ -167,14 +154,9 @@ class AiServiceActivity : Activity() {
// MARK: Own service
- /// 其他(兼容 OpenAI)(AISettings.swift › customPage): one row per use, each at its own address if
- /// need be (a text model, an audio model and a speech model often run as separate servers),
- /// each opening to its fields and saying whether it works and how fast. On a phone the hear
- /// model is what listens: there is no on-device recognition to fall back to.
private fun customPage(app: CicadaApp, c: AIConfig) {
val ling = app.ling
val check = ling.aiCheck
- // A service that isn't set up yet, or doesn't work, opens where it needs filling in.
val opened = open ?: mutableSetOf<String>().also {
if (check.failure?.step == AICheck.StepID.Hear) it.add("hear") else if (!check.passed || check.slow) it.add("text")
open = it
@@ -193,7 +175,6 @@ class AiServiceActivity : Activity() {
})
val host = c.base?.let { Uri.parse(it).host } ?: L("你填的地址")
page.addView(ui.helper(LF("加密存在这台手机上,只发给 %@", keyHosts(app, c))).apply { setPadding(ui.dp(16), ui.dp(8), ui.dp(16), 0) })
- // Never "按所选模型计费" here: the user runs it, or their provider bills it its own way.
val nearby = c.base?.let(Providers::isNearby) ?: false
val foot = (if (nearby) L("跑在你自己的机器上,不按量计费。") else L("费用以这个服务为准。")) +
if (app.settings.aiCustomOnly) LF("会议的语音和文字只发给 %@,不经过 Google 等外部服务。", customHosts(c))
@@ -201,9 +182,6 @@ class AiServiceActivity : Activity() {
page.addView(ui.helper(foot).apply { setPadding(ui.dp(16), ui.dp(12), ui.dp(16), 0) })
}
- /// 语音和文字只发给你的服务 (AISettings.swift › onlyRow): Google is never asked. The grey line says
- /// what it costs, and while the service can't be reached, that new subtitles are the original
- /// only (a phone has no on-device translation to stand in).
private fun onlyRow(app: CicadaApp): View {
val on = app.settings.aiCustomOnly
val check = app.ling.aiCheck
@@ -213,17 +191,13 @@ class AiServiceActivity : Activity() {
return ui.switchRow(L("语音和文字只发给你的服务"), detail, on) { app.setCustomOnly(it) }
}
- /// Where the custom service's audio and text go: one host when every use shares it. On a phone
- /// the hear model always listens, so its address always counts.
private fun customHosts(c: AIConfig): String =
hostsLine(listOfNotNull(c.base, c.forNotes.base?.takeIf { c.notesApart }, c.hearBase, c.voiceBase?.takeIf { c.hasVoices }))
- /// Where the custom service's key is sent: every use's address, the notes' only while they share it.
private fun keyHosts(app: CicadaApp, c: AIConfig): String =
hostsLine(listOfNotNull(c.base, c.forNotes.base?.takeIf { c.notesApart && !app.ling.notesHasOwnKey }, c.hearBase,
c.voiceBase?.takeIf { c.hasVoices }))
- /// One host, "a 和 b", or 你填的地址 for more.
private fun hostsLine(bases: List<String>): String {
val hosts = bases.mapNotNull { Uri.parse(it).host }.distinct()
return when (hosts.size) {
@@ -233,7 +207,6 @@ class AiServiceActivity : Activity() {
}
}
- /// A row that opens to its fields: a state dot, the use, what it runs on, and how it's doing.
private fun useRow(id: String, open: MutableSet<String>, title: String, detail: String, dot: Int, trailing: String?,
trailingColor: Int = Palette.tertiary): View {
val row = ui.listRow(title, detail, leading = ui.dot(dot), trailing = trailing?.let { ui.text(it, 13f, trailingColor, lines = 1).apply { fontFeatureSettings = "tnum" } }) {
@@ -244,7 +217,6 @@ class AiServiceActivity : Activity() {
return row
}
- /// The fields under an open row, indented under its title.
private fun panel(vararg views: View?) = ui.stack(0).apply {
setPadding(ui.dp(18), 0, 0, ui.dp(8))
views.filterNotNull().forEach { addView(it) }
@@ -255,7 +227,6 @@ class AiServiceActivity : Activity() {
private fun badAddress(raw: String) =
if (raw.isNotBlank() && Providers.customBase(raw) == null) note(L("地址要用 https;这台手机和局域网里的服务可以用 http。"), Palette.link) else null
- /// An address as the row shows it: host and port ("192.168.1.20:8000").
private fun where(raw: String): String {
val u = Uri.parse(Providers.customBase(raw) ?: return raw)
return (u.host ?: raw) + if (u.port > 0) ":${u.port}" else ""
@@ -263,7 +234,6 @@ class AiServiceActivity : Activity() {
private val grey = android.graphics.Color.parseColor("#C4C7CE")
- /// "192.168.1.20 · qwen-mt-turbo", then the notes' model, or their own server after a bar.
private fun textDetail(c: AIConfig, host: String): String {
if (host.isEmpty() || c.textModel.isEmpty()) return L("填上地址和模型")
val line = "$host · ${short(c.textModel)}"
@@ -274,17 +244,13 @@ class AiServiceActivity : Activity() {
return if (n.textModel == c.textModel) line else line + " · ${short(n.textModel)}"
}
- /// 翻译和纪要 (AISettings.swift › textSection): 翻译's address, key and model, then 纪要 on the
- /// same service (another model at most) or another one with its own address and key.
private fun textSection(app: CicadaApp, c: AIConfig, open: MutableSet<String>, rows: MutableList<View>) {
val ling = app.ling
val s = app.settings
val check = ling.aiCheck
val host = c.base?.let { Uri.parse(it).host }.orEmpty()
val secs = check.translate?.let { "%.1f".format(Strings.locale, it.seconds) }
- // The hear model's own failure shows on its row: the text model may be fine.
val failed = check.textFailure != null
- // Translation works but the notes' own model or server doesn't.
val notesDown = !failed && check.notesFailed
val trailing = when {
check.running -> L("正在检查…")
@@ -341,8 +307,6 @@ class AiServiceActivity : Activity() {
isAccessibilityHeading = true
}
- /// 纪要: the same service as translation (another model at most), or another one with its own
- /// address and key. Switching back keeps what was typed.
private fun notesGroup(app: CicadaApp, c: AIConfig, host: String): List<View?> {
val ling = app.ling
val s = app.settings
@@ -372,7 +336,6 @@ class AiServiceActivity : Activity() {
return views
}
- /// After a check with notes apart: one row each, what it runs and how it did.
private fun checkRows(c: AIConfig, check: AICheck): View {
val t = check.translate!!
val notes = check.notes
@@ -391,8 +354,6 @@ class AiServiceActivity : Activity() {
row(L("纪要"), c.forNotes.textModel, notes?.ok ?: true, notesText))
}
- /// The notes' own key (另一个服务): paste, save, or remove it (back to the key above). It goes
- /// only to the notes' address.
private fun editNotesKey(app: CicadaApp, host: String) {
lateinit var dialog: android.app.Dialog
lateinit var submit: () -> Unit
@@ -425,10 +386,6 @@ class AiServiceActivity : Activity() {
box.requestFocus()
}
- /// A custom service's model (AISettings.swift › ModelPicker): the row shows it; tapping opens
- /// the names its `/models` lists, searchable, and takes a name it doesn't list (an alias, a
- /// model it hides). Without a list the sheet is a plain field. `sameLabel`: a first choice
- /// that clears the value (和翻译模型一样).
private fun modelPicker(label: String, current: String, placeholder: String, sameLabel: String?, host: String,
catalog: () -> List<String>, refetch: () -> Unit, pick: (String) -> Unit) =
ui.listRow(label, null, trailing = value(if (current.isEmpty()) sameLabel ?: L("未填") else short(current))) {
@@ -441,7 +398,6 @@ class AiServiceActivity : Activity() {
fun choose(id: String) { d.dismiss(); if (id != current) pick(id) }
val search = android.widget.EditText(this).apply {
setSingleLine()
- // Model ids: ASCII, no autocorrect, the URL keyboard.
inputType = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_VARIATION_URI
imeHintLocales = android.os.LocaleList(java.util.Locale.US)
imeOptions = android.view.inputmethod.EditorInfo.IME_ACTION_DONE or android.view.inputmethod.EditorInfo.IME_FLAG_FORCE_ASCII
@@ -476,7 +432,6 @@ class AiServiceActivity : Activity() {
val q = search.text.toString().trim()
listed = all.isNotEmpty()
if (shape != listed) {
- // No list: a plain field, saved with 保存; a list: search it, or use what was typed.
shape = listed
search.hint = if (listed) L("搜索或输入模型") else placeholder
scroll.visibility = if (listed) View.VISIBLE else View.GONE
@@ -492,7 +447,6 @@ class AiServiceActivity : Activity() {
}
search.setOnEditorActionListener { _, a, _ ->
if (a != android.view.inputmethod.EditorInfo.IME_ACTION_DONE) return@setOnEditorActionListener false
- // Done: the only match, else exactly what was typed.
val q = search.text.toString().trim()
val matches = catalog().filter { it.contains(q, ignoreCase = true) }
if (listed && q.isNotEmpty() && matches.size == 1) choose(matches[0]) else if (q.isNotEmpty() || !listed) choose(q)
@@ -514,7 +468,6 @@ class AiServiceActivity : Activity() {
addView(foot, ui.weight())
addView(again)
}
- // Without a list the field holds the name to edit; with one it searches.
if (catalog().isEmpty()) search.setText(current)
render()
val body = ui.stack(10, search, scroll, footer, buttons)
@@ -525,7 +478,6 @@ class AiServiceActivity : Activity() {
search.requestFocus()
}
- /// 听对方: the hear model, which may run on its own server; its state is the check's hear step.
private fun hearSection(app: CicadaApp, c: AIConfig, open: MutableSet<String>, rows: MutableList<View>) {
val ling = app.ling
val s = app.settings
@@ -550,7 +502,6 @@ class AiServiceActivity : Activity() {
))
}
- /// 同传声音: the speech model that reads 我说 to the other side; empty is the phone's voice.
private fun voiceSection(app: CicadaApp, c: AIConfig, open: MutableSet<String>, rows: MutableList<View>) {
val ling = app.ling
val s = app.settings
@@ -570,7 +521,6 @@ class AiServiceActivity : Activity() {
))
}
- /// Recommended models first, with why, then everything else the service lists.
private fun modelRow(label: String, helper: String?, recommended: List<Model>, listed: List<String>, current: String, pick: (String) -> Unit): View {
val options = recommended.map { it.id to (it.id + if (it.note.isNotEmpty()) " · " + L(it.note) else "") }.toMutableList()
for (id in listed) if (options.none { it.first == id }) options.add(id to id)
@@ -585,11 +535,9 @@ class AiServiceActivity : Activity() {
ui.choose(this, label, options, selected) { changed(it) }
}
- /// A typed value (a custom service's address and models): the row shows it, tapping edits it.
private fun fieldRow(label: String, current: String, hint: String, helper: String?, empty: String = L("未填"),
shown: (String) -> String = ::short, save: (String) -> Unit) =
ui.listRow(label, helper, trailing = value(if (current.isEmpty()) empty else shown(current))) {
- // Addresses, model ids and voice names: ASCII, no autocorrect, the URL keyboard.
ui.input(this, label, current, helper = helper, hint = hint,
type = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_VARIATION_URI) { if (it != current) save(it) }
}
@@ -598,11 +546,8 @@ class AiServiceActivity : Activity() {
fun name(p: Provider) = if (p.id == "custom") L(p.name) else p.name
fun label(p: Provider) = if (p.id == "ling") "Ling" + L("(推荐)") else name(p)
- /// A model id without its vendor ("qwen3.8-omni-flash"): the rows are narrow.
fun short(id: String) = id.substringAfterLast('/')
- /// The service's own voice for 我说 (Ming on Ling, Gemini on OpenRouter and ZenMux), or null:
- /// the phone's. Which of its voices is 读出来的声音's choice.
fun cloudVoice(app: CicadaApp): String? {
val c = app.ling.config()
if (!app.ling.speaks) return null
@@ -611,13 +556,11 @@ class AiServiceActivity : Activity() {
return if ("gemini" in m.lowercase()) "Gemini" else short(m)
}
- /// How the service is doing, under its key; null when there's nothing to say.
fun status(app: CicadaApp): String? {
val ling = app.ling
val check = ling.aiCheck
if (!ling.hasKey) return null
if (check.running) return L("正在检查…")
- // Named after the step that failed: a missing model is not a connection problem.
check.failure?.takeIf { it.reason != AICheck.Reason.Busy }?.let {
return when (it.step) {
AICheck.StepID.Reach -> L("暂时连不上")
@@ -629,7 +572,6 @@ class AiServiceActivity : Activity() {
return AiCheckViews.summary(check)
}
- /// The 设置 row's line: connected (and what that costs in delay), or what's wrong.
fun summary(app: CicadaApp): String {
val ling = app.ling
val k = ling.currentKey() ?: return L("还没填 API key")
@@ -639,9 +581,6 @@ class AiServiceActivity : Activity() {
return status(app) ?: L("已连接")
}
- /// The prefix says whose key it is: a management key can't call models, and another
- /// service's key goes there with one tap (改用 %@ into `into`), never a silent switch.
- /// True when the key isn't for `service`: don't save it here.
fun keyHint(ui: Ui, key: String, service: String, status: android.widget.TextView, into: LinearLayout, switched: () -> Unit): Boolean {
val (owner, management) = AICheck.owner(key) ?: return false
if (management) {
@@ -661,7 +600,6 @@ class AiServiceActivity : Activity() {
return true
}
- /// Change or remove the key of the service in use: a sheet with the field, 粘贴, and 删除.
fun editKey(activity: Activity, ui: Ui) {
val app = activity.cicada
val p = app.ling.provider
@@ -670,7 +608,6 @@ class AiServiceActivity : Activity() {
lateinit var dialog: android.app.Dialog
lateinit var submit: () -> Unit
val box = ui.keyField { submit() }
- // A service on this phone or the local network may need none (the key is optional there).
val base = app.ling.config().base
if (p.id == "custom" && base != null && Providers.isNearby(base)) box.hint = L("本机和局域网服务可不填")
val field = LinearLayout(activity).apply {
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
index 101766f..bca75ab 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
@@ -36,9 +36,6 @@ import java.io.File
import java.util.Locale
import java.util.concurrent.Executors
-/// The process: wires the engines together (AppModel on the Mac, Controller on Windows) and tells
-/// the screens when something changed. Engine events arrive on worker threads; `observe`
-/// callbacks run on the main thread, coalesced to one per frame.
class CicadaApp : Application() {
lateinit var settings: AppSettings
lateinit var key: AIKey
@@ -53,9 +50,7 @@ class CicadaApp : Application() {
lateinit var overlay: Overlay
lateinit var voice: Voice
lateinit var updates: AppUpdates
- /// 存到文件夹 (设置 › 会后存一份).
lateinit var folderExport: FolderExporter
- /// 分享…: the share service on cicada.indaloop.app (Share.kt). Its version without "-dev".
val share by lazy {
ShareClient("android", (packageManager.getPackageInfo(packageName, 0).versionName ?: "0.0.0").substringBefore('-'))
}
@@ -65,21 +60,13 @@ class CicadaApp : Application() {
private var refreshQueued = false
private var tileListening = false
private var samplePlayer: MediaPlayer? = null
- /// Why the last listening couldn't start or ended early, shown on the main screen.
@Volatile var startProblem: String? = null
- /// Cicada's own screens in front: the floating window is for other apps, so it waits.
private var resumed = 0
- /// One of Cicada's screens is in front.
val foreground get() = resumed > 0
- /// Android silenced our recording: a phone call, or another app holding the microphone.
@Volatile var micSilenced = false
- /// The user closed the floating window (×) for this meeting.
var overlayClosed = false
- /// 在视频上看 asked for it in this meeting, whatever 悬浮窗 is set to.
var overlayThisMeeting = false
- /// 保存会议录音: the meeting's recorder while one runs.
private var recorder: Recorder? = null
- /// 导入录音或视频: the file being transcribed, while it is.
@Volatile var importing: FileSource? = null; private set
override fun onCreate() {
@@ -90,14 +77,11 @@ class CicadaApp : Application() {
if (BuildConfig.DEBUG) Log.sink = { android.util.Log.d("Cicada", it) }
settings = AppSettings.load()
SpeakerLabels.voices = settings.speakerVoices
- // The phone's whole language list, not the app's own locale: "follow system" falls back to
- // the next one when they speak mine (the Mac's Locale.preferredLanguages).
AppSettings.systemLanguages = {
val list = android.content.res.Resources.getSystem().configuration.locales
(0 until list.size()).map { list[it].toLanguageTag() }
}
loadStrings()
- // The AI service in use (设置 › AI 服务): its key file, address and models, read on every call.
key = AIKey(KeystoreProtector, service = { settings.aiProvider })
ling = LingClient(key, config = { settings.aiConfig() })
ling.proxyHint = { AiCheckViews.proxyHint(this) }
@@ -109,7 +93,6 @@ class CicadaApp : Application() {
translator = Translator(ling)
translator.googleOff = settings.customOnly
listen = ListenEngine(ling, translator, store, notes, settings)
- // 改正听错的词: the phone's ICU gives the pinyin the sound check compares, as the Mac's system transform does.
Correction.pinyinOf = Pinyin::of
vocabulary = Vocabulary()
fixes = LiveFixes(store, vocabulary, settings)
@@ -118,7 +101,6 @@ class CicadaApp : Application() {
translator.onFixes = { text, edits -> fixes.received(text, edits) }
fixes.onChange(::changed)
vocabulary.onChange(::changed)
- // 说话人识别: voiceprints on the phone, names from Ling once two voices are on show.
listen.speakers = SpeakerTagger(NativeVoiceprints.create(this))
namer = SpeakerNamer(ling, store)
listen.onVoice = { namer.guess(it) }
@@ -133,27 +115,21 @@ class CicadaApp : Application() {
listen.onChange(::changed)
notes.onChange(::changed)
store.onChange { changed() }
- // 存到文件夹: written once a record is settled, rewritten when it changes, forgotten (not
- // deleted) with it. "" is the records read at launch: try what was waiting.
store.onChange { id -> main.post {
if (id.isEmpty()) folderExport.retry()
else if (store.get(id) == null) folderExport.deleted(id) else folderExport.saved(id)
} }
notes.finalDone = { id -> main.post { folderExport.settled(id) } }
- main.post { folderExport.retry() } // the records may have been read before the listener was in
+ main.post { folderExport.retry() }
ling.onChange(::changed)
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
- // Meetings are private: the recent-apps preview shows a blank card, not the transcript
- // (Android 13+). Screenshots of the app itself still work.
override fun onActivityPreCreated(a: android.app.Activity, b: android.os.Bundle?) {
if (Build.VERSION.SDK_INT >= 33 && a !is ProjectionActivity) a.setRecentsScreenshotEnabled(false)
}
override fun onActivityResumed(a: android.app.Activity) {
- // Coming back from elsewhere (a grant fixed, storage back): 存到文件夹 tries again.
if (resumed++ == 0) folderExport.retry()
updateOverlay()
}
- // Moving between Cicada's own screens pauses one before resuming the next: wait a beat.
override fun onActivityPaused(a: android.app.Activity) { resumed--; main.postDelayed(::updateOverlay, 400) }
override fun onActivityCreated(a: android.app.Activity, b: android.os.Bundle?) {}
override fun onActivityStarted(a: android.app.Activity) {}
@@ -198,20 +174,13 @@ class CicadaApp : Application() {
val canOverlay get() = Settings.canDrawOverlays(this)
- /// Playback capture needs the projection consent first: ProjectionActivity asks, then hands
- /// the result to ListenService. The microphone and files start straight away.
- /// Between 开始听 and the service starting (permissions, the consent dialog): further taps wait.
@Volatile var starting = 0L
- /// From a screen, a known AI service failure first gets its sheet (AiCheckViews.start).
fun startListening(context: Context, kind: String, gate: Boolean = true) {
if (gate && context is android.app.Activity && !listen.listening && ling.hasKey) { AiCheckViews.start(context, kind); return }
startIntent(context, kind, gate = false)?.let { context.startActivity(it) }
}
- /// What starting takes: the permissions and consent screen, or onboarding without a key. Null
- /// while already listening or starting (a second tap). The Quick Settings tile opens it itself;
- /// a known failure sends it to the home screen, which says why (`gate`).
fun startIntent(context: Context, kind: String, gate: Boolean = true): Intent? {
if (listen.listening) return null
if (System.currentTimeMillis() - starting < 60_000) return null
@@ -223,7 +192,6 @@ class CicadaApp : Application() {
return Intent(context, ProjectionActivity::class.java).putExtra("kind", kind).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
- /// Called by ListenService once it is in the foreground, with the source it made.
fun began(source: AudioSource, kind: String) {
starting = 0
micSilenced = false
@@ -248,18 +216,15 @@ class CicadaApp : Application() {
// MARK: 我说 (面对面)
fun holdToSay() {
- // Pressing again while the phone still speaks: stop it, it's my turn.
if (voice.speaking) { voice.stop(); listen.muted = false }
listen.hold()
}
fun releaseToSay() = listen.release()
- /// 读出来的声音 for a language: the one chosen in settings, or its default (VoiceCatalog.chosen).
fun voiceId(lang: String): String =
VoiceCatalog.chosen(settings.speakVoices, lang, ling.config(), ling.speaks, ling.clones && VoiceReference.exists)
- /// 用这个声音: keeps the recording and uses it for `lang` (the language the picker was on).
fun saveVoiceReference(pcm: ShortArray, text: String, lang: String): Boolean = try {
VoiceReference.save(pcm, text)
Log.d("voice clone saved ${pcm.size / 16000} s")
@@ -268,7 +233,6 @@ class CicadaApp : Application() {
true
} catch (e: Exception) { Log.d("voice clone save failed ${e.javaClass.simpleName}"); false }
- /// 删除: the recording goes, and every language that used it is back on its default.
fun removeVoiceReference() {
VoiceReference.remove()
settings.speakVoices.entries.removeAll { it.value == VoiceCatalog.CLONE }
@@ -276,8 +240,6 @@ class CicadaApp : Application() {
Log.d("voice clone removed")
}
- /// Reads `text` in a service voice id (not the phone's): Ming's or Gemini's by name, or the
- /// user's own cloned from the saved recording. Failed when it can't (the caller falls back).
private fun speakIn(id: String, text: String, lang: String, onStart: () -> Unit, onEnd: () -> Unit,
draft: Pair<String, String>? = null): Voice.Result {
if (id == VoiceCatalog.CLONE) {
@@ -289,10 +251,6 @@ class CicadaApp : Application() {
else voice.speakCloud(ling, text, id.removePrefix(VoiceCatalog.CLOUD), null, onStart, onEnd)
}
- /// My words in their language, out of the phone's speaker. The mic is muted for the segmenter
- /// meanwhile (and a beat after, for the room's echo) so the phone doesn't hear itself as them.
- /// The voice chosen for their language reads them (Ming's on Ling, Gemini's on OpenRouter and
- /// ZenMux); the phone's reads them when that is the choice, and when a service's voice fails.
private fun speakAloud(text: String, lang: String) {
listen.muted = true
changed()
@@ -309,12 +267,8 @@ class CicadaApp : Application() {
speakWithPhone(text, lang)
}
- /// The voice being tried (试听 / 试一句), shown as a spinner on its row.
@Volatile var previewing: String? = null; private set
- /// Plays a voice on the speaker with a line in `lang` (the Mac's previewVoice); not a meeting
- /// line, so nothing is muted. `draft`: a recording not saved yet, for the clone (录好了).
- /// `failed` comes on the main thread with why nothing played.
fun previewVoice(id: String, lang: String, text: String = VoiceCatalog.sample(lang), draft: Pair<String, String>? = null,
failed: (String) -> Unit = {}) {
voice.stop()
@@ -342,7 +296,6 @@ class CicadaApp : Application() {
val r = voice.speak(text, lang, onStart = { changed() }, onEnd = {
main.postDelayed({ if (!voice.speaking) { listen.muted = false; changed() } }, 400)
})
- // A TTS engine that drops the utterance never calls back: don't stay deaf to the other side.
if (r == Voice.Result.Spoken) main.postDelayed({ if (listen.muted && !voice.speaking) { listen.muted = false; changed() } }, 3_000L + text.length * 150L)
if (r != Voice.Result.Spoken) {
listen.muted = false
@@ -351,15 +304,10 @@ class CicadaApp : Application() {
}
// MARK: Meeting end (the Mac's MeetingEndWatch: on Android only "nobody spoke", since no app
- // may see another one's microphone; so no hang-up signal and no 会议应用挂断后结束)
- /// The meeting ends at `deadline` unless someone keeps it going: the 正在听 strip, the floating
- /// window and the notification show it.
@Volatile var ending: MeetingEndWatch.Pending? = null; private set
- /// The last meeting ended by itself: 首页 says 会议已自动结束 instead of nothing.
@Volatile var autoEnded = false; private set
private var endWatch: MeetingEndWatch? = null
- /// Debug (`endtimes <silence> <countdown>`): seconds instead of minutes, to test it.
var endTimesOverride: Pair<Double, Double>? = null
private fun now() = System.currentTimeMillis() / 1000.0
@@ -380,7 +328,6 @@ class CicadaApp : Application() {
val reason = w.tick(now(), emptyMap(), said)
setEnding(w.pending)
if (reason != null) { autoEnd(reason, w); return }
- // Every second while counting down (the seconds left show), else every 2 s as on the Mac.
main.postDelayed(this, if (w.pending != null) 1000 else 2000)
}
}
@@ -409,18 +356,14 @@ class CicadaApp : Application() {
fun endingDetail(p: MeetingEndWatch.Pending) = Strings.LF("%lld 秒后结束会议并整理纪要", endingLeft(p))
- /// "继续记录" on the ending prompt.
fun keepRecording() {
endWatch?.keepGoing(now())
setEnding(null)
Log.d("meeting end: kept going")
}
- /// Ends where the meeting really ended: a little after the last words. Never before a line
- /// that was kept (lastSpeech is when the newest line arrived).
private fun autoEnd(reason: MeetingEndWatch.Reason, w: MeetingEndWatch) {
if (reason == MeetingEndWatch.Reason.NobodySpoke) {
- // Nothing to keep or summarise: back to 开始听, not 会议已自动结束.
Log.d("meeting end: nobody spoke for ${w.config.silenceAfter.toInt()} s, stopped")
stopListening()
return
@@ -430,7 +373,6 @@ class CicadaApp : Application() {
stopListening(endedAt = at) { autoEnded = true; changed() }
}
- /// The 正在听 screen, brought to the front.
fun openLive() {
startActivity(Intent(this, ListeningActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
}
@@ -445,10 +387,8 @@ class CicadaApp : Application() {
val imported = importing; importing = null
background.execute {
listen.stop(endedAt)
- // The whole meeting read once more for names.
recId?.let { namer.guess(it, force = true) }
if (imported != null && recId != null) store.update(recId) { it.importing = null }
- // A meeting or an imported file is over: 存到文件夹 writes it once its notes are.
recId?.let { id -> main.post { folderExport.ended(id) } }
rec?.finish { ok -> if (ok && recId != null && store.get(recId) != null) store.update(recId) { it.hasAudio = true } }
main.post {
@@ -462,13 +402,11 @@ class CicadaApp : Application() {
}
}
- /// A WAV (16 kHz or any PCM16) heard as if it were playing: the sample meeting and `feed`.
fun listenToFile(file: File?, play: Boolean, showLive: Boolean = !play) {
if (listen.listening) return
if (!ling.hasKey) { startProblem = noKeyText(); changed(); return }
val source = if (file != null) PcmAudioSource(file) else PcmAudioSource({ assets.open("sample.wav").use { Wav.read(it) } })
source.onEnded = { reason ->
- // A file that finished: give the last segment's reply a moment, then end the meeting.
main.postDelayed({ if (listen.listening && listen.sourceKind == "file") stopListening() }, if (reason == null) 3000 else 0)
}
overlayClosed = false
@@ -490,8 +428,6 @@ class CicadaApp : Application() {
changed()
}
- /// The floating window shows while listening with another app in front (unless turned off
- /// or closed), and goes when listening ends: inside Cicada the screens show the same.
fun updateOverlay() {
val want = listen.listening && (settings.overlay || overlayThisMeeting) && canOverlay && resumed == 0 && !overlayClosed
if (want) overlay.show() else if (!overlay.forced) overlay.hide()
@@ -507,12 +443,10 @@ class CicadaApp : Application() {
// MARK: AI 服务
- /// "需要 Ling key 才能听", or the service in use named.
fun noKeyText(): String = ling.provider.let { p ->
if (p.id == "ling") Strings.L("需要 Ling key 才能听") else Strings.LF("需要 %@ 的 key 才能听", Strings.L(p.name))
}
- /// 设置 › AI 服务: another service, with its own key file and models; checked again (`check`).
fun setAiProvider(id: String, check: Boolean = true) {
if (Providers.named(id).id != id || id == settings.aiProvider) return
settings.aiProvider = id
@@ -521,8 +455,6 @@ class CicadaApp : Application() {
aiChanged(check)
}
- /// "改用 Ling" where another service is out of reach: only when a Ling key is already saved,
- /// so the one tap works without a trip to the settings.
val canSwitchToLing: Boolean get() = settings.aiProvider != "ling" && Paths.keyFile("ling").isFile
fun switchToLing() {
@@ -530,13 +462,11 @@ class CicadaApp : Application() {
setAiProvider("ling")
}
- /// A model chosen over the recommended one ("text", "hear" or "voice"; "" goes back to it).
fun setAiModel(kind: String, model: String) {
val s = settings
val p = s.aiProvider
if (kind == "text" && p == "ling") s.model = model.ifEmpty { LingClient.DEFAULT_MODEL }
else if (kind == "notes") {
- // The custom service's notes model; empty: the translation model.
if (model.isNotEmpty()) s.aiModels[Providers.NOTES_MODEL] = model else s.aiModels.remove(Providers.NOTES_MODEL)
} else {
val table = when (kind) { "text" -> s.aiModels; "hear" -> s.aiHearModels; "voice" -> s.aiVoiceModels; else -> return }
@@ -546,7 +476,6 @@ class CicadaApp : Application() {
aiChanged()
}
- /// 纪要 › 同一个服务 / 另一个服务 (the custom service): off keeps the typed address.
fun setNotesOwn(on: Boolean) {
settings.aiCustomNotesOwn = on
settings.save()
@@ -559,24 +488,19 @@ class CicadaApp : Application() {
aiChanged()
}
- /// Notes' own key (另一个服务), sealed like the others; null removes it (back to the key above).
fun setNotesKey(raw: String?): Boolean {
val ok = if (raw == null) { ling.removeNotesKey(); true } else ling.setNotesKey(raw)
if (ok) aiChanged()
return ok
}
- /// The service, its address, models or key changed: forget the old check and check again.
fun aiChanged(check: Boolean = true) {
- // 语音和文字只发给你的服务 acts on the custom service only: another service brings Google back.
translator.googleOff = settings.customOnly
ling.keyChanged()
if (check && ling.hasKey) background.execute { ling.check() }
changed()
}
- /// 语音和文字只发给你的服务: kept for every service, in effect for the custom one. The service is
- /// the same, so its check stays (not aiChanged, which forgets it).
fun setCustomOnly(on: Boolean) {
settings.aiCustomOnly = on
settings.save()
@@ -585,11 +509,8 @@ class CicadaApp : Application() {
changed()
}
- /// 重新检查.
fun recheck() { if (ling.hasKey && !ling.aiCheck.running) background.execute { ling.check() } }
- /// One tap on 换成推荐的 ("text" or "hear"): the service's first recommended model, then a
- /// fresh check. Never done without that tap.
fun useRecommended(kind: String) {
val p = ling.provider
val first = (if (kind == "hear") p.hearModels else p.textModels).firstOrNull()?.id ?: return
@@ -597,8 +518,6 @@ class CicadaApp : Application() {
setAiModel(kind, if (p.id == "ling") first else "")
}
- /// A key pasted for one service that belongs to another (改用 OpenRouter): switch, save it
- /// there (the key file follows the service), check.
fun switchService(id: String, key: String) {
settings.aiProvider = id
settings.save()
@@ -608,9 +527,6 @@ class CicadaApp : Application() {
aiChanged()
}
- /// Any change of route (Wi-Fi back, a VPN or proxy turned on) waits 3 s for the network to
- /// settle, then the client looks again if the service was unreachable. No timer: nothing is
- /// checked while the network stays the same.
private fun watchNetwork() {
val cm = getSystemService(android.net.ConnectivityManager::class.java) ?: return
val recheck = Runnable { background.execute { ling.networkChanged() } }
@@ -623,7 +539,6 @@ class CicadaApp : Application() {
} catch (e: Exception) { Log.d("ai: no network callback ${e.javaClass.simpleName}") }
}
- /// 保存会议录音: what is heard goes to system.m4a as it comes (the Mac keeps it the same way).
private fun startRecording() {
val id = listen.sessionId ?: return
if (!settings.recordAudio) return
@@ -634,8 +549,6 @@ class CicadaApp : Application() {
// MARK: 导入录音或视频 (the Mac's FileImport)
- /// From 首页's 导入 or another app's 分享到知了: the file is transcribed as a meeting (dated
- /// now, named after the file) in the foreground service, so it goes on in the background.
fun importFile(context: Context, uri: android.net.Uri) {
if (listen.listening) { startProblem = Strings.L("正在听的时候不能导入,先结束这场会议"); changed(); return }
if (!ling.hasKey) { context.startActivity(Intent(context, OnboardingActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); return }
@@ -645,15 +558,12 @@ class CicadaApp : Application() {
context.startForegroundService(intent)
}
- /// Called by ListenService once it is in the foreground.
fun beginImport(uri: android.net.Uri) {
if (listen.listening) return
val name = FileSource.name(this, uri)
val source = FileSource(this, uri)
source.onEnded = { reason ->
if (reason != null) main.post { startProblem = Strings.L("这个文件读不出声音"); changed() }
- // A file that finished: give the last segments' replies a moment, then end the meeting.
- // The record lasts as long as the file, not as long as transcribing it took.
main.postDelayed({
if (!listen.listening || importing !== source) return@postDelayed
val start = listen.sessionId?.let { store.get(it) }?.startedAt
@@ -667,15 +577,12 @@ class CicadaApp : Application() {
startRecording()
Log.d("import: started")
changed()
- // Progress for the screens and the notification, a few times a second.
val tick = object : Runnable {
override fun run() { if (importing === source) { changed(); main.postDelayed(this, 500) } }
}
main.postDelayed(tick, 500)
}
- /// The system language, or this app's own in Settings › App languages (Android 13+), changed:
- /// the screens are recreated, and they read the new table.
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig)
if (settings.uiLanguage == "system") { loadStrings(); changed() }
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Capture.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Capture.kt
index a899caa..fe84983 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/Capture.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Capture.kt
@@ -12,14 +12,11 @@ import cicada.AudioSource
import cicada.Log
import cicada.Segmenter
-/// Reads an AudioRecord at 16 kHz mono on its own thread and hands each buffer on: the audio
-/// thread only copies, ListenEngine's worker does the rest. Android resamples for us.
abstract class RecordSource : AudioSource {
override var onSamples: ((ShortArray) -> Unit)? = null
override var onEnded: ((String?) -> Unit)? = null
@Volatile private var running = false
private var record: AudioRecord? = null
- /// Android silenced this recording (a call, or another app holding the microphone), or let it go.
var onSilenced: ((Boolean) -> Unit)? = null
protected open fun watch(r: AudioRecord) {}
protected open fun unwatch() {}
@@ -43,7 +40,7 @@ abstract class RecordSource : AudioSource {
Log.d("capture: ${javaClass.simpleName} started")
Thread({
Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO)
- val buf = ShortArray(Segmenter.RATE / 10) // 100 ms
+ val buf = ShortArray(Segmenter.RATE / 10)
while (running) {
val n = r.read(buf, 0, buf.size)
if (n > 0) onSamples?.invoke(buf.copyOf(n))
@@ -59,9 +56,6 @@ abstract class RecordSource : AudioSource {
override fun stop() { running = false }
}
-/// What other apps play (Android 10+): media, games and unknown usages, never Cicada itself.
-/// Call and meeting apps are not captured (their usage is voice communication, and apps can opt
-/// out), which is why there is a microphone mode too.
class PlaybackSource(private val projection: MediaProjection, private val ownUid: Int) : RecordSource() {
@SuppressLint("MissingPermission")
override fun make(format: AudioFormat, bufferBytes: Int): AudioRecord {
@@ -77,13 +71,10 @@ class PlaybackSource(private val projection: MediaProjection, private val ownUid
override fun released() { projection.stop() }
}
-/// 面对面: the phone's microphone, tuned for speech.
class MicSource(private val context: android.content.Context) : RecordSource() {
private var callback: android.media.AudioManager.AudioRecordingCallback? = null
private val audio get() = context.getSystemService(android.media.AudioManager::class.java)
- // During a phone call Android keeps the recording running but feeds it silence: say so
- // instead of looking like nobody is talking.
override fun watch(r: AudioRecord) {
val session = r.audioSessionId
val cb = object : android.media.AudioManager.AudioRecordingCallback() {
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
index 6358c42..1c96436 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
@@ -15,33 +15,12 @@ import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
-/// Debug commands for dev builds over `adb shell am broadcast` (scripts/cicadactl.sh): the
-/// Android counterpart of the Mac's tools/lsctl and the Windows pipe. One command per broadcast,
-/// one JSON line back as the broadcast's result (never meeting text or the key).
-/// state | start [playback|mic] | stop | feed <wav in files/> | sample | view notes|subtitles
-/// capture on|off | overlay show|hide | show main|live|records|settings|words|onboarding|record [id] | overlay collapse|expand | key reload
-/// hear|say <wav in files/> (面对面: the other side / me holding 我说) | tts <lang> <text>
-/// import <session.json in files/> | importfile <audio or video in files/> | face | onboarded on|off | target <code> | ui <lang> | clip <text>
-/// provider ling|openrouter|zenmux|custom | ai-model hear|text|voice|notes <id> ("" back to the recommended) | show ai
-/// ai-base <url> (the custom service's address) · ai-notes same|own · ai-notes-base <url> · notes-key import <file in files/>|remove (the custom service's 纪要)
-/// key import <file in files/> (sealed as the current service's key, the plain file deleted) | voice-try (设置's 试一句)
-/// voice <lang>[=<id>] (读出来的声音: choose, or say it and the options) · voice-preview <lang> [<id>] (试听) · show voices [lang]
-/// voiceref <wav in files/> [lang] | remove (我自己的声音 from a pushed recording) · show record-voice <lang> [<wav in files/>]
-/// ai-check (重新检查) | ai-check-sim <reason|lowBalance|off> (every check ends that way; the state's ai.check has the steps)
-/// 改正听错的词: fixes on|off · asknames on|off · silent (a meeting with no audio) · heard <text> · vocab add|remove|state
-/// fixstate · fixanswer yes|no · fixrevert <line> · fixlater · fixundo · fixedit <line>=<text>[|one][|keep0] · pinyin <text>
-/// 分享…: share <id>[,full][,pw] · unshare <id> · shares · shareSheet <id> (no id: closes it) · delete <id>
-/// shareserver [url] (a local Worker; none: cicada.indaloop.app) · clipboard
-/// 存到文件夹: export state · export folder <tree uri> (one already granted; else the problem shows) · export pick
-/// (the system picker) · export all (也存一份) · export retry · export off
-/// 会议记录's search: search <text> · search-open [n] · search-step 1|-1 (state: record.search)
class DebugReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (!BuildConfig.DEBUG) return
val app = context.cicada
val line = intent.getStringExtra("cmd") ?: "state"
val pending = goAsync()
- // UI work on the main thread; the reply waits for it, then for state to settle.
app.background.execute {
val done = CountDownLatch(1)
var reply: Map<String, Any?> = emptyMap()
@@ -59,7 +38,6 @@ class DebugReceiver : BroadcastReceiver() {
}
}
- /// Empty: "reply with the state once the command has had a moment".
private fun run(app: CicadaApp, line: String): Map<String, Any?> {
val parts = line.trim().split(Regex("\\s+"), 2)
val arg = parts.getOrElse(1) { "" }
@@ -72,16 +50,13 @@ class DebugReceiver : BroadcastReceiver() {
"stop" -> app.stopListening()
"feed" -> app.listenToFile(File(app.filesDir, arg), play = false)
"sample" -> app.listenToFile(null, play = true)
- // 导入录音或视频 without the file picker: any audio or video in files/.
"importfile" -> app.importFile(app, android.net.Uri.fromFile(File(app.filesDir, arg)))
"face" -> app.startActivity(Intent(app, FaceActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
"view" -> app.setView(if (arg == "subtitles") "subtitles" else "notes")
"capture" -> { app.settings.showInCapture = arg == "on"; app.saveSettings(); app.overlay.rebuild() }
"overlay" -> if (arg == "collapse") { app.overlay.collapsed = true; app.overlay.rebuild() } else if (arg == "expand") { app.overlay.collapsed = false; app.overlay.rebuild() } else if (arg == "hide") { app.overlay.forced = false; app.overlay.hide() } else { app.overlay.forced = true; app.overlay.show() }
- // 面对面 without a voice: `hear` plays a WAV as the other side, `say` as me holding 我说.
"hear" -> app.listen.inject(Wav.read(File(app.filesDir, arg).inputStream()))
"say" -> { app.holdToSay(); app.listen.inject(Wav.read(File(app.filesDir, arg).inputStream())); app.releaseToSay() }
- // 会议自己结束 in seconds: `endtimes 20 10` (silence, countdown); `endtimes` alone resets.
"endtimes" -> { val v = arg.split(Regex("\\s+")).mapNotNull { it.toDoubleOrNull() }; app.endTimesOverride = if (v.size == 2) v[0] to v[1] else null }
"silence" -> { app.settings.silenceEnd = arg.ifEmpty { "prompt" }; app.saveSettings() }
"keep" -> app.keepRecording()
@@ -92,12 +67,9 @@ class DebugReceiver : BroadcastReceiver() {
}
"target" -> { app.settings.target = arg.ifEmpty { "system" }; app.saveSettings() }
"ui" -> { app.settings.uiLanguage = arg.ifEmpty { "system" }; app.saveSettings(); app.loadStrings(); app.overlay.rebuild() }
- // Puts text on the clipboard (the shell can't), so 粘贴 can be tested.
"clip" -> app.getSystemService(android.content.ClipboardManager::class.java).setPrimaryClip(android.content.ClipData.newPlainText("test", arg))
"onboarded" -> { app.settings.onboarded = arg != "off"; app.saveSettings() }
"key" -> if (arg.startsWith("import ")) {
- // A key pushed in as a plain file: sealed into the current service's key file like
- // one pasted in, and the plain copy goes at once.
val f = File(app.filesDir, arg.removePrefix("import ").trim())
val text = try { f.readText().trim() } catch (_: Exception) { "" } finally { f.delete() }
if (text.isEmpty() || !app.key.save(text)) return mapOf("error" to "no key in ${f.name}")
@@ -108,7 +80,6 @@ class DebugReceiver : BroadcastReceiver() {
"ai-base" -> { app.settings.aiCustomBase = arg.removeSurrounding("\"").trim(); app.settings.save(); app.aiChanged(); return mapOf("ok" to true, "ai" to ai(app)) }
"ai-notes" -> { app.setNotesOwn(arg == "own"); return mapOf("ok" to true, "ai" to ai(app)) }
"ai-notes-base" -> { app.setNotesBase(arg.removeSurrounding("\"")); return mapOf("ok" to true, "ai" to ai(app)) }
- // The notes' own key, pushed in as a plain file like `key import`, sealed, the plain copy deleted.
"notes-key" -> {
if (arg == "remove") { app.setNotesKey(null); return mapOf("ok" to true, "ai" to ai(app)) }
val f = File(app.filesDir, arg.removePrefix("import ").trim())
@@ -116,15 +87,12 @@ class DebugReceiver : BroadcastReceiver() {
if (text.isEmpty() || !app.setNotesKey(text)) return mapOf("error" to "no key in ${f.name}")
return mapOf("ok" to true, "ai" to ai(app))
}
- // The 改用 Ling on a status line (says when it isn't offered).
"switchToLing" -> { val offered = app.canSwitchToLing; app.switchToLing(); return mapOf("offered" to offered, "ai" to ai(app)) }
- // ai-check-sim <reason|lowBalance|off>: every check ends this way (screenshots of each state).
"ai-check-sim" -> {
app.ling.simulateCheck = cicada.AICheck.reasonNamed(arg)
app.ling.simulateBalance = if (arg == "lowBalance") 0.4 else null
app.background.execute { app.ling.check() }
}
- // 重新检查.
"ai-check" -> app.background.execute { app.ling.check() }
"ai-model" -> {
val kind = arg.substringBefore(' ')
@@ -132,11 +100,8 @@ class DebugReceiver : BroadcastReceiver() {
app.setAiModel(kind, model)
return mapOf("ok" to true, "ai" to ai(app))
}
- // 语音和文字只发给你的服务 (the Mac's aiCustomOnly:on|off): `ai-custom-only on|off`.
"ai-custom-only" -> { app.setCustomOnly(arg == "on"); return mapOf("ok" to true, "ai" to ai(app)) }
"voice-try" -> { app.previewVoice(app.voiceId("en"), "en", SettingsActivity.SAMPLE) { Log.d("debug: voice-try failed") }; return mapOf("voice" to app.voiceId("en")) }
- // 读出来的声音: `voice <lang>=<id>` chooses (en=ming:UK_George, zh=phone; en= back to the
- // default), `voice <lang>` says what it is and what's offered; `voice-preview <lang> <id>` is 试听.
"voice" -> {
val lang = arg.substringBefore('=')
if ('=' in arg) {
@@ -147,9 +112,6 @@ class DebugReceiver : BroadcastReceiver() {
return mapOf("lang" to lang, "voice" to app.voiceId(lang), "options" to VoiceCatalog.options(lang, app.ling.config()).map { it.id },
"clone" to VoiceReference.exists, "cloneSeconds" to VoiceReference.duration, "clones" to app.ling.clones)
}
- // 我自己的声音 without a microphone: `voiceref <wav in files/> [<lang>]` checks a pushed
- // recording as 录制 would (Ming hears it) and saves it for <lang>; `voiceref remove` is 删除.
- // Replies with numbers only (never what it says).
"voiceref" -> {
if (arg == "remove") { app.removeVoiceReference(); return mapOf("exists" to VoiceReference.exists) }
val name = arg.substringBefore(' ')
@@ -170,7 +132,6 @@ class DebugReceiver : BroadcastReceiver() {
app.previewVoice(id, lang) { Log.d("debug: preview failed $it") }
return mapOf("previewing" to id)
}
- // 检查更新 against a test feed: the dev build checks only once one is set.
"updatefeed" -> { app.updates.setFeed(if (arg.isEmpty() || arg.contains("://")) arg else File(app.filesDir, arg).path); app.updates.checkIfDue(0) }
"update" -> when (arg) {
"check" -> app.updates.checkNow()
@@ -178,14 +139,10 @@ class DebugReceiver : BroadcastReceiver() {
"job" -> app.background.execute { app.updates.checkInBackground() }
"notify" -> app.updates.available?.let { app.updates.notifyAbout(it) }
}
- // 改正听错的词 (the Mac's fixes / askNames / silentListen / heard / vocab* / fix* commands).
"fixes" -> { app.settings.fixMisheard = arg != "off"; app.saveSettings() }
"asknames" -> { app.settings.askNames = arg != "off"; app.saveSettings() }
- // A meeting with no audio at all, its lines given by `heard <text>` (translated and fixed
- // by the AI service in use, as a heard line is).
"silent" -> if (!app.listen.listening) { app.listen.start(SilentAudioSource(), "file"); app.openLive() }
"heard" -> app.listen.debugHeard(arg)
- // vocab add Morpho=莫拉、莫法|巡检 · vocab remove <word> · vocab state
"vocab" -> {
val (sub, rest) = arg.split(Regex("\\s+"), 2).let { it[0] to it.getOrElse(1) { "" } }
when (sub) {
@@ -195,12 +152,12 @@ class DebugReceiver : BroadcastReceiver() {
return mapOf("terms" to app.vocabulary.terms.size, "heard" to app.vocabulary.terms.sumOf { it.heard.size }, "fixes" to app.vocabulary.terms.sumOf { it.fixes })
}
"fixstate" -> return fixState(app, arg.ifEmpty { null })
- "fixanswer" -> { // fixanswer yes|no [session]
+ "fixanswer" -> {
val id = sessionOf(app, arg.substringAfter(' ', ""))
val f = app.fixes.asking(id)?.fix ?: app.fixes.pending(id).firstOrNull()?.fix ?: return mapOf("error" to "nothing waiting")
app.fixes.answer(f, arg.substringBefore(' ') == "yes", id)
}
- "fixrevert" -> { // fixrevert <line> [session]: the line's first applied fix
+ "fixrevert" -> {
val id = sessionOf(app, arg.substringAfter(' ', ""))
val l = app.store.line(id, arg.substringBefore(' ')) ?: return mapOf("error" to "no line")
val f = l.fixes?.firstOrNull { it.applied } ?: return mapOf("error" to "no fix")
@@ -208,7 +165,7 @@ class DebugReceiver : BroadcastReceiver() {
}
"fixlater" -> { val id = sessionOf(app, arg); app.fixes.asking(id)?.let { app.fixes.later(it.fix, id) } }
"fixundo" -> app.fixes.undo()
- "fixedit" -> { // fixedit <line>=<new text>[|one][|keep0] [, session]
+ "fixedit" -> {
val (head, sid) = if (arg.contains(",") && !arg.substringAfterLast(",").contains("=")) arg.substringBeforeLast(",") to arg.substringAfterLast(",").trim() else arg to ""
val line = head.substringBefore("=")
val opts = head.substringAfter("=").split("|")
@@ -221,7 +178,6 @@ class DebugReceiver : BroadcastReceiver() {
app.store.import(s)
}
"delete" -> app.store.delete(arg)
- // rename <id>=<title>, as typed into the record's title (empty: the automatic one).
"rename" -> app.store.rename(arg.substringBefore('='), arg.substringAfter('=', ""))
"export" -> {
val ex = app.folderExport
@@ -235,8 +191,6 @@ class DebugReceiver : BroadcastReceiver() {
else -> return ex.debugState()
}
}
- // 分享… (the Mac's share: / unshare: / shareSheet:): `share <id>[,full][,pw]` shares as the
- // sheet would and logs the link; `unshare <id>` turns it off; `shares` lists them (never the token).
"share" -> {
val p = arg.split(",").map { it.trim() }
val s = app.store.get(p[0])?.let { Session.from(it.toJson()) } ?: return mapOf("error" to "no such record")
@@ -257,14 +211,11 @@ class DebugReceiver : BroadcastReceiver() {
app.background.execute { Log.d("debug: share revoked ${app.share.revoke(r, arg)}") }
return mapOf("unsharing" to arg)
}
- // `shareserver http://127.0.0.1:8790` (after adb reverse) points 分享… at a local Worker (wrangler dev), with its
- // own device file so the real one stays registered; no argument goes back to cicada.indaloop.app.
"shareserver" -> {
app.share.base = arg.ifEmpty { "https://cicada.indaloop.app" }.trimEnd('/')
app.share.deviceFile = if (arg.isEmpty()) null else File(cicada.Paths.root, "share-device-local.json")
return mapOf("shareserver" to app.share.base)
}
- // What is on the clipboard (the app must be in front to read it).
"clipboard" -> return mapOf("clipboard" to app.getSystemService(android.content.ClipboardManager::class.java)
.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text?.toString())
"shares" -> return mapOf("shares" to cicada.ShareStore.all().mapValues { (_, r) ->
@@ -273,9 +224,6 @@ class DebugReceiver : BroadcastReceiver() {
"shareSheet" -> if (arg.isEmpty()) ShareSheet.open?.let { it.dismiss() } else
app.startActivity(Intent(app, RecordActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra("id", arg).putExtra("share", true))
- // 会议记录's search (#33): `search <text>` types it into 会议记录, `search-open [n]` taps the
- // n-th meeting found (0: the first), `search-step 1|-1` is 下一个 / 上一个 in the record.
- // The state's record.search has the matches, where it is and the line's id.
"search" -> app.startActivity(Intent(app, RecordsActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtra("query", arg))
"search-open" -> {
val r = RecordsActivity.current ?: return mapOf("error" to "会议记录 is not in front")
@@ -290,7 +238,6 @@ class DebugReceiver : BroadcastReceiver() {
"words" -> open(WordListActivity::class.java)
"ai" -> open(AiServiceActivity::class.java)
"voices" -> open(VoicesActivity::class.java, arg.substringAfter(' ', "").ifEmpty { null })
- // `show record <lang> [<wav in files/>]`: 录制 for that language; a WAV stands in for the mic.
"record-voice" -> {
val rest = arg.substringAfter(' ', "").split(' ')
app.startActivity(Intent(app, VoiceRecordActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@@ -308,11 +255,9 @@ class DebugReceiver : BroadcastReceiver() {
}
companion object {
- /// The meeting a fix command is for: the one named, else the live one, else the newest.
fun sessionOf(app: CicadaApp, arg: String): String =
arg.trim().ifEmpty { null } ?: app.store.liveId ?: app.store.all().firstOrNull()?.id ?: ""
- /// A meeting's fixes in numbers (never its words): lines fixed, applied, waiting, said no to.
fun fixState(app: CicadaApp, arg: String?): Map<String, Any?> {
val id = sessionOf(app, arg ?: "")
val lines = app.store.lines(id)
@@ -326,7 +271,6 @@ class DebugReceiver : BroadcastReceiver() {
"translated" to lines.count { it.dst != null }, "terms" to app.vocabulary.terms.size)
}
- /// The AI service in use and what its last check found (never the key itself).
fun ai(app: CicadaApp): Map<String, Any?> {
val l = app.ling
val c = l.config()
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/FaceActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/FaceActivity.kt
index 93821b1..1d6cbb0 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/FaceActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/FaceActivity.kt
@@ -13,10 +13,6 @@ import android.widget.TextView
import cicada.Strings.L
import cicada.TranscriptLine
-/// 面对面翻译: the phone flat between two people. The top half is turned to the other side and
-/// shows the newest line in their language (what I said, translated; or what they said, so they
-/// see it was heard); the bottom half shows it in mine. Hold the button to speak: on release the
-/// phone reads my words aloud in their language (only ever a translation: ListenEngine.speakable).
class FaceActivity : Activity() {
private lateinit var ui: Ui
private lateinit var theirLabel: TextView
@@ -65,7 +61,6 @@ class FaceActivity : Activity() {
else -> true
}
}
- // TalkBack's double tap is a click: once to start, again to finish.
hold.setOnClickListener { if (cicada.listen.holding) cicada.releaseToSay() else cicada.holdToSay(); update() }
val close = ui.roundButton(R.drawable.i_close, L("收起")) { finish() }
val middle = FrameLayout(this).apply {
@@ -88,7 +83,6 @@ class FaceActivity : Activity() {
}, LinearLayout.LayoutParams(-1, -2))
clipChildren = false
}
- // The system bars' insets go on the outer frame: fitsSystemWindows replaces a view's own padding.
setContentView(FrameLayout(this).apply {
setBackgroundColor(Palette.ground)
fitsSystemWindows = true
@@ -116,12 +110,10 @@ class FaceActivity : Activity() {
val key = listOf(line?.id, line?.shown, line?.dst, l.holding, l.saying, app.voice.speaking, l.sayProblem, their).joinToString("|")
if (key == shown) return
shown = key
- // What each side reads, in their own language.
val mine = line?.speaker == "me"
val translated = line?.dst?.takeIf { it.isNotEmpty() && it != line.shown }
theirLabel.text = NotesViews.languageName(their)
theirText.text = when { line == null -> "…"; mine -> translated ?: "…"; else -> line.shown }
- // My line was said with 我说: the other side heard its translation (同传, as on the Mac).
myLabel.text = (if (mine) L("你 · 同传") else if (line == null) L("你") else L("对方")) + " · " + NotesViews.languageName(mineLang)
myText.text = when { line == null -> L("按住下面的按钮说话,松开后对方会听到译文"); mine -> line.shown; else -> translated ?: line.shown }
myText.setTextColor(if (line == null) Palette.secondary else Palette.ink)
@@ -136,7 +128,6 @@ class FaceActivity : Activity() {
hint.text = if (l.holding) L("松开,说给对方") else L("松开后用 {lang} 读出来").replace("{lang}", NotesViews.languageName(their))
hold.background = ui.ripple(ui.rounded(if (live) Palette.accent else Palette.ink, 52), 52, dark = true)
holdIcon.setColorFilter(if (live) Palette.ink else android.graphics.Color.WHITE)
- // The ring says "I'm listening to you" while held.
hold.foreground = if (l.holding) ui.rounded(0, 52, 0x40E8552B, 10) else null
}
}
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/FileSource.kt b/android/app/src/main/kotlin/com/wquguru/cicada/FileSource.kt
index 1200a97..1ef6dfd 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/FileSource.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/FileSource.kt
@@ -9,15 +9,10 @@ import cicada.AudioSource
import cicada.Log
import cicada.Segmenter
-/// 导入录音或视频: a file's sound, decoded by the phone's own codecs (anything Android plays: m4a,
-/// mp3, wav, mp4, mov…), mixed to mono and resampled to 16 kHz, handed on as it decodes. Paced at
-/// `speed` × real time: faster than a meeting, slow enough that Ming keeps up (each segment takes
-/// ~2 s whatever its length, so several are in flight). Streams, so an hour never sits in memory.
class FileSource(private val context: Context, private val uri: Uri, private val speed: Double = 2.5) : AudioSource {
override var onSamples: ((ShortArray) -> Unit)? = null
override var onEnded: ((String?) -> Unit)? = null
@Volatile private var stopped = false
- /// Seconds handed on so far, and the file's length (0 until known).
@Volatile var done = 0.0; private set
@Volatile var total = 0.0; private set
@@ -27,7 +22,7 @@ class FileSource(private val context: Context, private val uri: Uri, private val
val reason = try { decode(); null } catch (e: Exception) {
Log.d("import: decode failed ${e.javaClass.simpleName}: ${e.message}"); "unreadable"
}
- if (!stopped && reason == null) onSamples?.invoke(ShortArray(Segmenter.RATE)) // the last sentence's pause
+ if (!stopped && reason == null) onSamples?.invoke(ShortArray(Segmenter.RATE))
onEnded?.invoke(reason)
}, "FileSource").apply { isDaemon = true }.start()
}
@@ -47,7 +42,7 @@ class FileSource(private val context: Context, private val uri: Uri, private val
codec.start()
var rate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE)
var channels = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT)
- var pos = 0.0 // the resampler's place in the input, in input samples
+ var pos = 0.0
var carry = 0.0f; var hasCarry = false
val started = System.nanoTime()
var handed = 0L
@@ -74,13 +69,11 @@ class FileSource(private val context: Context, private val uri: Uri, private val
buf.position(info.offset); buf.limit(info.offset + info.size)
val shorts = buf.asShortBuffer()
val frames = shorts.remaining() / channels
- // Mono, then linear resampling to 16 kHz.
val mono = FloatArray(frames)
for (f in 0 until frames) { var sum = 0f; for (c in 0 until channels) sum += shorts.get(f * channels + c); mono[f] = sum / channels }
codec.releaseOutputBuffer(o, false)
val step = rate.toDouble() / Segmenter.RATE
val out = ArrayList<Short>(((frames / step) + 2).toInt())
- // `pos` runs from -1 (the previous buffer's last sample, `carry`) to frames-1.
while (pos < frames - 1 || (pos < frames && frames == 1)) {
val i0 = Math.floor(pos).toInt()
val a = if (i0 < 0) (if (hasCarry) carry else mono[0]) else mono[i0]
@@ -92,7 +85,6 @@ class FileSource(private val context: Context, private val uri: Uri, private val
pos -= frames
if (frames > 0) { carry = mono[frames - 1]; hasCarry = true }
if (out.isNotEmpty()) {
- // In 100 ms pieces, like a capture callback, paced at `speed`.
val all = out.toShortArray()
var k = 0
val chunk = Segmenter.RATE / 10
@@ -117,7 +109,6 @@ class FileSource(private val context: Context, private val uri: Uri, private val
}
companion object {
- /// The file's name as the picker or the sharing app gives it ("访谈录像.mp4").
fun name(context: Context, uri: Uri): String {
try {
context.contentResolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/FixViews.kt b/android/app/src/main/kotlin/com/wquguru/cicada/FixViews.kt
index aff4828..c97f1b8 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/FixViews.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/FixViews.kt
@@ -24,12 +24,7 @@ import cicada.Strings.L
import cicada.Strings.LF
import cicada.TranscriptLine
-/// 改正听错的词 on screen (the Mac's FixViews.swift and the fixing parts of NotesViews.swift): the
-/// fixed words dotted, what each was heard as with 改回, the 这样改对吗? card, the banner over a
-/// finished meeting, 改这句… and the 撤销 message. A phone has no pointer to hover with: a line's
-/// fixed words open with a long press (the record) or show under the newest line (正在听).
object FixViews {
- /// A fixed word: drawn as it is, with a dotted line under it (Android has no dotted underline).
class Dotted(private val color: Int, private val dp: Float) : ReplacementSpan() {
override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int {
if (fm != null) paint.getFontMetricsInt(fm)
@@ -47,7 +42,6 @@ object FixViews {
}
}
- /// The line as shown, each fixed word dotted, words waiting for the user (这样改对吗?) washed pale.
fun text(ui: Ui, line: TranscriptLine, prefix: String = ""): CharSequence {
val fixes = line.fixes ?: return prefix + line.src
val a = Correction.apply(fixes, line.src)
@@ -61,7 +55,6 @@ object FixViews {
return s
}
- /// "听成 莫拉 → Morpho" with the grey parts grey.
private fun heardAs(from: String, to: String): CharSequence {
val head = L("听成") + " "
val arrow = " → "
@@ -71,7 +64,6 @@ object FixViews {
return s
}
- /// Under a line: each applied fix, what it was heard as, and 改回.
fun fixedWords(ui: Ui, lineId: String, fixes: List<LineFix>, onRevert: (String, LineFix) -> Unit): View? {
val applied = fixes.filter { it.applied }
if (applied.isEmpty()) return null
@@ -95,8 +87,6 @@ object FixViews {
return box
}
- /// 这样改对吗?: a name sound can't check, asked about once. 对 fixes every line waiting on it and
- /// adds it to the word list; × (稍后再看) asks again after the meeting.
fun confirmCard(ui: Ui, a: LiveFixes.Asking, onAnswer: (Boolean) -> Unit, onLater: (() -> Unit)?): View {
val (from, to) = Correction.label(a.fix)
val card = ui.stack(0)
@@ -127,8 +117,6 @@ object FixViews {
return card
}
- /// Above a finished meeting's transcript: how many words were fixed, and the ones waiting for the
- /// user, one at a time (对 / 不对 / 改成…). Nothing when there was nothing to fix.
fun reviewBanner(ui: Ui, fixes: LiveFixes, s: Session, onShow: (String) -> Unit, onEdit: (TranscriptLine, String) -> Unit): View? {
val waiting = fixes.pending(s.id)
val fixed = fixes.store.lines(s.id).sumOf { l -> (l.fixes ?: emptyList()).count { it.applied } }
@@ -154,7 +142,6 @@ object FixViews {
return box
}
- /// A long press on a line in the record: its fixed words with 改回, and 改这句….
fun lineSheet(activity: Activity, ui: Ui, app: CicadaApp, sessionId: String, line: TranscriptLine) {
lateinit var d: android.app.Dialog
val box = ui.stack(10)
@@ -166,8 +153,6 @@ object FixViews {
d.show()
}
- /// 改这句…: the line as shown, to rewrite. What changed becomes the user's own fix, on every line
- /// heard the same way or only this one, and (made everywhere) joins the word list.
fun edit(activity: Activity, ui: Ui, app: CicadaApp, sessionId: String, line: TranscriptLine, start: String) {
lateinit var d: android.app.Dialog
val field = android.widget.EditText(activity).apply {
@@ -186,14 +171,12 @@ object FixViews {
fun update() {
val same = app.fixes.sameHeard(line.id, sessionId, field.text.toString())
heard.visibility = if (same == null) View.GONE else View.VISIBLE
- // Only a word for a word can teach the list: an added or dropped word can't.
keep.visibility = if (same != null && same.swap) View.VISIBLE else View.GONE
scope.visibility = if (same != null && same.count > 1) View.VISIBLE else View.GONE
if (same != null) {
heard.text = LF("听成 %@", same.heard)
everywhere.text = LF("整场听成 %@ 的 %lld 处都改", same.heard, same.count)
}
- // Only a change made everywhere teaches the word list.
keep.isEnabled = same == null || same.count <= 1 || everywhere.isChecked
}
field.addTextChangedListener(object : android.text.TextWatcher {
@@ -220,8 +203,6 @@ object FixViews {
field.requestFocus()
}
- /// The last fix decision said back for a few seconds, with 撤销, over the bottom of a screen
- /// (Android's own toast can't carry a button).
class Toast(private val activity: Activity, private val ui: Ui, private val app: CicadaApp, private val above: Int = 24) {
private var view: View? = null
private var shownAt = 0L
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/FolderExportViews.kt b/android/app/src/main/kotlin/com/wquguru/cicada/FolderExportViews.kt
index 3dd2f95..4d44973 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/FolderExportViews.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/FolderExportViews.kt
@@ -11,19 +11,15 @@ import cicada.Strings
import cicada.Strings.L
import cicada.Strings.LF
-/// 设置 › 会后存一份 and the record's line under its title (the Mac's FolderExportViews.swift).
-/// There is no default folder on a phone: the system's folder picker chooses, and its grant is kept.
object FolderExportViews {
const val PICK = 41
- /// The section: label, card, and the grey 上次存于 line under it.
fun section(activity: Activity, ui: Ui, page: LinearLayout) {
val ex = activity.cicada.folderExport
page.addView(ui.sectionLabel(L("会后存一份")))
val rows = mutableListOf<View>(ui.switchRow(L("存到文件夹"), L("纪要和文字记录存成 Markdown;文件夹同步到哪,内容就到哪"), ex.on) { on ->
when {
!on -> ex.turnOff()
- // A folder chosen before whose grant still holds: on again, as on the Mac.
ex.tree?.let { t -> activity.contentResolver.persistedUriPermissions.any { it.uri == t && it.isWritePermission } } == true -> ex.choose(ex.tree!!)
else -> pick(activity)
}
@@ -53,7 +49,6 @@ object FolderExportViews {
}
}
- /// A lost grant and a folder that is gone look the same from here: 找不到, and 重新选.
private fun problemRow(activity: Activity, ui: Ui, problem: FolderExporter.Problem): View {
val ex = activity.cicada.folderExport
val box = ui.stack(2).apply { setPadding(ui.dp(12), ui.dp(10), ui.dp(12), ui.dp(10)) }
@@ -77,7 +72,6 @@ object FolderExportViews {
}
}
- /// The system's folder picker, starting at Documents (or the folder in use).
fun pick(activity: Activity) {
val start = activity.cicada.folderExport.tree?.let { DocumentsContract.buildDocumentUriUsingTree(it, DocumentsContract.getTreeDocumentId(it)) }
?: DocumentsContract.buildDocumentUri("com.android.externalstorage.documents", "primary:Documents")
@@ -90,7 +84,6 @@ object FolderExportViews {
} catch (e: Exception) { Log.d("folder export: no folder picker ${e.javaClass.simpleName}") }
}
- /// The picker's answer: the grant kept, the folder chosen. Cancelled: the switch stays (or goes back) off.
fun picked(activity: Activity, resultCode: Int, data: Intent?) {
val uri = data?.data
if (resultCode != Activity.RESULT_OK || uri == null) { activity.cicada.changed(); return }
@@ -100,8 +93,6 @@ object FolderExportViews {
activity.cicada.folderExport.choose(uri)
}
- /// The record's grey line: where its file is, or why it isn't there yet. Null when there is
- /// nothing to say (off, or the record isn't settled).
fun recordLine(activity: Activity, ui: Ui, s: Session): View? {
val ex = activity.cicada.folderExport
if (!ex.on || !ex.ready(s)) return null
@@ -115,7 +106,6 @@ object FolderExportViews {
when {
!pending && ex.file(s.id) != null -> {
val reveal = ex.revealIntent(s.id)
- // Nothing opens Markdown here: the line ends at the folder.
row.addView(note(LF("已存到 %@ ·", ex.shortPath).let { if (reveal == null) it.removeSuffix("·").trimEnd() else it }))
if (reveal != null) row.addView(link(L("打开")) {
try { activity.startActivity(reveal) } catch (e: Exception) { Log.d("folder export: reveal failed ${e.javaClass.simpleName}") }
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/FolderExporter.kt b/android/app/src/main/kotlin/com/wquguru/cicada/FolderExporter.kt
index 655d5c6..0645b03 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/FolderExporter.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/FolderExporter.kt
@@ -20,26 +20,17 @@ import java.io.File
import java.time.Instant
import java.util.concurrent.Executors
-/// 存到文件夹 (docs/folder-export.md, the Mac's FolderExporter): writes settled meetings as Markdown
-/// into the folder the user picked (a SAF tree, held by a persisted grant) and keeps the index of
-/// what it wrote. State lives on the main thread; the files are written one at a time on its own
-/// thread, through DocumentsContract, since a provider may be slow or remote.
class FolderExporter(private val app: CicadaApp) {
enum class Problem {
- /// The grant is gone (the user revoked it, or the app was restored without it).
Denied,
- /// The folder, or the storage it was on, is gone.
Missing,
Failed,
}
var index: FolderExportIndex; private set
var problem: Problem? = null; private set
- /// Failed's provider message.
var problemText: String? = null; private set
- /// Checking a newly chosen folder.
var checking = false; private set
- /// The folder is an Obsidian vault itself (it has `.obsidian`): the 位置 row says so.
var vault = false; private set
private val settings get() = app.settings
@@ -47,7 +38,6 @@ class FolderExporter(private val app: CicadaApp) {
private val indexFile = File(Paths.root, "FolderExport.json")
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "FolderExport").apply { isDaemon = true } }
private var scheduled: Runnable? = null
- /// Told about this problem already (cleared once a write works).
private var notified = false
init { index = FolderExportIndex.load(indexFile) }
@@ -55,10 +45,8 @@ class FolderExporter(private val app: CicadaApp) {
val on get() = settings.exportOn && settings.exportFolder.isNotEmpty()
val tree: Uri? get() = settings.exportFolder.takeIf { it.isNotEmpty() }?.let(Uri::parse)
- /// "Documents › Cicada": the folder and the one it is in, named when it was chosen.
val shortPath: String get() = settings.exportName.ifEmpty { "Cicada" }
- /// The record's file, when it is written to this folder.
fun file(id: String): Uri? {
if (!on || index.folder != settings.exportFolder || index.files[id] == null) return null
return index.uris[id]?.let(Uri::parse)
@@ -66,18 +54,14 @@ class FolderExporter(private val app: CicadaApp) {
fun isPending(id: String) = on && id in index.pending
- /// Ended, not being imported, with something said.
fun ready(s: Session) = s.endedAt != null && s.importing != true && s.lines.isNotEmpty() && s.id != store.liveId
- /// Settled records not written to this folder yet.
val unwritten: List<Session> get() = store.all().filter { ready(it) && index.files[it.id] == null && it.id !in index.pending }
- /// What the screens' keys compare, so they rebuild when any of it changes.
fun stateKey(): String = listOf(on, settings.exportName, problem, problemText, checking, vault, index.pending.size, index.files.size, index.lastAt, unwritten.size).joinToString("|")
// MARK: Triggers (main thread)
- /// A meeting ended or an import finished: write it once it is settled.
fun ended(id: String) {
if (!on) return
if (id !in index.pending) index.pending.add(id)
@@ -85,17 +69,14 @@ class FolderExporter(private val app: CicadaApp) {
schedule()
}
- /// A record changed: rewrite it if it was written, or write it if it is waiting.
fun saved(id: String) {
if (!on || (index.files[id] == null && id !in index.pending)) return
if (id !in index.pending) index.pending.add(id)
schedule()
}
- /// The final notes pass for a meeting is over (done, failed, or no key).
fun settled(id: String) { if (on && id in index.pending) schedule() }
- /// 也存一份: every settled record not written yet.
fun writeAll() {
if (!on) return
index.pending.addAll(unwritten.map { it.id })
@@ -103,13 +84,11 @@ class FolderExporter(private val app: CicadaApp) {
flush(fromMeeting = false)
}
- /// At launch (once the records are read) and when the app comes forward: try what is waiting.
fun retry() {
if (!on || index.pending.isEmpty() || !store.loaded) return
schedule(500, fromMeeting = false)
}
- /// The record is gone from Cicada; its file stays.
fun deleted(id: String) {
if (index.files.remove(id) == null && !index.pending.remove(id)) return
index.uris.remove(id)
@@ -118,8 +97,6 @@ class FolderExporter(private val app: CicadaApp) {
// MARK: Choosing the folder
- /// A new folder (its grant already taken), or the same one again: start its index and check it
- /// can be written now, so a problem shows while settings is open, not when a meeting ends.
fun choose(folder: Uri) {
val text = folder.toString()
if (settings.exportFolder.isNotEmpty() && settings.exportFolder != text) release(Uri.parse(settings.exportFolder))
@@ -156,12 +133,10 @@ class FolderExporter(private val app: CicadaApp) {
app.changed()
}
- /// The folder Cicada writes in no longer: its grant goes back (an app holds at most 128 or 512).
private fun release(old: Uri) {
try { app.contentResolver.releasePersistableUriPermission(old, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) } catch (_: Exception) {}
}
- /// The folder in the Files app, if anything opens a folder.
fun openFolderIntent(): Intent? {
val t = tree ?: return null
val doc = DocumentsContract.buildDocumentUriUsingTree(t, DocumentsContract.getTreeDocumentId(t))
@@ -170,7 +145,6 @@ class FolderExporter(private val app: CicadaApp) {
.takeIf { it.resolveActivity(app.packageManager) != null }
}
- /// The record's file in a Markdown viewer, or null when nothing opens text/markdown.
fun revealIntent(id: String): Intent? {
val uri = file(id) ?: return null
return Intent(Intent.ACTION_VIEW).setDataAndType(uri, "text/markdown")
@@ -195,7 +169,6 @@ class FolderExporter(private val app: CicadaApp) {
class Stopped(val problem: Problem, val message: String? = null) : Outcome()
}
- /// Renders what is settled here, writes it on the worker.
private fun flush(fromMeeting: Boolean) {
val folder = tree
if (!on || folder == null || !store.loaded) return
@@ -233,23 +206,19 @@ class FolderExporter(private val app: CicadaApp) {
problem = stopped?.problem; problemText = stopped?.message
Log.d("folder export: ${outcomes.count { it is Outcome.Wrote }} written, ${outcomes.count { it is Outcome.Unchanged }} unchanged${stopped?.let { ", stopped: ${it.problem}" } ?: ""}")
if (stopped == null) notified = false
- // A lost grant is told once after a meeting (never for 也存一份); a missing folder never.
if (stopped?.problem == Problem.Denied && fromMeeting && !notified) { notified = true; notifyDenied() }
app.changed()
}
- /// On the worker. Stops at the first problem: the rest would fail the same way.
private fun write(resolver: ContentResolver, folder: Uri, jobs: List<Job>, ours: MutableMap<String, String>): List<Outcome> {
Saf.access(app, folder)?.let { return listOf(Outcome.Stopped(it)) }
val out = mutableListOf<Outcome>()
try {
- // Child queries ignore a selection on most providers: list once, match names here.
val listing = Saf.children(resolver, folder)
val parent = Saf.root(folder)
for (job in jobs) {
val mine = ours.filterKeys { it != job.id }.values.toSet()
val name = FolderExportFormat.fileName(job.stem) { c -> c != job.old && (c in mine || c in listing) }
- // The stored URI is a hint; a path-based provider gives a renamed file a new one.
val existing = job.old?.let { listing[it] }
val doc: Uri
if (existing != null && name == job.old) {
@@ -257,7 +226,6 @@ class FolderExporter(private val app: CicadaApp) {
Saf.write(resolver, existing, job.text)
doc = existing
} else if (existing != null) {
- // A new name moves the file: renamed in place, else written anew and the old one deleted.
val renamed = try { DocumentsContract.renameDocument(resolver, existing, name) } catch (e: SecurityException) { throw e } catch (_: Exception) { null }
if (renamed != null) {
listing.remove(job.old); doc = renamed
@@ -272,7 +240,6 @@ class FolderExporter(private val app: CicadaApp) {
doc = Saf.create(resolver, parent, name)
Saf.write(resolver, doc, job.text)
}
- // SAF may have named it otherwise (a collision it saw, an extension it added).
val actual = Saf.displayName(resolver, doc) ?: name
listing[actual] = doc
ours[job.id] = actual
@@ -305,7 +272,6 @@ class FolderExporter(private val app: CicadaApp) {
try { nm.notify(NOTIFICATION, n); Log.d("folder export: notified denied") } catch (e: Exception) { Log.d("folder export: notification not shown ${e.javaClass.simpleName}") }
}
- /// The debug command's view (`export state`): no meeting text, only names and counts.
fun debugState(): Map<String, Any?> = mapOf(
"on" to on, "folder" to settings.exportFolder, "short" to shortPath, "problem" to problem?.name, "message" to problemText,
"checking" to checking, "vault" to vault, "files" to index.files.toSortedMap(), "pending" to index.pending.toList(),
@@ -319,14 +285,11 @@ class FolderExporter(private val app: CicadaApp) {
}
}
-/// The Storage Access Framework calls 存到文件夹 makes, on the exporter's worker thread.
object Saf {
class Probe(val problem: FolderExporter.Problem?, val message: String? = null)
- /// The tree's own document.
fun root(tree: Uri): Uri = DocumentsContract.buildDocumentUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree))
- /// The grant first (cheap and certain), then whether the folder still answers.
fun access(app: CicadaApp, tree: Uri): FolderExporter.Problem? {
val granted = app.contentResolver.persistedUriPermissions.any { it.uri == tree && it.isWritePermission }
if (!granted) return FolderExporter.Problem.Denied
@@ -335,12 +298,10 @@ object Saf {
} catch (_: SecurityException) { FolderExporter.Problem.Denied }
}
- /// Writes and deletes a hidden file: the check after choosing a folder.
fun probe(app: CicadaApp, tree: Uri): Probe {
access(app, tree)?.let { return Probe(it) }
val r = app.contentResolver
return try {
- // octet-stream: a provider adds no extension to a name it has no type for.
val doc = DocumentsContract.createDocument(r, root(tree), "application/octet-stream", ".cicada-check") ?: throw IllegalStateException("not created")
try { DocumentsContract.deleteDocument(r, doc) } catch (_: Exception) {}
Probe(null)
@@ -348,7 +309,6 @@ object Saf {
catch (e: Exception) { Probe(FolderExporter.Problem.Failed, e.message ?: e.javaClass.simpleName) }
}
- /// The folder's files by name.
fun children(r: ContentResolver, tree: Uri): MutableMap<String, Uri> {
val out = HashMap<String, Uri>()
val uri = DocumentsContract.buildChildDocumentsUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree))
@@ -362,7 +322,6 @@ object Saf {
return out
}
- /// Null when the provider doesn't answer: the document (or folder) is gone.
fun displayName(r: ContentResolver, doc: Uri): String? = try {
r.query(doc, arrayOf(Document.COLUMN_DISPLAY_NAME), null, null, null)?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
} catch (e: SecurityException) { throw e } catch (_: Exception) { null }
@@ -374,8 +333,6 @@ object Saf {
r.openInputStream(doc)?.use { it.readBytes().toString(Charsets.UTF_8) }
} catch (e: SecurityException) { throw e } catch (_: Exception) { null }
- /// No atomic replace in SAF, so the caller skips unchanged text. "wt" truncates; "w" only for a
- /// provider that rejects "wt" (most providers truncate on "w" too).
fun write(r: ContentResolver, doc: Uri, text: String) {
val bytes = text.toByteArray(Charsets.UTF_8)
val stream = try { r.openOutputStream(doc, "wt") } catch (e: SecurityException) { throw e } catch (_: IllegalArgumentException) { null }
@@ -383,8 +340,6 @@ object Saf {
stream.use { it.write(bytes) }
}
- /// "Documents › Cicada": the tree's display name, and its parent's from the document id when
- /// the provider uses paths (external storage: "primary:Documents/Cicada").
fun shortPath(r: ContentResolver, tree: Uri): String? {
val name = try { displayName(r, root(tree)) } catch (_: Exception) { null } ?: return null
val path = DocumentsContract.getTreeDocumentId(tree).substringAfter(':', "")
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/ImportActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/ImportActivity.kt
index 16c6ea7..31a3870 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/ImportActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/ImportActivity.kt
@@ -12,14 +12,10 @@ import cicada.Languages
import cicada.Strings.L
import cicada.Strings.LF
-/// 导入录音或视频 (the Mac's FileImport): pick a file, or share one to 知了 from another app, and it
-/// becomes a meeting record: transcribed, translated and summarised like one that was heard. It
-/// runs in the foreground service, so it goes on with another app in front.
class ImportActivity : Activity() {
private lateinit var ui: Ui
private lateinit var content: FrameLayout
private var shown: String? = null
- /// The meeting this screen started or watched, to open once it's done.
private var watching: String? = null
private var unobserve: (() -> Unit)? = null
@@ -35,7 +31,6 @@ class ImportActivity : Activity() {
override fun onNewIntent(intent: Intent) { super.onNewIntent(intent); shared(intent)?.let(::start) }
- /// The file another app shared (分享到知了).
private fun shared(intent: Intent?): Uri? {
if (intent?.action != Intent.ACTION_SEND) return null
return if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java)
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/KeyStore.kt b/android/app/src/main/kotlin/com/wquguru/cicada/KeyStore.kt
index b1c1499..3086dab 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/KeyStore.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/KeyStore.kt
@@ -9,8 +9,6 @@ import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
-/// Seals the Ling key with an AES-GCM key that lives in the Android Keystore and never leaves it
-/// (Windows uses DPAPI for the same). Sealed bytes are the 12-byte IV, then the ciphertext.
object KeystoreProtector : KeyProtector {
override val tag = "keystore"
private const val ALIAS = "cicada-ling-key"
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/ListenService.kt b/android/app/src/main/kotlin/com/wquguru/cicada/ListenService.kt
index 5d31d64..fecc6ed 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/ListenService.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/ListenService.kt
@@ -19,10 +19,6 @@ import android.os.IBinder
import cicada.Log
import cicada.Strings.L
-/// Keeps listening alive with the screen off or another app in front, as a foreground service
-/// whose notification is the Android counterpart of the Mac's menu bar panel: what is being heard,
-/// for how long, the newest line, and 结束. Its type is mediaProjection (what the phone plays) or
-/// microphone (面对面), as Android 14 requires.
class ListenService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
@@ -32,7 +28,6 @@ class ListenService : Service() {
if (intent?.action == ACTION_KEEP) { app.keepRecording(); return START_NOT_STICKY }
val kind = intent?.getStringExtra("kind") ?: run { stopSelf(); return START_NOT_STICKY }
channel(this)
- // In the foreground with the right type first; only then may the projection be taken.
val type = when (kind) {
"playback" -> ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
"import" -> ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
@@ -58,7 +53,6 @@ class ListenService : Service() {
val code = intent.getIntExtra("code", Activity.RESULT_CANCELED)
val projection = data?.let { (getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager).getMediaProjection(code, it) }
if (projection == null) { app.startProblem = L("没能开始听"); app.starting = 0; app.changed(); stopSelf(); return START_NOT_STICKY }
- // The user can end sharing from the status bar: listening ends with it.
projection.registerCallback(object : MediaProjection.Callback() {
override fun onStop() { if (app.listen.listening && app.listen.sourceKind == "playback") app.stopListening() }
}, app.main)
@@ -90,7 +84,6 @@ class ListenService : Service() {
val listen = app.listen
val session = listen.sessionId?.let { app.store.get(it) }
val line = listen.sessionId?.let { app.store.lines(it).lastOrNull() }
- // 正在听 over 首页, so back from it stays in the app.
val open = android.app.TaskStackBuilder.create(context)
.addNextIntent(Intent(context, MainActivity::class.java))
.addNextIntent(Intent(context, ListeningActivity::class.java))
@@ -98,8 +91,6 @@ class ListenService : Service() {
val stop = PendingIntent.getService(context, 1, Intent(context, ListenService::class.java).setAction(ACTION_STOP), PendingIntent.FLAG_IMMUTABLE)
val ending = app.ending
val file = app.importing
- // Something only the user can fix (a key, the credit, a model): said here, where it is
- // seen with Cicada in the background, with the way to fix it. No second notification.
val blocking = if (file == null) app.ling.blocking else null
val title = when {
file != null -> L("知了 · 正在转写") + " " + (session?.sourceFile ?: "")
@@ -118,14 +109,12 @@ class ListenService : Service() {
.setUsesChronometer(session != null)
.setWhen(session?.startedAt?.toEpochMilli() ?: System.currentTimeMillis())
.setContentIntent(open)
- // About to end by itself: the same two choices as the 正在听 strip.
if (ending != null) {
val keep = PendingIntent.getService(context, 2, Intent(context, ListenService::class.java).setAction(ACTION_KEEP), PendingIntent.FLAG_IMMUTABLE)
b.addAction(Notification.Action.Builder(null, L("继续记录"), keep).build())
b.addAction(Notification.Action.Builder(null, L("现在结束"), stop).build())
} else {
if (blocking != null) {
- // 设置 › AI 服务 over 首页, as the home card opens it.
val fix = android.app.TaskStackBuilder.create(context)
.addNextIntent(Intent(context, MainActivity::class.java))
.addNextIntent(Intent(context, AiServiceActivity::class.java))
@@ -137,7 +126,6 @@ class ListenService : Service() {
return b.setCategory(Notification.CATEGORY_SERVICE).build()
}
- /// The notification follows the newest line (only when its text changes).
fun refresh(context: Context) {
val app = context.cicada
if (!app.listen.listening || (app.listen.sourceKind == "file" && app.importing == null)) { lastText = null; return }
@@ -151,16 +139,12 @@ class ListenService : Service() {
}
}
-/// A see-through activity that gets what listening needs before ListenService starts: the
-/// microphone permission (Android asks for it even to capture other apps), the notification
-/// permission, and for playback the system's screen-capture consent, which is single-use.
class ProjectionActivity : Activity() {
private lateinit var kind: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
kind = intent.getStringExtra("kind") ?: "playback"
- // Recreated (rotation) while a permission or consent dialog is up: that dialog's result still comes.
if (savedInstanceState != null) return
val needed = mutableListOf<String>()
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) needed.add(Manifest.permission.RECORD_AUDIO)
@@ -181,8 +165,6 @@ class ProjectionActivity : Activity() {
private fun next() {
if (kind == "playback") {
val mpm = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
- // The whole device, not "one app": what is heard is every app's sound, and the
- // one-app picker would only confuse (Android 14+).
val consent = if (Build.VERSION.SDK_INT >= 34)
mpm.createScreenCaptureIntent(android.media.projection.MediaProjectionConfig.createConfigForDefaultDisplay())
else mpm.createScreenCaptureIntent()
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/ListenTile.kt b/android/app/src/main/kotlin/com/wquguru/cicada/ListenTile.kt
index 4f2f47d..63c75d0 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/ListenTile.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/ListenTile.kt
@@ -9,11 +9,7 @@ import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import cicada.Strings.L
-/// The 知了 tile in Quick Settings: one tap starts listening (from the source chosen last time) or
-/// ends it, without opening the app first. Lit while listening, with the time as its subtitle.
class ListenTile : TileService() {
- // While Quick Settings is open the tile is updated directly (a refresh request is ignored for a
- // tile already showing), and its clock ticks.
private val tick = object : Runnable {
override fun run() { update(); if (cicada.listen.listening) cicada.main.postDelayed(this, 1000) }
}
@@ -26,7 +22,6 @@ class ListenTile : TileService() {
val app = cicada
if (app.listen.listening) { app.stopListening { update() }; return }
val intent = app.startIntent(this, app.settings.source) ?: return
- // A tile may only open an activity by collapsing the panel; Android 14+ takes a PendingIntent.
if (Build.VERSION.SDK_INT >= 34) {
startActivityAndCollapse(PendingIntent.getActivity(this, 3, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT))
} else {
@@ -54,7 +49,6 @@ class ListenTile : TileService() {
companion object {
@Volatile private var visible: ListenTile? = null
- /// Listening started or ended: update the tile now if it is showing, else ask the system to.
fun refresh(context: Context) {
visible?.let { it.cicada.main.post(it.tick); return }
try { requestListeningState(context, ComponentName(context, ListenTile::class.java)) } catch (_: Exception) {}
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/ListeningActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/ListeningActivity.kt
index e72ce45..0d22dc9 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/ListeningActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/ListeningActivity.kt
@@ -14,9 +14,6 @@ import cicada.Languages
import cicada.Strings.L
import cicada.Strings.LF
-/// 正在听: the meeting as it happens. Subtitles stream in (newest large, at the bottom) or the
-/// live notes; 在视频上看 goes back to the other app, where the floating window takes over; 结束
-/// ends it and opens the record.
class ListeningActivity : Activity() {
private lateinit var ui: Ui
private lateinit var tabsHost: FrameLayout
@@ -29,23 +26,19 @@ class ListeningActivity : Activity() {
private var sayButton: LinearLayout? = null
private var sayLabel: TextView? = null
private var sayHelper: TextView? = null
- private var tab = 0 // 0 实时纪要, 1 字幕
+ private var tab = 0
private var shown: String? = null
private var unobserve: (() -> Unit)? = null
private var toast: FixViews.Toast? = null
private val tick = object : Runnable {
- // The clock, and states that come without an event (20 s of silence): render() is keyed.
override fun run() { badgeText.text = NotesViews.status(cicada); render(); NotesViews.tickEnding(content, cicada); cicada.main.postDelayed(this, 1000) }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ui = Ui(this)
- // 实时纪要 first and by default, as on the Mac; 面对面 opens on 字幕, where each line is read
- // as it comes (and 我说's replies show).
tab = savedInstanceState?.getInt("tab") ?: if (cicada.listen.sourceKind == "mic") 1 else 0
badgeText = ui.text(NotesViews.status(cicada), 14f, Palette.ink, bold = true, lines = 1).apply { fontFeatureSettings = "tnum" }
- // 正在听 · 12:48 in a white pill, the live dot in the accent (the design's B).
val badge = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = android.view.Gravity.CENTER_VERTICAL
@@ -79,8 +72,6 @@ class ListeningActivity : Activity() {
private lateinit var actionHost: FrameLayout
private var actionKind: String? = null
- /// Top right: 在视频上看 while hearing the phone; 面对面 turns the phone into the two-sided
- /// interpreter (FaceActivity).
private fun buildAction() {
val kind = cicada.listen.sourceKind
if (kind == actionKind) return
@@ -95,11 +86,8 @@ class ListeningActivity : Activity() {
else actionHost.addView(View(this), FrameLayout.LayoutParams(ui.dp(48), ui.dp(48)))
}
- /// 面对面 gets 我说 (hold, speak, release: the phone says it in their language) in place of
- /// 在视频上看, which has no video to go back to.
private fun buildBottom() {
val kind = cicada.listen.sourceKind
- // Keyed on the language too: one changed in 设置 meanwhile would leave 结束 in the old one.
if ("$kind ${L("结束")}" == bottomKind) return
bottomKind = "$kind ${L("结束")}"
bottomHost.removeAllViews()
@@ -127,7 +115,6 @@ class ListeningActivity : Activity() {
else -> true
}
}
- // TalkBack's double tap is a click: press once to start, again to finish.
say.setOnClickListener { if (cicada.listen.holding) cicada.releaseToSay() else cicada.holdToSay(); updateSay() }
val bar = ui.bottomBar(ui.button(L("结束"), "white", height = 64) { end() }, say)
(say.layoutParams as LinearLayout.LayoutParams).weight = 2.2f
@@ -142,7 +129,6 @@ class ListeningActivity : Activity() {
updateSay()
}
- /// The button changes in place: rebuilding it under a finger would lose the hold.
private fun updateSay() {
val say = sayButton ?: return
val app = cicada
@@ -156,8 +142,6 @@ class ListeningActivity : Activity() {
}
sayLabel?.text = text
say.contentDescription = text
- // The accent only while it's live (my turn, or the phone speaking); white on it is under
- // 4.5:1, so the label is ink then.
say.background = ui.ripple(ui.rounded(if (live) Palette.accent else Palette.ink, 32), 32, dark = true)
sayLabel?.setTextColor(if (live) Palette.ink else android.graphics.Color.WHITE)
(0 until say.childCount).map { say.getChildAt(it) }.filterIsInstance<android.widget.ImageView>().firstOrNull()?.setColorFilter(if (live) Palette.ink else android.graphics.Color.WHITE)
@@ -184,7 +168,6 @@ class ListeningActivity : Activity() {
private fun render() {
val app = cicada
- // Ended elsewhere (the notification, the floating window, Android's "stop sharing").
if (!app.listen.listening && app.listen.pending == 0) { openRecord(); return }
badgeText.text = NotesViews.status(app)
buildBottom()
@@ -200,7 +183,6 @@ class ListeningActivity : Activity() {
content.removeAllViews()
NotesViews.endingStrip(ui, app)?.let { content.addView(it) }
NotesViews.banner(ui, app) { switchToMic() }?.let { content.addView(it) }
- // 这样改对吗?: a name the service proposed, asked about once (× puts it off until after the meeting).
app.listen.sessionId?.let { sid ->
app.fixes.asking(sid)?.let { a -> content.addView(FixViews.confirmCard(ui, a, { yes -> app.fixes.answer(a.fix, yes, sid) }, { app.fixes.later(a.fix, sid) })) }
}
@@ -217,19 +199,14 @@ class ListeningActivity : Activity() {
}
}
- /// Back to the app underneath (the video): the floating window shows there. Without the
- /// permission for it, the guide asks for it (and walks through Android's unlock when needed).
private fun watchOver() {
val app = cicada
if (!app.canOverlay) { OverlayGuideActivity.open(this, watch = true); return }
- // Asked for now: show it for this meeting even if 悬浮窗 is off in 设置, without changing that.
app.overlayThisMeeting = true
app.overlayClosed = false
moveTaskToBack(true)
}
- /// The Mac's requestStop: a meeting with lines ends only after asking, 继续记录 the safe
- /// choice; an empty one just stops.
private fun end() {
val s = cicada.listen.sessionId?.let { cicada.store.get(it) }
if (s == null || s.lines.isEmpty() || !cicada.listen.listening) { endNow(); return }
@@ -251,7 +228,6 @@ class ListeningActivity : Activity() {
finish()
}
- /// Nothing heard from the phone: start again from the microphone.
private fun switchToMic() {
val app = cicada
app.settings.source = "mic"; app.saveSettings()
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/MainActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/MainActivity.kt
index 86c0bf1..22d9805 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/MainActivity.kt
@@ -22,9 +22,6 @@ import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
-/// 首页 is 会议记录 (as on iOS): the large title, the card that starts listening (what the phone
-/// plays, or 面对面) or shows the meeting going on, then the meetings by day. 会议记录 / 设置 and
-/// search float at the bottom; 导入 is the round button by the title.
class MainActivity : Activity() {
private lateinit var ui: Ui
private lateinit var top: FrameLayout
@@ -50,7 +47,6 @@ class MainActivity : Activity() {
}
private var builtTitle = ""
- /// The Quick Settings tile's 开始听, held back by a known AI service failure: say why here.
private var startFromTile: String? = null
override fun onNewIntent(intent: Intent) {
@@ -60,8 +56,6 @@ class MainActivity : Activity() {
override fun onResume() {
super.onResume()
- // The nav brings this screen back to the front rather than making a new one, so a language
- // changed in 设置 meanwhile would leave the title and nav in the old one.
if (L("会议记录") != builtTitle) { recreate(); return }
unobserve = cicada.observe(::render)
shownTop = null; shownRecent = null
@@ -96,14 +90,11 @@ class MainActivity : Activity() {
else -> startCard()
})
if (app.settings.overlay && !app.canOverlay && file == null) column.addView(tipCard())
- // The AI service needs the user (a phone has no tray): where the update card goes.
if (file == null && !app.listen.listening) AiCheckViews.card(this, ui)?.let { column.addView(it) }
- // A new version, under the start card; never while a meeting or a file is going on.
app.updates.available?.takeIf { file == null && !app.listen.listening }?.let { column.addView(updateCard(it)) }
top.addView(column)
}
- /// A meeting is going on: where it is and a way back to it.
private fun liveCard(): LinearLayout {
val app = cicada
val status = ui.text(NotesViews.status(app), 15f, Palette.link, bold = true)
@@ -115,7 +106,6 @@ class MainActivity : Activity() {
return card
}
- /// A file being transcribed: its name and how far it is.
private fun importCard(file: FileSource): LinearLayout {
clockText = null
val app = cicada
@@ -132,7 +122,6 @@ class MainActivity : Activity() {
val pb = app.settings.source != "mic"
clockText = null
val card = ui.card(gap = 16)
- // The last meeting ended by itself (as the Mac's menu says 会议已自动结束, not 已暂停).
if (app.autoEnded) card.addView(LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
@@ -154,7 +143,6 @@ class MainActivity : Activity() {
ui.helper(if (pb) L("通话和会议 app 的声音系统不让录,改用“面对面”") else L("线下开会;有人在线上就把会议 app 开外放"))), ui.weight().apply { leftMargin = ui.dp(12) })
}
card.addView(desc, ui.lp(top = 16))
- // The language pair: what is heard (found by itself) → what subtitles read in.
val lang = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER
@@ -188,14 +176,12 @@ class MainActivity : Activity() {
addView(ui.textButton(L("去开启")) { OverlayGuideActivity.open(this@MainActivity, direct = true) })
}
- /// 有新版本: 更新 downloads the APK in the browser, the words open the release notes.
private fun updateCard(u: UpdateChecker.Update) = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
background = ui.rounded(Palette.card, 22)
setPadding(ui.dp(16), ui.dp(12), ui.dp(8), ui.dp(12))
addView(ui.tile(R.drawable.i_update, 40, Palette.accentPale, Palette.link).apply { background = ui.rounded(Palette.accentPale, 20) })
- // The words open the release notes (a bigger target than the grey line alone).
val texts = ui.stack(2, ui.text(LF("有新版本 %@", u.version), 15f, Palette.ink, medium = true), ui.helper(L("更新说明"))).apply {
setPadding(ui.dp(6), ui.dp(4), ui.dp(6), ui.dp(4))
contentDescription = LF("有新版本 %@", u.version) + "," + L("更新说明")
@@ -205,7 +191,6 @@ class MainActivity : Activity() {
addView(ui.textButton(L("更新")) { cicada.updates.download() })
}
- /// The meetings, newest first, under 今天 / 昨天 / the date (the last 60; search finds the rest).
private fun renderRecent() {
val app = cicada
val sessions = app.store.all().take(60)
@@ -233,7 +218,6 @@ class MainActivity : Activity() {
}
companion object {
- /// "今天 20:54" / "昨天 09:02" / "11月1日 15:30".
fun day(at: Instant): String {
val local = at.atZone(ZoneId.systemDefault())
val d = local.toLocalDate()
@@ -248,14 +232,10 @@ class MainActivity : Activity() {
fun time(at: Instant): String = DateTimeFormatter.ofPattern("HH:mm").withZone(ZoneId.systemDefault()).format(at)
- /// The meeting's name without its date (lists and rename show the date apart).
fun name(s: Session): String =
if (s.renamed ?: !s.title.startsWith("会议 ")) s.title else s.notes?.title?.takeIf { it.isNotEmpty() } ?: SessionStore.displayTitle(s)
- /// One meeting in a list: title (and 正在听), when, how long, how many lines, to-dos.
- /// `query`: found by 会议记录's search, the record opens at the lines found (#33).
fun recordRow(activity: Activity, ui: Ui, s: Session, live: Boolean, query: String = ""): LinearLayout {
- // The line under it says when: the title is just the meeting's name.
val title = name(s)
val titleView = LinearLayout(activity).apply {
orientation = LinearLayout.HORIZONTAL
@@ -263,7 +243,6 @@ class MainActivity : Activity() {
if (live) addView(ui.badge(if (activity.cicada.importing != null) L("正在转写") else L("正在听"), dot = true), LinearLayout.LayoutParams(-2, -2).apply { rightMargin = ui.dp(8) })
addView(ui.text(title, 16f, Palette.ink, bold = true, lines = 1), ui.weight())
}
- // Under a day's heading: the time, how long, how many lines, and where it came from.
val from = s.sourceFile?.let { L("导入") }
val meta = if (live) "${time(s.startedAt)} · ${Languages.clock(s.durationSeconds)}"
else listOfNotNull("${time(s.startedAt)}", Languages.clock(s.durationSeconds), LF("%lld 句", s.lines.size), from).joinToString(" · ")
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/NotesViews.kt b/android/app/src/main/kotlin/com/wquguru/cicada/NotesViews.kt
index c9495b2..184b728 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/NotesViews.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/NotesViews.kt
@@ -12,31 +12,24 @@ import cicada.Strings.LF
import cicada.TranscriptLine
import java.time.Instant
-/// What the live screens show, built the same way for 正在听 and the floating window.
object NotesViews {
- /// This meeting's lines while it runs (or until its last reply lands).
fun currentLines(app: CicadaApp): List<TranscriptLine> {
val listen = app.listen
if (!listen.listening && listen.pending == 0) return emptyList()
return listen.sessionId?.let { app.store.lines(it) } ?: emptyList()
}
- /// No sound for 20 s from what the phone plays: most likely an app that can't be captured.
fun silent(app: CicadaApp) = app.listen.let { it.listening && it.sourceKind == "playback" && it.heardSeconds > 20 && it.peak < 0.002 }
- /// Everything the live views show, so they are rebuilt only when it changes: a view replaced
- /// under a finger loses the tap.
fun liveKey(app: CicadaApp): String {
val listen = app.listen
val line = listen.sessionId?.let { app.store.lines(it).lastOrNull() }
return listOf(listen.listening, listen.sourceKind, listen.sessionId, listen.pending > 0, listen.problem, app.startProblem, silent(app), app.micSilenced,
line?.id, line?.shown, line?.dst, app.notes.status, app.notes.notes.updatedAt, app.notes.notes.covered,
app.ending?.deadline, app.ling.blocking, listen.problemKind, app.ling.provider.id, customOnlyUntranslated(app),
- // 改正听错的词: the newest line's fixes, the card and the 撤销 message.
line?.fixes, listen.sessionId?.let { app.fixes.asking(it)?.fix }, app.fixes.toastNow()?.at, app.settings.showInCapture).joinToString("|")
}
- /// "正在听 · 03:12" / "面对面 · 03:12".
fun status(app: CicadaApp): String {
val head = if (app.listen.sourceKind == "mic") L("面对面") else L("正在听")
return head + " · " + clock(app)
@@ -44,7 +37,6 @@ object NotesViews {
fun clock(app: CicadaApp): String = app.listen.sessionId?.let { app.store.get(it) }?.let { Languages.clock(it.durationSeconds) } ?: "00:00"
- /// "手机里的声音 · English → 简体中文".
fun sourceLine(app: CicadaApp): String {
val source = if (app.listen.sourceKind == "mic") L("面对面") else L("手机里的声音")
val from = app.listen.spoken?.let { languageName(it) } ?: L("自动识别")
@@ -54,17 +46,12 @@ object NotesViews {
fun languageName(code: String) = Languages.targets.firstOrNull { it.code == code }?.name
?: Languages.sources.firstOrNull { it.code == code }?.name ?: code
- /// "刚刚更新" / "3 分钟前更新".
fun updated(at: Instant?): String? {
at ?: return null
val minutes = (Instant.now().epochSecond - at.epochSecond) / 60
return if (minutes < 1) L("刚刚更新") else LF("%@ 分钟前更新", minutes)
}
- /// The problem banner of the live screens, or null. `onMic` offers 面对面 when nothing is heard.
- /// The meeting is about to end by itself (the Mac's MeetingEndingStrip): what's happening, the
- /// seconds left (tagged ENDING_DETAIL, updated in place each second so the buttons keep their
- /// touch), 继续记录 and 现在结束.
fun endingStrip(ui: Ui, app: CicadaApp, compact: Boolean = false): View? {
val p = app.ending ?: return null
return ui.stack(if (compact) 8 else 12).apply {
@@ -85,11 +72,8 @@ object NotesViews {
const val ENDING_DETAIL = "endingDetail"
const val ENDING_BAR = "endingBar"
- /// The subtitle bar has no buttons (as on the Mac): it says what will happen, and speaking
- /// keeps a silent meeting going.
fun endingBarText(app: CicadaApp): String? = app.ending?.let { app.endingTitle(it) + " · " + LF("%lld 秒后结束", app.endingLeft(it)) }
- /// The countdown's seconds, without rebuilding the views around it.
fun tickEnding(root: View?, app: CicadaApp) {
val p = app.ending ?: return
(root?.findViewWithTag<TextView>(ENDING_DETAIL))?.text = app.endingDetail(p)
@@ -99,21 +83,15 @@ object NotesViews {
fun banner(ui: Ui, app: CicadaApp, onMic: (() -> Unit)?): View? {
val problem = app.listen.problem
val kind = app.listen.problemKind
- // A key, the credit or a model: before the hearing's own words ("Ling key 无效"), which say less.
val blocking = app.ling.blocking
val micTaken = app.micSilenced && app.listen.listening
- // The service's trouble is a status line; the microphone taken or nothing heard is not.
when {
- // Hearing goes through the service too: the subtitles wait with the notes. The network or
- // the proxy, not the notes: it picks up by itself, or 改用 Ling when that key is saved.
kind == "network" -> return statusLine(ui, Tone.Waiting, LF("字幕和纪要等 %@ 恢复 · 连上后自动继续", serviceLabel(app)),
if (app.canSwitchToLing) L("改用 Ling") to { app.switchToLing() } else null)
micTaken -> {}
blocking != null -> return statusLine(ui, Tone.NeedsYou, blocking, openSettings(ui, onMic))
problem != null -> return statusLine(ui, when (kind) { "busy" -> Tone.Waiting; "key" -> Tone.NeedsYou; else -> Tone.Info },
problem, openSettings(ui, onMic).takeIf { kind == "key" })
- // 语音和文字只发给你的服务: heard, but the user's service didn't translate and Google isn't
- // asked. It picks up by itself; no 改用 Ling, which would send the meeting elsewhere.
customOnlyUntranslated(app) -> return statusLine(ui, Tone.Waiting, LF("译文等 %@ 恢复 · 字幕先显示原文", serviceLabel(app)))
!silent(app) -> return null
}
@@ -132,17 +110,11 @@ object NotesViews {
}
}
- /// 打开设置 › AI 服务, on Cicada's own screens only (`onMic` set): not from the floating window.
private fun openSettings(ui: Ui, onMic: (() -> Unit)?): Pair<String, () -> Unit>? = if (onMic == null) null
else L("打开设置") to { ui.context.startActivity(android.content.Intent(ui.context, AiServiceActivity::class.java)) }
- /// How a status line reads at a glance, by its dot alone (a passing wait shouldn't look like a
- /// fault): Waiting comes back by itself, NeedsYou is the user's to fix, Info is just so you know.
enum class Tone { Waiting, NeedsYou, Info }
- /// A service in trouble, said the same way wherever it shows (the Mac's StatusLine): a dot,
- /// "what waits for what · what still works", and at most one action. The text is child 1:
- /// the floating window's subtitle bar takes it from there.
fun statusLine(ui: Ui, tone: Tone, text: String, action: Pair<String, () -> Unit>? = null): LinearLayout = LinearLayout(ui.context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
@@ -159,17 +131,13 @@ object NotesViews {
accessibilityLiveRegion = View.ACCESSIBILITY_LIVE_REGION_POLITE
}
- /// #C98A00, the Mac's waiting dot: AiCheckViews.warn is too dark to tell from the text at 6 dp.
private val WAITING = android.graphics.Color.parseColor("#C98A00")
- /// Finished sentences going untranslated with 语音和文字只发给你的服务 in effect (the Mac's googleOff banner).
private fun customOnlyUntranslated(app: CicadaApp) =
app.listen.listening && app.translator.googleOff && app.translator.sentencesUntranslated
- /// Where this meeting's notes stop: the time of the last line they cover.
private fun serviceLabel(app: CicadaApp): String = app.ling.serviceLabel
- /// An import's progress: the bar and "26:40 / 42:15".
fun progress(ui: Ui, file: FileSource): LinearLayout {
val box = ui.stack(8)
val frac = if (file.total > 0) (file.done / file.total).coerceIn(0.0, 1.0) else 0.0
@@ -184,13 +152,10 @@ object NotesViews {
return box
}
- /// Speaker colours (the iOS design's): the first voices blue and clay, then green and violet;
- /// 你 ink; 对方 / 未识别 grey. Each pair passes 4.5:1.
private val voiceColors = listOf(0xFFDCE7F7.toInt() to 0xFF1F4E8C.toInt(), 0xFFF6E2D6.toInt() to 0xFF8A3A16.toInt(),
0xFFDFF0E4.toInt() to 0xFF1E6B3A.toInt(), 0xFFEDE3F6.toInt() to 0xFF5B2E8A.toInt())
fun voiceColor(number: Int?): Pair<Int, Int> = number?.let { voiceColors[(it - 1) % voiceColors.size] } ?: (0xFFE7E9EE.toInt() to 0xFF3F434C.toInt())
- /// A round initial for who said it.
fun avatar(ui: Ui, line: TranscriptLine, numbers: Map<String, Int>, name: String, size: Int = 22) = ui.text(
if (line.speaker == "me") L("你") else name.trim().firstOrNull()?.uppercase() ?: "?", 11f,
if (line.speaker == "me") android.graphics.Color.WHITE else voiceColor(numbers[line.id]).second, bold = true).apply {
@@ -200,27 +165,22 @@ object NotesViews {
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
}
- /// One line as a white bubble: who and when, the original small and grey, the translation in
- /// ink. The newest is outlined in the accent while more may come.
fun bubble(ui: Ui, line: TranscriptLine, numbers: Map<String, Int>, names: Map<Int, String>, newest: Boolean, listening: Boolean,
onRevert: ((String, cicada.LineFix) -> Unit)? = null): LinearLayout {
val who = cicada.SpeakerLabels.speakerName(line, numbers, names)
val card = ui.stack(6)
card.background = if (newest && listening) ui.rounded(Palette.card, 22, android.graphics.Color.parseColor("#F2C3B2"), 1.5) else ui.rounded(Palette.card, 22)
card.setPadding(ui.dp(16), ui.dp(14), ui.dp(16), ui.dp(14))
- // An initial only for someone known (你, a numbered or named voice); 对方 has no face.
val head = ui.text("$who · ${Languages.clock(line.t)}", 12f, Palette.secondary, lines = 1)
card.addView(if (line.speaker == "me" || numbers[line.id] != null) ui.row(8, avatar(ui, line, numbers, who), head) else head)
val translated = !line.dst.isNullOrEmpty() && line.dst != line.shown
if (translated) card.addView(ui.text(FixViews.text(ui, line), Ui.Type.ORIGINAL, Palette.secondary).apply { leading(1.45f) })
card.addView(ui.text(line.dst?.takeIf { translated } ?: FixViews.text(ui, line), Ui.Type.TRANSLATION, Palette.ink).apply { leading(1.5f) })
- // The line being said shows its fixed words open (the Mac's notes window does too): nothing to hover with.
if (onRevert != null) FixViews.fixedWords(ui, line.id, line.fixes ?: emptyList(), onRevert)?.let { card.addView(it, ui.lp(top = 4)) }
if (newest) card.accessibilityLiveRegion = View.ACCESSIBILITY_LIVE_REGION_POLITE
return card
}
- /// The subtitle stream on 正在听: a bubble per line, the newest at the bottom.
fun bubbles(ui: Ui, app: CicadaApp, count: Int): LinearLayout {
val lines = currentLines(app)
val box = ui.stack(12)
@@ -243,7 +203,6 @@ object NotesViews {
return box
}
- /// The subtitle stream: earlier lines small, the newest as a large card at the bottom.
fun stream(ui: Ui, app: CicadaApp, earlier: Int): LinearLayout {
val lines = currentLines(app)
val box = ui.stack(18)
@@ -270,8 +229,6 @@ object NotesViews {
return box
}
- /// The newest line as a card, with the "still listening" dots under it.
- /// The original as shown above its translation: mine is marked, so it's clear who said it.
fun said(l: TranscriptLine) = if (l.speaker == "me") L("你 · 同传") + " · " + l.shown else l.shown
fun liveCard(ui: Ui, app: CicadaApp, line: TranscriptLine, big: Float, bg: Int = Palette.card, lines: Int = 0, dots: Boolean = true): LinearLayout {
@@ -292,20 +249,13 @@ object NotesViews {
return card
}
- /// The notes: name and freshness, summary, topics, conclusions, to-dos. `compact` (the
- /// floating window) keeps the current topic only.
- /// `heard`: this meeting's lines so far, for the listening placeholder.
fun notesBody(ui: Ui, notes: MeetingNotes, status: NotesEngine.State, listening: Boolean, compact: Boolean = false, heard: Int = 0): LinearLayout {
val body = ui.stack(0)
notesTrouble(ui, notes, status, listening, actions = !compact)?.let { body.addView(it, LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = ui.dp(12) }) }
- // Listening and no request out yet (the first waits for a few lines or 20 s): the notes'
- // own shape, kept after the first line is heard (the Mac's notesPane).
if (notes.isEmpty && listening && (status == NotesEngine.State.Idle || status == NotesEngine.State.Failed)) {
body.addView(listeningPlaceholder(ui, heard, compact))
return body
}
- // The first version on its way (the Mac's NotesGeneratingView): the same shape, a spinner
- // and how many lines it was written from, not a bare 正在整理纪要… for the 10–20 s it takes.
if (notes.isEmpty && listening && heard > 0 && status == NotesEngine.State.Updating) {
body.addView(listeningPlaceholder(ui, heard, compact, generating = true))
return body
@@ -351,10 +301,6 @@ object NotesViews {
return body
}
- /// What went wrong with the notes' own request, as a status line (the Mac's notes banner), or
- /// null. What the live banner already says (the service unreachable, busy for the hearing too,
- /// a key it can't use) isn't said twice. `actions`: 换 key opens the settings, so not from the
- /// floating window.
private fun notesTrouble(ui: Ui, notes: MeetingNotes, status: NotesEngine.State, listening: Boolean, actions: Boolean): View? {
val app = CicadaApp.shared
val shown = app.listen.problemKind.takeIf { listening }
@@ -364,26 +310,20 @@ object NotesViews {
statusLine(ui, Tone.NeedsYou, if (stopped != null) LF("key 失效了 · 纪要停在 %@", Languages.clock(stopped)) else L("key 失效了 · 纪要等新的 key"),
if (actions) L("换 key") to { ui.context.startActivity(android.content.Intent(ui.context, AiServiceActivity::class.java)) } else null)
}
- // A busy notes request is its own: the hearing goes on unless it is busy too (then the banner says so).
status == NotesEngine.State.RateLimited && (listening || notes.isEmpty) && shown != "busy" ->
statusLine(ui, Tone.Waiting, LF("%@ 很忙 · 纪要稍后补上,字幕照常", serviceLabel(app)))
- // Nothing reached: the banner's 字幕和纪要等 … 恢复 covers this round too.
status == NotesEngine.State.Failed && listening && shown != "network" ->
statusLine(ui, Tone.Info, L("这轮纪要没写好 · 下轮自动补上"))
else -> null
}
}
- /// The Mac's NotesListeningView: a quiet status row, then the notes' shape waiting to be
- /// filled and what they will hold. `compact` (the floating window) keeps the status row only.
- /// `generating`: the first request is out: a spinner and 正在生成纪要… instead of the sound bars,
- /// and no list of what the notes will hold (the Mac's NotesGeneratingView).
fun listeningPlaceholder(ui: Ui, heard: Int, compact: Boolean, generating: Boolean = false): LinearLayout {
val box = ui.stack(0)
box.addView(LinearLayout(ui.context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
- background = ui.rounded(0xB3FDEBE4.toInt(), 12) // accentPale at 70%, as on the Mac
+ background = ui.rounded(0xB3FDEBE4.toInt(), 12)
setPadding(ui.dp(14), ui.dp(12), ui.dp(14), ui.dp(12))
if (generating) {
addView(android.widget.ProgressBar(ui.context).apply {
@@ -407,7 +347,6 @@ object NotesViews {
box.addView(topicSlot(ui, "00:00", listOf(0.52f, 0.88f, 0.7f)), ui.lp(top = 12))
box.addView(topicSlot(ui, "--:--", listOf(0.4f, 0.76f)).apply { alpha = 0.6f }, ui.lp(top = 12))
if (generating) return box
- // Wraps: the English chips don't fit one line on a phone.
box.addView(FlowRow(ui.context, ui.dp(6)).apply {
addView(ui.text(L("会整理出"), 12f, Palette.tertiary).apply { setPadding(0, ui.dp(4), 0, ui.dp(4)) })
for (t in listOf(L("结论"), L("待办"), L("人名和术语"), L("鱼骨图"))) addView(ui.text(t, 12f, Palette.secondary, lines = 1).apply {
@@ -432,20 +371,15 @@ object NotesViews {
}, ui.weight().apply { leftMargin = ui.dp(12) })
}
- /// The Mac's Palette.placeholder and Palette.fill.
private val PLACEHOLDER = android.graphics.Color.parseColor("#B8BDC6")
private val FILL = android.graphics.Color.parseColor("#F2F3F5")
- /// 0..1 through a repeating cycle (the Mac's phase()); with animations off, one still frame
- /// (bars at mixed heights).
fun phase(period: Double, delay: Double = 0.0): Double {
val now = if (android.animation.ValueAnimator.areAnimatorsEnabled()) android.os.SystemClock.uptimeMillis() / 1000.0 else 0.4
val t = now - delay
return ((t % period) + period) % period / period
}
- /// Four small orange bars rising and falling: "listening". Redraws itself only while drawn,
- /// so it stops once detached or off screen.
class SoundBars(context: android.content.Context) : View(context) {
private val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply { color = Palette.accent }
private val rect = android.graphics.RectF()
@@ -464,8 +398,6 @@ object NotesViews {
}
}
- /// A placeholder line with a light sweeping across it (the Mac's SkeletonBar), `fraction` of
- /// the width. Redraws itself only while drawn.
class SkeletonBar(context: android.content.Context, private val fraction: Float) : View(context) {
private val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)
private val rect = android.graphics.RectF()
@@ -487,8 +419,6 @@ object NotesViews {
}
}
- /// Children left to right, wrapping to the next line (the Mac's FlowLayout), each row
- /// centred vertically.
class FlowRow(context: android.content.Context, private val gap: Int) : android.view.ViewGroup(context) {
private fun rows(max: Int): List<List<View>> {
val rows = mutableListOf<MutableList<View>>(mutableListOf())
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/OnboardingActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/OnboardingActivity.kt
index 862add4..c399476 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/OnboardingActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/OnboardingActivity.kt
@@ -20,8 +20,6 @@ import cicada.Strings.L
import cicada.Strings.LF
import cicada.keepsSavedKey
-/// First run, three screens, one job each, the main button pinned at the bottom: Ling key → what
-/// Cicada can hear and the permissions for it → try the sample meeting.
class OnboardingActivity : Activity() {
private lateinit var ui: Ui
private lateinit var host: FrameLayout
@@ -30,7 +28,6 @@ class OnboardingActivity : Activity() {
private var shown: String? = null
private var progressFill: View? = null
private var progressClock: android.widget.TextView? = null
- // The sample's progress and clock move on their own; the rest re-renders when lines arrive.
private val tick = object : Runnable {
override fun run() {
val l = cicada.listen
@@ -56,12 +53,9 @@ class OnboardingActivity : Activity() {
override fun onResume() { super.onResume(); unobserve = cicada.observe { if (step == 2) render(); checkShown?.invoke() }; shown = null; render(); cicada.main.post(tick) }
- /// The key step's (or its sheet's) check, redrawn when the AI client changes: the same step
- /// list as the settings, and on to the next step once it passes.
private var checkShown: (() -> Unit)? = null
private var checkKey: String? = null
- /// Fills `into` with the steps of a check this page started; true once it passed.
private fun showCheck(into: LinearLayout): Boolean {
val ling = cicada.ling
val c = ling.aiCheck
@@ -75,9 +69,6 @@ class OnboardingActivity : Activity() {
}
override fun onPause() { super.onPause(); unobserve?.invoke(); unobserve = null; cicada.main.removeCallbacks(tick) }
- // Back goes to the previous step. Android 13+ delivers back through OnBackInvokedCallback
- // (Android 16 no longer calls onBackPressed for apps that target it), registered only while
- // there is a step to go back to, so the system's back animation still works on the first.
private val stepBack = android.window.OnBackInvokedCallback { step--; shown = null; render() }
private var stepBackOn = false
@@ -99,7 +90,6 @@ class OnboardingActivity : Activity() {
step++
if (step > 2) {
cicada.settings.onboarded = true; cicada.saveSettings()
- // Opened on its own (no home screen under it): go home rather than out of the app.
if (isTaskRoot) startActivity(Intent(this, MainActivity::class.java))
finish(); return
}
@@ -114,7 +104,6 @@ class OnboardingActivity : Activity() {
syncBack()
host.removeAllViews()
host.addView(when (step) { 0 -> keyStep(); 1 -> hearStep(); else -> sampleStep() })
- // A view added after the first layout gets the system bars' insets only when asked.
host.requestApplyInsets()
}
@@ -122,7 +111,6 @@ class OnboardingActivity : Activity() {
private val micGranted get() = checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
private val notifyGranted get() = Build.VERSION.SDK_INT < 33 || checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
- /// The step's frame: progress (and a back arrow after the first), the content, the main button.
private fun frame(content: View, button: View): View {
val progress = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
@@ -144,8 +132,6 @@ class OnboardingActivity : Activity() {
val root = ui.screen(this, null, back = false, ground = Palette.ground, body = content, bottom = bottom)
window.navigationBarColor = Palette.ground
bottom.setBackgroundColor(Palette.ground)
- // The screen's own bar is replaced by the progress bar. The bar is the first child of the
- // column inside the root (the root's other child is the floating bottom), not of the root.
val column = root.getChildAt(0) as LinearLayout
column.removeViewAt(0)
column.addView(topBar, 0)
@@ -177,8 +163,6 @@ class OnboardingActivity : Activity() {
if (problem) status.announceForAccessibility(text)
}
showStatus(LF("加密存在这台手机上,只发给 %@", app.ling.serviceName), false)
- // When the keyboard opens the page shrinks: once it has (the IME inset arrives), scroll to
- // the end so the field and the line under it sit above the pinned button.
var imeShown = false
box.viewTreeObserver.addOnGlobalLayoutListener {
val ime = box.rootWindowInsets?.isVisible(android.view.WindowInsets.Type.ime()) == true
@@ -189,7 +173,6 @@ class OnboardingActivity : Activity() {
}
imeShown = ime
}
- // Another service's key pasted here: what it is, and 改用 it with one tap.
val other = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
val steps = ui.stack(0)
var tried = false
@@ -203,16 +186,13 @@ class OnboardingActivity : Activity() {
submit = submit@{
val text = box.text.toString().trim()
other.removeAllViews()
- // Onboarding never blocks: a key that was checked and failed still goes on (the steps say why).
if (tried && !app.ling.aiCheck.running && (text.isEmpty() || text == app.ling.currentKey())) { checkShown = null; next(); return@submit }
- // The guide opened again with a working key saved: an empty field keeps it.
if (!tried && keepsSavedKey(text, app.ling.currentKey(), app.ling.keyState)) { checkShown = null; next(); return@submit }
if (AiServiceActivity.keyHint(ui, text, "ling", status, other) { tried = true; checkKey = null; status.text = L("正在检查…") }) {
field.background = ui.rounded(Palette.card, 16, Palette.link, 2)
return@submit
}
if (!text.startsWith("sk-")) { showStatus(L("要粘贴 sk- 开头的 Ling key"), true); return@submit }
- // Back on this page after choosing another service: a Ling key means Ling again.
app.setAiProvider("ling", check = false)
app.key.save(text)
app.ling.keyChanged()
@@ -245,16 +225,12 @@ class OnboardingActivity : Activity() {
intro(L("接上 Ling"), L("识别、翻译和纪要都靠它,大约 1 分钟")),
ui.group(listOf(stepRow(1, L("打开 Ling 开放平台"), open), stepRow(2, L("点“创建令牌”,复制 sk- 开头的 Ling key")), stepRow(3, L("回到这里粘贴")))),
ui.stack(8, ui.text(L("Ling key"), 13f, Palette.body, bold = true).apply { setPadding(ui.dp(4), 0, 0, 0); labelFor = View.generateViewId().also { box.id = it } }, field, status.apply { setPadding(ui.dp(4), 0, 0, 0) }, other, steps),
- // A way out for people who can't use Ling: another service, in a sheet, saying what it lacks.
ui.textButton(L("用不了 Ling?"), Palette.link) { otherService() }.apply {
layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
})
return frame(content, ui.button(L("继续"), "primary") { submit() })
}
- /// 用其他服务 (OnboardingKey.swift › otherEntry): OpenRouter or ZenMux, their key, and what they
- /// lack. The service switches only once its key checks out; a custom address is set up in
- /// 设置 › AI 服务.
private fun otherService() {
val app = cicada
var chosen = app.settings.aiProvider.takeIf { it == "openrouter" || it == "zenmux" } ?: "zenmux"
@@ -270,7 +246,6 @@ class OnboardingActivity : Activity() {
fun problem(text: String) { status.text = text; status.setTextColor(Palette.link); status.announceForAccessibility(text) }
val other = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
val steps = ui.stack(0)
- // After a check that failed: the steps say why, and onboarding still goes on.
val goOn = ui.textButton(L("继续"), Palette.link) { checkShown = null; dialog.dismiss(); next() }.apply { visibility = View.GONE }
fun watch() {
checkKey = null
@@ -287,7 +262,6 @@ class OnboardingActivity : Activity() {
other.removeAllViews()
if (AiServiceActivity.keyHint(ui, text, p.id, status, other) { status.text = L("正在检查…"); watch() }) return@check
if (!text.startsWith("sk-")) { problem(LF("剪贴板里没有 sk- 开头的 key,请先去 %@ 复制。", p.name)); return@check }
- // The service and key stay as chosen even if the check fails: the steps say why.
app.setAiProvider(p.id, check = false)
app.key.save(text)
app.aiChanged(check = false)
@@ -405,8 +379,6 @@ class OnboardingActivity : Activity() {
val card = NotesViews.liveCard(ui, app, line, 20f, dots = playing)
card.addView(ui.text(L("字幕"), 13f, Palette.secondary, bold = true), 0)
(card.getChildAt(1).layoutParams as? LinearLayout.LayoutParams)?.topMargin = ui.dp(10)
- // The lines before the newest stay above it: the sample's two come back half a second
- // apart, and showing only the newest made the first one flash by.
lines.dropLast(1).takeLast(2).forEachIndexed { i, l ->
val row = ui.stack(2, ui.text(NotesViews.said(l), 13f, Palette.secondary))
if (!l.dst.isNullOrEmpty() && l.dst != l.shown) row.addView(ui.text(l.dst!!, 15f, Palette.ink))
@@ -421,7 +393,6 @@ class OnboardingActivity : Activity() {
}
content.addView(notesCard, ui.lp(top = 12))
} else if (playing) {
- // Ming answers a stretch once it ends (the sample's first, ~7 s in): say it's coming.
content.addView(ui.stack(10, ui.text(L("字幕"), 13f, Palette.secondary, bold = true),
LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Overlay.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Overlay.kt
index 0827ec6..eb3c9e5 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/Overlay.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Overlay.kt
@@ -19,13 +19,6 @@ import cicada.Strings.L
import kotlin.math.abs
import kotlin.math.hypot
-/// The floating window over other apps while listening, in three shapes: live notes (a card),
-/// the subtitle bar (dark, along the bottom, for reading over video), or collapsed to a small
-/// round bubble that drags anywhere and closes when dropped on the × target.
-///
-/// Like the Mac's notes panel it never takes focus (FLAG_NOT_FOCUSABLE: the keyboard and back
-/// button stay with the app underneath) and stays out of screenshots and recordings
-/// (FLAG_SECURE) unless 共享屏幕时让对方看到 is on, which shows a badge.
class Overlay(private val app: CicadaApp) {
private val wm = app.getSystemService(WindowManager::class.java)
private val ui = Ui(app)
@@ -36,20 +29,16 @@ class Overlay(private val app: CicadaApp) {
private var live: LinearLayout? = null
private var notes: FrameLayout? = null
private var shownKey: String? = null
- /// The 这样改对吗? card is up (for the debug state: a secure window can't be screenshotted).
private var asking = false
private val tick = object : Runnable {
override fun run() { if (root != null) { clockText?.text = NotesViews.clock(app); render(); NotesViews.tickEnding(root, app); app.main.postDelayed(this, 1000) } }
}
- /// Shown by a debug command regardless of the rules (screenshots of it over Cicada itself).
var forced = false
- /// Collapsed to the bubble (reset when a meeting starts).
var collapsed = false
val shown get() = root != null
private val subtitles get() = app.settings.view == "subtitles"
private val mode get() = if (collapsed) "bubble" else if (subtitles) "subtitles" else "notes"
- /// Where the person dragged the card and the subtitle bar, kept while Cicada runs.
private val placed = HashMap<String, Pair<Int, Int>>()
fun show() {
@@ -67,7 +56,6 @@ class Overlay(private val app: CicadaApp) {
app.main.removeCallbacks(tick)
}
- /// The shape changed (notes ↔ subtitles ↔ bubble, or the capture setting): build it again in place.
fun rebuild() { if (root != null) { hide(); show() } }
private fun flags(): Int {
@@ -78,7 +66,6 @@ class Overlay(private val app: CicadaApp) {
private fun build() {
val dm = app.resources.displayMetrics
- // Phone-sized on a tablet: a card and a subtitle bar, not a banner across the screen.
val full = dm.widthPixels - ui.dp(16)
val width = when (mode) { "bubble" -> ViewGroup.LayoutParams.WRAP_CONTENT; "subtitles" -> minOf(full, ui.dp(720)); else -> minOf(full, ui.dp(420)) }
val left = if (width > 0) (dm.widthPixels - width) / 2 else 0
@@ -86,8 +73,6 @@ class Overlay(private val app: CicadaApp) {
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, flags(), PixelFormat.TRANSLUCENT).apply {
title = "Cicada floating window"
when (mode) {
- // The subtitle bar hangs from the bottom edge, above the navigation bar, so a long
- // line grows upwards instead of off the screen.
"subtitles" -> { gravity = Gravity.BOTTOM or Gravity.START; x = left; y = ui.dp(64) }
"bubble" -> { gravity = Gravity.TOP or Gravity.START; x = dm.widthPixels - ui.dp(76); y = (dm.heightPixels * 0.45).toInt() }
else -> { gravity = Gravity.TOP or Gravity.START; x = left; y = (dm.heightPixels * 0.32).toInt() }
@@ -102,8 +87,6 @@ class Overlay(private val app: CicadaApp) {
"subtitles" -> buildSubtitles(frame, p)
else -> buildNotes(frame, p)
}
- // A video in picture-in-picture moves out of the way of keep-clear areas (Android 13+),
- // so 在视频上看 doesn't hide the very video it is about. The bubble is small enough to sit on it.
if (mode != "bubble" && android.os.Build.VERSION.SDK_INT >= 33) frame.isPreferKeepClear = true
try {
wm.addView(frame, p)
@@ -128,8 +111,6 @@ class Overlay(private val app: CicadaApp) {
addView(clock(if (dark) Palette.onScrim else Palette.ink), LinearLayout.LayoutParams(-2, -2).apply { leftMargin = ui.dp(8) })
if (app.settings.showInCapture) addView(ui.badge(L("对方可见")), LinearLayout.LayoutParams(-2, -2).apply { leftMargin = ui.dp(8) })
addView(ui.spacer())
- // Back to 正在听 in Cicada (the full notes, 结束): without it the only way was the
- // notification or the launcher. A video that does picture-in-picture keeps playing.
addView(ui.iconButton(R.drawable.i_external, L("回到正在听"), fg, 20, dark) { app.openLive() })
addView(if (subtitles) ui.iconButton(R.drawable.i_list, L("换成纪要"), fg, 20, dark) { app.setView("notes") }
else ui.iconButton(R.drawable.i_captions, L("换成字幕条"), fg, 22, dark) { app.setView("subtitles") })
@@ -192,7 +173,6 @@ class Overlay(private val app: CicadaApp) {
column.addView(chip, LinearLayout.LayoutParams(-2, -2).apply { topMargin = ui.dp(4) })
frame.addView(column)
live = null; notes = null
- // A tap expands it; a drag moves it, and dropping it on the × closes the floating window.
var downX = 0f; var downY = 0f; var startX = 0; var startY = 0; var moved = false
bubble.setOnTouchListener { _, e ->
when (e.actionMasked) {
@@ -216,10 +196,9 @@ class Overlay(private val app: CicadaApp) {
else -> { hideTarget(); false }
}
}
- bubble.setOnClickListener { collapsed = false; rebuild() } // TalkBack's double tap
+ bubble.setOnClickListener { collapsed = false; rebuild() }
}
- /// Bubbles rest against the nearer side.
private fun snapToEdge(frame: View, p: WindowManager.LayoutParams) {
val dm = app.resources.displayMetrics
p.x = if (p.x + ui.dp(34) < dm.widthPixels / 2) ui.dp(8) else dm.widthPixels - ui.dp(76)
@@ -267,10 +246,6 @@ class Overlay(private val app: CicadaApp) {
dismissTarget = null
}
- /// The card or the subtitle bar, dragged from anywhere on it: a finger that moves past the
- /// touch slop takes the gesture from the buttons underneath, so taps still reach them. (A
- /// listener on the header alone never moved it: it turned the first touch down, and Android
- /// then sends that view nothing more of the gesture.)
@SuppressLint("ViewConstructor", "ClickableViewAccessibility")
private inner class DragFrame(private val p: WindowManager.LayoutParams, private val fromBottom: Boolean) : FrameLayout(app) {
private val slop = ViewConfiguration.get(app).scaledTouchSlop
@@ -302,7 +277,6 @@ class Overlay(private val app: CicadaApp) {
return true
}
- /// Follows the finger, kept on the screen and clear of the status and gesture bars.
private fun move(e: MotionEvent) {
val dm = app.resources.displayMetrics
val edge = ui.dp(28)
@@ -315,7 +289,6 @@ class Overlay(private val app: CicadaApp) {
fun refresh() { if (root != null) render() }
private fun render() {
- // Rebuilt only when what it shows changed: a view replaced under a finger loses the tap.
val key = NotesViews.liveKey(app) + mode + app.settings.showInCapture
if (key == shownKey) return
shownKey = key
@@ -333,7 +306,6 @@ class Overlay(private val app: CicadaApp) {
line == null -> box.addView(ui.text(L("等有人说话…"), 15f, if (dark) Palette.onScrim else Palette.secondary).apply { setPadding(ui.dp(if (dark) 0 else 14), ui.dp(10), 0, ui.dp(10)) })
dark -> {
val col = ui.stack(4)
- // My line (我说) says so, as the Mac's subtitle bar does.
if (!line.dst.isNullOrEmpty() && line.dst != line.shown) col.addView(ui.text(NotesViews.said(line), 13f, Palette.onScrim, lines = 2))
else if (line.speaker == "me") col.addView(ui.text(L("你 · 同传"), 13f, Palette.onScrim))
col.addView(ui.text(line.dst ?: line.shown, 20f, Color.WHITE, bold = true, lines = 3).apply { leading(1.2f) })
@@ -341,8 +313,6 @@ class Overlay(private val app: CicadaApp) {
}
else -> box.addView(NotesViews.liveCard(ui, app, line, 18f, Palette.ground, lines = 3, dots = false).apply { setPadding(ui.dp(14), ui.dp(12), ui.dp(14), ui.dp(12)) })
}
- // 这样改对吗? in the live notes, never while the window is shown to the other side (共享屏幕时
- // 让对方看到): names wait for after the meeting then. Taps reach it; it never takes focus.
asking = false
val sid = app.listen.sessionId
if (!dark && sid != null) {
@@ -381,7 +351,6 @@ class Overlay(private val app: CicadaApp) {
}
}
- /// For the debug receiver: the window as Android has it.
fun describe(): Map<String, Any?> = mapOf(
"shown" to (root != null),
"mode" to if (root != null) mode else null,
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/OverlayGuideActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/OverlayGuideActivity.kt
index 33f7b5d..eb5fe71 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/OverlayGuideActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/OverlayGuideActivity.kt
@@ -15,21 +15,12 @@ import android.widget.LinearLayout
import cicada.Log
import cicada.Strings.L
-/// 显示在其他应用上层: asked for, and when Android holds it back, unlocked step by step.
-///
-/// Android 15+ holds this switch back from apps installed from a file (downloaded by a browser or
-/// chat app, or opened in a file manager): it shows 已停用 and refuses once with 系统已拒绝…, and
-/// only after that refusal does app info's ⋮ menu offer 允许受限制的设置. Checked in the emulator:
-/// Android 15 and 16 hold it back; 14 (where 13's restriction covers accessibility and
-/// notification access only) and 10 don't. Store and USB installs aren't held back. Android
-/// doesn't tell an app whether it is held back, so the guide judges by the version, how it was
-/// installed and the switch still being off when the person comes back.
class OverlayGuideActivity : Activity() {
private enum class Stage { Ask, Retry, Unlock, LastStep, Xiaomi, Done }
private lateinit var ui: Ui
- private var tried = false // the overlay switch's page has been opened
- private var unlockOpened = false // app info (for ⋮ › 允许受限制的设置) has been opened
+ private var tried = false
+ private var unlockOpened = false
private var shown: Stage? = null
private val watch get() = intent.getBooleanExtra("watch", false)
private val direct get() = intent.getBooleanExtra("direct", false)
@@ -39,7 +30,6 @@ class OverlayGuideActivity : Activity() {
ui = Ui(this)
tried = savedInstanceState?.getBoolean("tried") ?: false
unlockOpened = savedInstanceState?.getBoolean("unlockOpened") ?: false
- // From a row that already says what it's for (onboarding, settings): straight to the switch.
if (savedInstanceState == null && direct && !cicada.canOverlay) openSwitch()
}
@@ -74,7 +64,6 @@ class OverlayGuideActivity : Activity() {
start(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName")))
}
- /// Xiaomi's own permission page (其他权限), else app info.
private fun openXiaomi() {
tried = true
val miui = Intent("miui.intent.action.APP_PERM_EDITOR").putExtra("extra_pkgname", packageName)
@@ -154,7 +143,6 @@ class OverlayGuideActivity : Activity() {
setContentView(ui.screen(this, null, back = true, ground = Palette.ground, bottom = bottom, body = body))
}
- /// A video with the subtitle card over it: what the switch is for.
private fun preview() = FrameLayout(this).apply {
background = ui.rounded(Palette.ink, 20)
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
@@ -174,7 +162,6 @@ class OverlayGuideActivity : Activity() {
}
}
- /// One numbered step: a ✓ once done, filled while it's the one to do now.
private fun step(n: Int, text: String, done: Boolean = false, current: Boolean = false, extra: View? = null) = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
setPadding(0, ui.dp(14), 0, ui.dp(14))
@@ -191,7 +178,6 @@ class OverlayGuideActivity : Activity() {
contentDescription = (if (done) L("已完成") + ":" else "") + text
}
- /// App info's top bar with ⋮ ringed and the item it opens.
private fun menuSketch() = ui.stack(8).apply {
background = ui.rounded(Palette.ground, 14)
setPadding(ui.dp(12), ui.dp(10), ui.dp(12), ui.dp(10))
@@ -216,12 +202,10 @@ class OverlayGuideActivity : Activity() {
private val xiaomi get() = Build.MANUFACTURER.lowercase() in setOf("xiaomi", "redmi", "poco")
- /// How this copy was installed (Android 13+): 3 a local file, 4 a downloaded file, 2 a store, 0 USB / unknown.
fun installSource(context: Context): Int = if (Build.VERSION.SDK_INT < 33) -1 else try {
context.packageManager.getInstallSourceInfo(context.packageName).packageSource
} catch (_: Exception) { -1 }
- /// Android 15+ holds the switch back from a copy installed from a file.
fun restrictedLikely(context: Context) = Build.VERSION.SDK_INT >= 35 &&
installSource(context).let { it == PackageInstaller.PACKAGE_SOURCE_LOCAL_FILE || it == PackageInstaller.PACKAGE_SOURCE_DOWNLOADED_FILE }
}
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Pinyin.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Pinyin.kt
index 1563971..c04e0da 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/Pinyin.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Pinyin.kt
@@ -1,8 +1,5 @@
package com.wquguru.cicada
-/// Toneless pinyin for Correction.soundsAlike, from the phone's own ICU (Android 7+): the Mac reads
-/// it from the system's Mandarin transform, one character at a time, and so does this. The CLI's
-/// tests use a table generated from the Mac's transform; `cicadactl.sh pinyin <text>` compares.
object Pinyin {
private val transform by lazy { android.icu.text.Transliterator.getInstance("Han-Latin; Latin-ASCII") }
private val cache = HashMap<Char, String>()
@@ -11,7 +8,6 @@ object Pinyin {
if (!Character.isIdeographic(c.code)) return ""
synchronized(cache) { cache[c]?.let { return it } }
val s = synchronized(transform) { transform.transliterate(c.toString()) }.trim().lowercase()
- // A character ICU can't read comes back as itself: no syllable.
val out = if (s.any { it.code >= 128 } ) "" else s
synchronized(cache) { if (cache.size < 5000) cache[c] = out }
return out
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Recorder.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Recorder.kt
index 06601bf..5d0a302 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/Recorder.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Recorder.kt
@@ -9,9 +9,6 @@ import cicada.Segmenter
import java.io.File
import java.util.concurrent.Executors
-/// 保存会议录音: what was heard, as the Mac keeps it (system.m4a beside session.json, AAC mono).
-/// Written to a .partial file and renamed when the meeting ends, so a record never points at a
-/// half-written file. The audio thread only hands buffers over; encoding has its own thread.
class Recorder(private val target: File) {
private val partial = File(target.path + ".partial")
private val worker = Executors.newSingleThreadExecutor { Thread(it, "Recorder").apply { isDaemon = true } }
@@ -38,7 +35,6 @@ class Recorder(private val target: File) {
fun write(pcm: ShortArray) { if (!failed) worker.execute { feed(pcm, false) } }
- /// Ends the file; `done(true)` once system.m4a is in place. Called off the main thread is fine.
fun finish(done: (Boolean) -> Unit) {
worker.execute {
if (!failed) feed(ShortArray(0), true)
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt
index b8a234c..19ae95a 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt
@@ -25,8 +25,6 @@ import cicada.Strings
import cicada.TranscriptExport
import cicada.TranscriptSearch
-/// 会议记录: every meeting, newest first, grouped by day; search covers titles, notes and what
-/// was said; chips narrow to meetings with notes or to-dos.
class RecordsActivity : Activity() {
private lateinit var ui: Ui
private lateinit var list: FrameLayout
@@ -69,16 +67,13 @@ class RecordsActivity : Activity() {
val body = ui.stack(12, searchBox, HorizontalScrollView(this).apply { isHorizontalScrollBarEnabled = false; addView(chips) }, list)
.apply { setPadding(ui.dp(16), ui.dp(4), ui.dp(16), ui.dp(32)) }
setContentView(ui.screen(this, null, back = true, ground = Palette.ground, body = body))
- // Opened from the floating search button: straight to typing.
if (savedInstanceState == null) { search.requestFocus(); window.setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) }
- // Debug `search <text>`: typed in, as a person would.
if (savedInstanceState == null) intent.getStringExtra("query")?.let { search.setText(it) }
}
override fun onResume() { super.onResume(); current = this; unobserve = cicada.observe(::render); shown = null; render() }
override fun onPause() { super.onPause(); if (current === this) current = null; unobserve?.invoke(); unobserve = null }
- /// For `cicadactl search`: the meetings the search finds (ids), and opening one as a tap does.
fun debugFound(): List<String> = cicada.store.all().filter(::matches).map { it.id }
fun debugOpen(index: Int): String? {
val id = debugFound().getOrNull(index) ?: return null
@@ -88,10 +83,8 @@ class RecordsActivity : Activity() {
}
companion object {
- /// 会议记录 in front, for the debug commands.
var current: RecordsActivity? = null; private set
}
- // The search text is kept by the field itself (it has an id); the filter by us.
override fun onSaveInstanceState(out: Bundle) { super.onSaveInstanceState(out); out.putString("filter", filter) }
private fun matches(s: Session): Boolean {
@@ -99,7 +92,6 @@ class RecordsActivity : Activity() {
if (filter == "todo" && (s.notes?.todos?.isEmpty() != false)) return false
if (query.isEmpty()) return true
val q = query.lowercase()
- // What was said is searched as the record will mark it: misheard names too (TranscriptSearch).
val terms = TranscriptSearch.terms(query, s.notes?.terms.orEmpty())
return SessionStore.displayTitle(s).lowercase().contains(q) ||
s.notes?.let { n -> (n.summary + n.topics.joinToString { it.title + it.points.joinToString() } + n.terms.joinToString { it.name }).lowercase().contains(q) } == true ||
@@ -133,20 +125,13 @@ class RecordsActivity : Activity() {
}
}
-/// One meeting on one white sheet: who spoke (tap a name to change it), 纪要 or the bilingual
-/// 文字记录, and the recording when it was kept (tap a line to hear it there). Export and the
-/// rest are in the sheet behind 更多.
class RecordActivity : Activity() {
private lateinit var ui: Ui
private lateinit var id: String
- // A ListView, so a two-hour meeting's 1,500 lines are drawn as they scroll into view
- // rather than all at once (that froze the screen for over a second).
private lateinit var list: android.widget.ListView
private lateinit var header: FrameLayout
private lateinit var footer: FrameLayout
private lateinit var playerHost: FrameLayout
- // Once the big title scrolls away: the title in the top bar (a tap goes back up) and the
- // tabs pinned under it, as the Mac's pinned bar.
private lateinit var barTitle: TextView
private lateinit var pinnedTabs: FrameLayout
private var headTitle: View? = null
@@ -163,18 +148,13 @@ class RecordActivity : Activity() {
private var speedLabel: TextView? = null
private var scrubber: Scrubber? = null
private var speed = 1f
- // The file is there but MediaPlayer can't open it: said as 找不到录音 instead of a dead bar.
private var broken = false
- private var playing: String? = null // the line at the playhead, for the highlight
- private var playingOn = false // and whether it is sounding (its bars bounce)
- /// The transcript keeps the playing line centred. Scrolling it by finger stops that until a
- /// line is tapped, the bar is used or 回到正在播放 is pressed: following would yank the page away.
+ private var playing: String? = null
+ private var playingOn = false
private var following = true
private lateinit var backToPlaying: LinearLayout
private lateinit var backToPlayingText: TextView
private var toast: FixViews.Toast? = null
- /// Opened from 会议记录's search (#33): what was searched, the lines it finds here (misheard
- /// names too), which one is being looked at, and whether the page still has to go to it.
private var query = ""
private var terms: List<String> = emptyList()
private var found: List<String> = emptyList()
@@ -205,14 +185,11 @@ class RecordActivity : Activity() {
addFooterView(footer, null, false)
setOnItemClickListener { _, _, pos, _ -> (pos - headerViewsCount).takeIf { it in 0 until [email protected] }?.let { playFrom([email protected](it).t) } }
- // 改正听错的词: a long press shows what a line's fixed words were heard as (改回) and 改这句….
setOnItemLongClickListener { _, _, pos, _ -> (pos - headerViewsCount).takeIf { it in 0 until [email protected] }?.let { FixViews.lineSheet(this@RecordActivity, ui, cicada, [email protected], [email protected](it)) } != null }
setOnScrollListener(object : android.widget.AbsListView.OnScrollListener {
override fun onScrollStateChanged(v: android.widget.AbsListView, state: Int) {}
override fun onScroll(v: android.widget.AbsListView, first: Int, visible: Int, total: Int) = pin()
})
- // A finger dragging the list stops following. Not the scroll state: a touch that only
- // catches following's own centring (or a tap during it) reports TOUCH_SCROLL too.
val slop = android.view.ViewConfiguration.get(context).scaledTouchSlop
var downY = 0f
setOnTouchListener { _, e ->
@@ -233,12 +210,9 @@ class RecordActivity : Activity() {
setBackgroundColor(Palette.card)
setPadding(ui.dp(20), ui.dp(6), ui.dp(20), ui.dp(10))
visibility = View.GONE
- isClickable = true // taps on its edges don't reach the lines under it
+ isClickable = true
}
- // The player floats over the bottom of the page (not screen()'s bottom bar), so render()
- // can show it once a live meeting ends and its recording is in place.
playerHost.visibility = View.GONE
- // Scrolled away from what is playing: one way back, just above the player.
backToPlayingText = ui.text("", 13f, android.graphics.Color.WHITE, bold = true, lines = 1).apply { fontFeatureSettings = "tnum" }
backToPlaying = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
@@ -251,13 +225,11 @@ class RecordActivity : Activity() {
elevation = ui.dp(4).toFloat()
visibility = View.GONE
}
- // Where the search is in this meeting: 本场 2 / 7, and the previous and next line found.
- // Under the pinned tabs, so it stays while the transcript scrolls.
matchLabel = ui.text("", 13f, Palette.secondary, lines = 1).apply { fontFeatureSettings = "tnum" }
matchBar = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setBackgroundColor(Palette.card)
- isClickable = true // taps on it don't reach the lines under it
+ isClickable = true
addView(LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = android.view.Gravity.CENTER_VERTICAL
@@ -270,8 +242,6 @@ class RecordActivity : Activity() {
addView(View(context).apply { setBackgroundColor(Palette.divider) }, LinearLayout.LayoutParams(-1, 1))
visibility = View.GONE
}
- // Moved, not laid out, under the tabs: pin() runs inside the list's layout, where a
- // relayout of its neighbours would be missed.
pinnedTabs.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> placeMatchBar() }
val body = FrameLayout(this).apply {
addView(list, FrameLayout.LayoutParams(-1, -1))
@@ -284,14 +254,12 @@ class RecordActivity : Activity() {
ui.roundButton(R.drawable.i_share, L("分享"), onWhite = true) { cicada.store.get(id)?.let(::share) },
ui.roundButton(R.drawable.i_more, L("更多"), onWhite = true) { more() })))
toast = FixViews.Toast(this, ui, cicada, above = 140)
- // Debug `shareSheet <id>`: the 分享… sheet opens over the record.
if (savedInstanceState == null && intent.getBooleanExtra("share", false))
list.post { cicada.store.get(id)?.takeIf { ShareSheet.canShare(cicada, it) }?.let { ShareSheet(this, ui, id).show() } }
}
private fun audio() = cicada.store.audioFile(id)
- /// The banner's line, in view: the transcript tab, scrolled to it.
private fun show(lineId: String) {
val i = adapter.indexOf(lineId)
if (i >= 0) list.post { list.setSelectionFromTop(i + list.headerViewsCount, ui.dp(160)) }
@@ -301,14 +269,11 @@ class RecordActivity : Activity() {
private fun currentMatch(): String? = found.getOrNull(matchIndex.coerceIn(0, maxOf(0, found.size - 1)))
- /// To the previous (-1) or next (1) line found, round the ends, on the transcript.
fun step(d: Int) {
val n = found.size
if (n == 0) return
matchIndex = (matchIndex.coerceIn(0, n - 1) + d + n) % n
if (tab != 1) { tab = 1; render() }
- // While the recording plays, going to a line found stops following it, as a finger does:
- // otherwise the next line heard yanks the page back within seconds.
if (following && player?.isPlaying == true) { following = false; showBackToPlaying() }
showMatchBar()
adapter.notifyDataSetChanged()
@@ -316,8 +281,6 @@ class RecordActivity : Activity() {
Log.d("record search: ${matchIndex + 1}/$n at ${currentMatch()}")
}
- /// The line found, in the middle of the page. A jump from far away lands by a guessed row
- /// height and before the tabs pin, so once laid out it is centred again, exactly.
private fun goToMatch() {
val i = adapter.indexOf(currentMatch())
if (i < 0) return
@@ -338,7 +301,6 @@ class RecordActivity : Activity() {
if (n > 0) matchLabel.text = LF("本场 %lld / %lld", matchIndex.coerceIn(0, n - 1) + 1, n)
}
- /// Every term in a line marked in place; the line being looked at stands out from the rest.
private fun marked(text: CharSequence, current: Boolean): CharSequence {
val ranges = TranscriptSearch.ranges(text.toString(), terms)
if (ranges.isEmpty()) return text
@@ -350,14 +312,10 @@ class RecordActivity : Activity() {
return s
}
- /// The title moves into the top bar once the big one is out of sight, and the tabs pin once
- /// theirs scroll under the top edge (the header leaves the list entirely far down a transcript).
private fun pin() {
- // The list reports a scroll as soon as the listener is set, before the views below exist.
if (!::list.isInitialized || !::barTitle.isInitialized || !::pinnedTabs.isInitialized || !::matchBar.isInitialized) return
val gone = list.firstVisiblePosition > 0
val top = header.top
- // Under the search's bar the tabs are already out of sight.
val inset = if (matchBar.visibility == View.VISIBLE) matchBar.height else 0
fun above(v: View?, by: Int = 0) = gone || (v != null && top + (v.parent as View).top + v.bottom <= by)
val titleAway = above(headTitle)
@@ -373,9 +331,6 @@ class RecordActivity : Activity() {
}
override fun onResume() { super.onResume(); current = this; unobserve = cicada.observe(::render); shown = null; render() }
- // Leaving the record (back, another screen, the phone locked) stops what it was playing.
- // Only a playing player is paused: pause() on one that never started puts MediaPlayer in its
- // error state (the bar came back with a length of 00:00).
override fun onPause() { super.onPause(); if (current === this) current = null; unobserve?.invoke(); unobserve = null; player?.takeIf { it.isPlaying }?.pause(); if (isFinishing) releasePlayer() else updatePlayer() }
override fun onDestroy() { super.onDestroy(); releasePlayer() }
@@ -390,7 +345,6 @@ class RecordActivity : Activity() {
val playable = file && !broken
terms = TranscriptSearch.terms(query, s.notes?.terms.orEmpty())
found = TranscriptSearch.matches(app.store.lines(id), terms)
- // Opened by a search that finds lines here: their transcript, at the first one.
if (landing && app.store.lines(id).isNotEmpty()) {
landing = false
if (found.isNotEmpty()) { tab = 1; matchIndex = 0; list.post { goToMatch() } }
@@ -401,7 +355,6 @@ class RecordActivity : Activity() {
if (key == shown) return
shown = key
showMatchBar()
- // The search's bar sits over the top of the page: the title starts under it.
val top = ui.stack(0).apply { setPadding(ui.dp(20), ui.dp(if (found.isEmpty()) 4 else 52), ui.dp(20), ui.dp(6)) }
val title = ui.title(SessionStore.displayTitle(s), 28f).apply { leading(1.2f) }
top.addView(title)
@@ -413,13 +366,11 @@ class RecordActivity : Activity() {
s.sourceFile?.let { L("导入") }).joinToString(" · ")
top.addView(ui.text(meta, 13f, Palette.secondary), ui.lp(top = 6))
recordingNote(s, live, file, playable)?.let { top.addView(it, ui.lp(top = 6)) }
- // 存到文件夹: where its file is, or why it isn't there yet.
if (!live) FolderExportViews.recordLine(this, ui, s)?.let { top.addView(it, ui.lp(top = 2)) }
speakerChips(s)?.let { top.addView(it, ui.lp(top = 14)) }
val tabLabels = listOf(L("纪要"), "${L("文字记录")} · ${LF("%lld 句", s.lines.size)}")
val tabs = ui.tabs(tabLabels, tab) { tab = it; render() }
top.addView(tabs, ui.lp(top = 18))
- // Over a finished meeting's transcript: the words fixed, and those waiting for the user.
if (tab == 1 && !live) FixViews.reviewBanner(ui, app.fixes, s, onShow = { show(it) }, onEdit = { l, start -> FixViews.edit(this, ui, app, id, l, start) })
?.let { top.addView(it, ui.lp(top = 14)) }
headTabs = tabs
@@ -443,7 +394,6 @@ class RecordActivity : Activity() {
footer.removeAllViews(); footer.addView(bottom)
if (playable && playerHost.childCount == 0) buildPlayer()
playerHost.visibility = if (playable) View.VISIBLE else View.GONE
- // The last lines end above the floating player, but scroll under it.
list.setPadding(0, 0, 0, ui.dp(if (playable) 124 else 40))
val lines = if (tab == 1) app.store.lines(id) else emptyList()
val numbers = SpeakerLabels.numbers(lines)
@@ -451,13 +401,11 @@ class RecordActivity : Activity() {
updatePlayer()
}
- /// One grey line under the date when there is nothing to play: why, and where to change it.
private fun recordingNote(s: Session, live: Boolean, file: Boolean, playable: Boolean): View? {
fun note(text: String) = ui.text(text, 12f, Palette.secondary)
return when {
playable -> null
live -> if (cicada.settings.recordAudio) note(L("会议结束后可以回放录音")) else null
- // Just ended: the recorder is still closing the file (the page updates once it's in place).
java.io.File(audio().path + ".partial").isFile -> null
file || s.hasAudio -> note(L("找不到录音,没法播放"))
s.lines.isEmpty() -> null
@@ -473,7 +421,6 @@ class RecordActivity : Activity() {
}
}
- /// The voices told apart (in records from the Mac or Windows): a chip each; a tap names it.
private fun speakerChips(s: Session): View? {
val numbers = SpeakerLabels.numbers(s.lines)
if (numbers.isEmpty()) return null
@@ -493,7 +440,6 @@ class RecordActivity : Activity() {
return HorizontalScrollView(this).apply { isHorizontalScrollBarEnabled = false; addView(row) }
}
- /// The Mac's 改说话人: the name goes on the voice, so every line, the notes and exports follow.
private fun nameVoice(s: Session, number: Int, shownName: String) {
val voice = SpeakerLabels.voiceOf(s.lines, number) ?: return
ui.input(this, LF("%@ 是谁?", shownName), SpeakerLabels.names(s)[number] ?: "", helper = L("只改这场会议,前面的字幕和纪要一起改"),
@@ -502,7 +448,6 @@ class RecordActivity : Activity() {
}
}
- /// One transcript line per row: time, who, what was said, its translation. Rows are reused.
private inner class LinesAdapter : android.widget.BaseAdapter() {
private var lines: List<cicada.TranscriptLine> = emptyList()
private var numbers: Map<String, Int> = emptyMap()
@@ -530,14 +475,9 @@ class RecordActivity : Activity() {
}
val l = lines[i]
val now = l.id == playing
- // With a recording the whole row plays from its line (the list's item click): the line
- // at the playhead on the pale accent, a grey press on the others; the fill reaches 10dp
- // past the text, as the Mac's.
row.background = if (!playable) null else android.graphics.drawable.InsetDrawable(
ui.ripple(if (now) ui.rounded(PLAYING_LINE, 10) else null, 10), ui.dp(10), 0, ui.dp(10), 0)
- // A background with insets brings its own padding: the row's goes back on after it.
row.setPadding(ui.dp(20), ui.dp(14), ui.dp(20), ui.dp(14))
- // On the time, not the row: a row with a description hides its texts from TalkBack.
(row.getChildAt(0) as TextView).apply {
text = Languages.clock(l.t)
contentDescription = if (playable) "${L("从这里播放")} ${text}" else null
@@ -560,8 +500,6 @@ class RecordActivity : Activity() {
}
}
- /// Three bars that bounce beside the line the recording is playing; nothing while paused
- /// (still bars when the system's animations are off).
private inner class PlayingBars : View(this@RecordActivity) {
var on = false; set(v) { if (field != v) { field = v; invalidate() } }
private val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply { color = Palette.accent }
@@ -584,8 +522,6 @@ class RecordActivity : Activity() {
// MARK: The recording (保存会议录音)
- /// The floating player (iOS's PlayerBar on a white card): play / pause, the progress line
- /// (drag it to seek), the time and the length under it, and the speed.
private fun buildPlayer() {
val play = android.widget.ImageView(this).apply { setImageDrawable(ui.drawable(R.drawable.i_play, android.graphics.Color.WHITE)); importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO }
val button = FrameLayout(this).apply {
@@ -609,12 +545,10 @@ class RecordActivity : Activity() {
val card = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = android.view.Gravity.CENTER_VERTICAL
- // On the white page a shadow alone doesn't separate it: a hairline too.
background = ui.rounded(Palette.card, 32, Palette.line, 1)
ui.lift(this, 6)
setPadding(ui.dp(8), ui.dp(4), ui.dp(4), ui.dp(4))
addView(button, LinearLayout.LayoutParams(ui.dp(48), ui.dp(48)))
- // The line's touch area is taller than the line (scrub.height), the times tucked under it.
addView(LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
addView(scrub, LinearLayout.LayoutParams(-1, ui.dp(24)))
@@ -630,7 +564,6 @@ class RecordActivity : Activity() {
})
}
- /// The progress line: the track grey, what has played in the accent; a tap or a drag seeks.
private inner class Scrubber : View(this@RecordActivity) {
var fraction = 0f; set(v) { field = v; invalidate() }
var dragging = false; private set
@@ -658,7 +591,6 @@ class RecordActivity : Activity() {
return true
}
- // While dragging the time follows the finger; the player moves on release.
private fun showTime() { playTime?.text = Languages.clock(fraction * length()) }
}
@@ -686,7 +618,6 @@ class RecordActivity : Activity() {
private fun start(p: android.media.MediaPlayer) {
p.start()
- // Setting the speed on a paused player starts it on some versions: only ever while playing.
if (speed != 1f) try { p.playbackParams = p.playbackParams.setSpeed(speed) } catch (_: Exception) {}
list.removeCallbacks(tickPlayer); list.post(tickPlayer)
}
@@ -697,7 +628,6 @@ class RecordActivity : Activity() {
updatePlayer()
}
- /// A line's time (or the line): plays the recording from where it was said.
private fun playFrom(t: Double) {
if (playerHost.visibility != View.VISIBLE) return
val p = ensurePlayer() ?: return
@@ -714,7 +644,6 @@ class RecordActivity : Activity() {
follow()
}
- /// 1× → 1.5× → 2× → 1×.
private fun cycleSpeed() {
speed = when (speed) { 1f -> 1.5f; 1.5f -> 2f; else -> 1f }
speedLabel?.text = if (speed == 1.5f) "1.5×" else "${speed.toInt()}×"
@@ -734,8 +663,6 @@ class RecordActivity : Activity() {
scrubber?.fraction = if (dur > 0) (pos / dur).toFloat().coerceIn(0f, 1f) else 0f
}
playLength?.text = Languages.clock(dur)
- // The line being heard: the last one that started at or before the playhead, once
- // playing has begun (iOS's lineID).
val lines = if (p != null && (on || pos > 0)) cicada.store.get(id)?.lines.orEmpty() else emptyList()
val line = lines.lastOrNull { it.t <= pos + 0.2 }
val now = line?.id
@@ -748,7 +675,6 @@ class RecordActivity : Activity() {
if (on && moved && following) centre(adapter.indexOf(now))
}
- /// Back to following the recording: the 回到正在播放 capsule, a tapped line, the bar.
private fun follow() {
backToPlaying.visibility = View.GONE
if (following) return
@@ -763,8 +689,6 @@ class RecordActivity : Activity() {
backToPlaying.animate().alpha(1f).translationY(0f).setDuration(200).start()
}
- /// Scrolls the line being heard to the middle of what shows between the pinned tabs and the
- /// player (the Mac's anchor: .center): smoothly when it is on screen, a jump from far away.
private fun centre(index: Int) {
if (index < 0) return
val pos = index + list.headerViewsCount
@@ -775,14 +699,12 @@ class RecordActivity : Activity() {
if (row != null) list.smoothScrollBy(row.top - y, 300) else list.setSelectionFromTop(pos, y)
}
- /// For `cicadactl state`: the open record's player (never what was said).
fun debugState(): Map<String, Any?> {
val p = player
return mapOf("id" to id, "tab" to tab, "playable" to (playerHost.visibility == View.VISIBLE), "playing" to (p?.isPlaying == true),
"position" to ((p?.currentPosition ?: 0) / 1000.0), "line" to playing, "lineIndex" to adapter.indexOf(playing),
"following" to following, "backToPlaying" to (backToPlaying.visibility == View.VISIBLE),
"firstVisible" to (list.firstVisiblePosition - list.headerViewsCount), "lastVisible" to (list.lastVisiblePosition - list.headerViewsCount),
- // Opened from a search: lines found, the one looked at (1-based), its id and row (never the words).
"search" to if (query.isEmpty()) null else mapOf("matches" to found.size, "at" to (if (found.isEmpty()) 0 else matchIndex + 1),
"line" to currentMatch(), "lineIndex" to adapter.indexOf(currentMatch()), "bar" to (matchBar.visibility == View.VISIBLE)))
}
@@ -793,7 +715,6 @@ class RecordActivity : Activity() {
val s = cicada.store.get(id) ?: return
lateinit var d: android.app.Dialog
fun act(res: Int, label: String, helper: String? = null, red: Boolean = false, run: () -> Unit) = ui.sheetAction(res, label, helper, red) { d.dismiss(); run() }
- // 分享…: a link on cicada.indaloop.app (the round 分享 above sends the Markdown).
val link = act(R.drawable.i_external, L("分享…"), L("生成链接")) { ShareSheet(this, ui, s.id).show() }
if (!ShareSheet.canShare(cicada, s)) { link.alpha = 0.4f; link.isEnabled = false; link.isClickable = false }
val box = ui.stack(0, link,
@@ -803,15 +724,12 @@ class RecordActivity : Activity() {
act(R.drawable.i_captions, L("导出字幕 SRT…"), L("配回原视频用")) { export(s, "srt") })
box.addView(View(this).apply { setBackgroundColor(Palette.divider) }, LinearLayout.LayoutParams(-1, 1).apply { setMargins(ui.dp(8), ui.dp(8), ui.dp(8), ui.dp(8)) })
box.addView(act(R.drawable.i_edit, L("重命名")) { rename(s) })
- // As on the Mac: back to the notes' name once the user named it themselves.
if ((s.renamed ?: !s.title.startsWith("会议 ")) && s.notes?.title != null) box.addView(act(R.drawable.i_restore, L("恢复自动标题")) { cicada.store.rename(s.id, "") })
- // The meeting being listened to can't be deleted (its next lines would vanish).
if (cicada.store.liveId != s.id) box.addView(act(R.drawable.i_trash, L("删除"), red = true) { delete(s) })
d = ui.sheet(this, null, box)
d.show()
}
- /// The Markdown through the share sheet (chat apps, notes apps, Files…).
private fun share(s: Session) {
val send = Intent(Intent.ACTION_SEND).setType("text/plain")
.putExtra(Intent.EXTRA_SUBJECT, SessionStore.displayTitle(s))
@@ -821,13 +739,11 @@ class RecordActivity : Activity() {
private fun copy(s: Session) {
getSystemService(android.content.ClipboardManager::class.java).setPrimaryClip(android.content.ClipData.newPlainText(SessionStore.displayTitle(s), TranscriptExport.markdown(s)))
- // Android 13+ confirms a copy itself; older versions get a toast.
if (android.os.Build.VERSION.SDK_INT < 33) android.widget.Toast.makeText(this, L("已复制"), android.widget.Toast.LENGTH_SHORT).show()
}
private var exportKind = "md"
- /// Saves a file where the user picks (the system file picker), in the Mac's formats.
private fun export(s: Session, kind: String) {
exportKind = kind
val type = when (kind) { "docx" -> "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; "srt" -> "application/x-subrip"; else -> "text/markdown" }
@@ -848,7 +764,6 @@ class RecordActivity : Activity() {
private fun rename(s: Session) {
val shown = MainActivity.name(s)
- // Untouched changes nothing; emptied goes back to the automatic title (the store's rule).
ui.input(this, L("重命名"), shown) { if (it != shown) cicada.store.rename(s.id, it) }
}
@@ -857,9 +772,7 @@ class RecordActivity : Activity() {
}
companion object {
- /// The record in front, for the debug state.
var current: RecordActivity? = null; private set
- /// The line being heard (the Mac's Palette.accentPale) and the player's unplayed track.
private val PLAYING_LINE = android.graphics.Color.parseColor("#FCEDE7")
private val TRACK = android.graphics.Color.parseColor("#E1E3E8")
}
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt
index 8c13640..506af67 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt
@@ -16,9 +16,6 @@ import cicada.Strings
import cicada.Strings.L
import cicada.VoiceCatalog
-/// 设置, a top-level screen beside 会议记录 (the floating navigation): grouped rows as the Mac
-/// groups them (AI 服务, 语言, 听对方, 我说 · 面对面, …), each a value that opens its choices in a
-/// sheet, or a switch whose effect is said under it.
class SettingsActivity : Activity() {
private lateinit var ui: Ui
private lateinit var page: LinearLayout
@@ -35,7 +32,6 @@ class SettingsActivity : Activity() {
private var builtTitle = ""
- // Brought back to the front by the nav, so rebuild if the language changed meanwhile.
override fun onResume() { super.onResume(); if (L("设置") != builtTitle) { recreate(); return }; unobserve = cicada.observe(::build); shown = null; build()
if (pickFolder) { pickFolder = false; FolderExportViews.pick(this) }
}
@@ -51,8 +47,6 @@ class SettingsActivity : Activity() {
shown = key
page.removeAllViews()
- // AI 服务: the service and how it is doing; its key, what works with it and its models are
- // on their own page (AiServiceActivity).
page.addView(ui.sectionLabel(L("AI 服务")))
page.addView(ui.group(listOf(ui.listRow(L("服务"), AiServiceActivity.summary(app), leading = ui.icon(R.drawable.i_lock, 22, Palette.body),
trailing = value(AiServiceActivity.name(app.ling.provider))) {
@@ -68,23 +62,17 @@ class SettingsActivity : Activity() {
s.uiLanguage = it; app.saveSettings(); app.loadStrings(); shown = null; recreate()
})))
- // 听对方: the Mac's listening switches. 说话人识别 tells voices apart on the phone
- // (NativeVoiceprints); should the library not load, it still numbers the voices of
- // records made elsewhere, and the helper says so.
page.addView(ui.sectionLabel(L("听对方")))
val voicesHere = app.listen.speakers?.available == true
page.addView(ui.group(listOf(
ui.switchRow(L("说话人识别"), if (voicesHere) L("按声音标出说话人 1、2…,只在这台手机上处理") else L("显示 Mac 和 Windows 上分出的说话人;这台手机还不能按声音分人"),
s.speakerVoices) { s.speakerVoices = it; app.saveSettings() },
ui.switchRow(L("保存会议录音"), L("只存在这台手机上,会议记录里能回放原声"), s.recordAudio) { s.recordAudio = it; app.saveSettings() },
- // 改正听错的词: its switches and the word list (the Mac's 设置 › 词表).
ui.listRow(L("词表"), if (s.fixMisheard && app.ling.usable) L("会中改正听错的词") else L("已关"),
trailing = value(if (app.vocabulary.terms.isEmpty()) "" else "${app.vocabulary.terms.size}")) {
startActivity(Intent(this, WordListActivity::class.java))
})))
- // 读出来的声音: the voice for the language they speak now, chosen per language on its own
- // page (VoicesActivity, the Mac's VoiceSection). 试一句 reads English in English's voice.
page.addView(ui.sectionLabel(L("我说 · 面对面")))
val their = app.listen.theirLanguage
val theirVoice = VoiceCatalog.option(app.voiceId(their), their, app.ling.config())
@@ -113,7 +101,6 @@ class SettingsActivity : Activity() {
})
page.addView(ui.group(rows))
- // As on the Mac, minus 会议应用挂断后结束: Android can't see another app's microphone.
page.addView(ui.sectionLabel(L("结束会议")))
val endRows = mutableListOf<View>(
choiceRow(L("没人说话时"), listOf("prompt" to L("提醒后结束"), "end" to L("直接结束"), "off" to L("一直记录")), s.silenceEnd,
@@ -122,14 +109,12 @@ class SettingsActivity : Activity() {
"${s.silenceMinutes.toInt()}") { s.silenceMinutes = it.toDouble(); app.saveSettings() })
page.addView(ui.group(endRows))
- // 会后存一份: 存到文件夹 (FolderExportViews), as the Mac's 设置 › 通用.
FolderExportViews.section(this, ui, page)
page.addView(ui.sectionLabel(L("其他")))
page.addView(ui.group(listOf(
ui.listRow(L("导入录音或视频"), L("转成一场会议记录")) { startActivity(Intent(this, ImportActivity::class.java)) },
ui.listRow(L("重看新手引导")) { startActivity(Intent(this, OnboardingActivity::class.java)) }) +
- // Android 13+ can add the tile from here; older versions edit Quick Settings by hand.
(if (android.os.Build.VERSION.SDK_INT >= 33) listOf(ui.listRow(L("添加到快捷设置"), L("下拉通知栏,一键开始或结束听")) { addTile() }) else emptyList()) +
listOf(updateRow())))
val version = packageManager.getPackageInfo(packageName, 0).versionName
@@ -141,7 +126,6 @@ class SettingsActivity : Activity() {
if (requestCode == FolderExportViews.PICK) { shown = null; FolderExportViews.picked(this, resultCode, data) }
}
- /// 检查更新: its answer on the right; with a new version found, tapping it downloads that.
private fun updateRow(): View {
val u = cicada.updates
val found = u.available
@@ -162,13 +146,11 @@ class SettingsActivity : Activity() {
}
}
- /// A row showing its current value; tapping lists the choices.
private fun choiceRow(label: String, options: List<Pair<String, String>>, selected: String, helper: String? = null, changed: (String) -> Unit) =
ui.listRow(label, helper, trailing = value(options.firstOrNull { it.first == selected }?.second ?: selected)) {
ui.choose(this, label, options, selected) { changed(it); shown = null; build() }
}
- /// A sample of how my words will sound to them (the Mac's 试一句), in English's voice.
private fun tryVoice() {
val app = cicada
app.previewVoice(app.voiceId("en"), "en", SAMPLE) { android.widget.Toast.makeText(this, it, android.widget.Toast.LENGTH_SHORT).show() }
@@ -177,7 +159,6 @@ class SettingsActivity : Activity() {
companion object {
const val SAMPLE = "Could you send the revised quote by Friday? We can sign next week."
- /// Debug (`export pick`): open the folder picker once settings is in front.
var pickFolder = false
fun paste(box: android.widget.EditText) {
@@ -185,7 +166,6 @@ class SettingsActivity : Activity() {
val text = clip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.coerceToText(box.context)?.toString()?.trim()
if (!text.isNullOrEmpty()) {
box.setText(text); box.setSelection(text.length)
- // A secret: don't leave it on the clipboard for the next app (or the keyboard's history).
if (text.startsWith("sk-")) try { box.context.getSystemService(ClipboardManager::class.java).clearPrimaryClip() } catch (_: Exception) {}
}
}
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/ShareViews.kt b/android/app/src/main/kotlin/com/wquguru/cicada/ShareViews.kt
index ee60aee..07ab9df 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/ShareViews.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/ShareViews.kt
@@ -26,9 +26,6 @@ import cicada.Strings.L
import cicada.Strings.LF
import java.time.Instant
-/// 分享…: a meeting as a link on cicada.indaloop.app (ShareViews.swift). Settings, then the server's
-/// review, then the link (and its password) or what the review stopped. A meeting already shared
-/// opens on its link. A bottom sheet whose content follows the step.
class ShareSheet(private val activity: Activity, private val ui: Ui, private val sessionId: String) {
private val app = activity.cicada
private sealed class Step {
@@ -39,7 +36,6 @@ class ShareSheet(private val activity: Activity, private val ui: Ui, private val
class Failed(val message: String) : Step()
}
- // A copy: the record is read while the request runs.
private val session: Session = Session.from(app.store.get(sessionId)!!.toJson())
private val hasNotes = session.notes?.isEmpty == false
private var step: Step = Step.Settings
@@ -123,7 +119,6 @@ class ShareSheet(private val activity: Activity, private val ui: Ui, private val
}
lateinit var go: View
if (!showOptions) {
- // The choices already made, in one line; 更改 opens them.
box.addView(LinearLayout(activity).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
@@ -146,8 +141,6 @@ class ShareSheet(private val activity: Activity, private val ui: Ui, private val
if (names) L("显示名字") else L("不显示名字"),
).joinToString(" · ")
- /// Password, expiry, names and the preview, opened by 更改 (in the Mac's order). `go` is the
- /// primary button, made after these rows: the password field turns it off under six characters.
private fun options(go: () -> View) {
val toggles = ui.stack(0).apply { setPadding(0, ui.dp(8), 0, 0) }
toggles.addView(ui.switchRow(L("用密码保护"), null, usePassword, titleLines = 2) { usePassword = it; render() }.apply { setPadding(ui.dp(4), paddingTop, ui.dp(4), paddingBottom) })
@@ -239,8 +232,6 @@ class ShareSheet(private val activity: Activity, private val ui: Ui, private val
}) else buttons(back), ui.lp(top = 18))
}
- /// Would anything be left to share once the flagged parts are out? (A notes-only share whose
- /// notes were flagged has nothing; the server would refuse an empty document.)
private fun leftAfterRemoving(hits: List<ShareHit>, kept: List<Int>): Boolean {
val notesLeft = hasNotes && !dropNotes && hits.none { it.part == "notes" }
if (scope != ShareScope.Full) return notesLeft
@@ -272,7 +263,6 @@ class ShareSheet(private val activity: Activity, private val ui: Ui, private val
private fun done(r: ShareRecord) {
header(if (copied == "all") (if (r.password == null) L("链接已复制") else L("链接和密码已复制")) else L("已分享"))
- // One grey box: the link, and the password under it.
box.addView(ui.stack(4, field(r.url)).apply {
r.password?.let { addView(field(LF("密码:%@", it), Palette.secondary)) }
background = ui.rounded(Palette.ground, 12)
@@ -281,7 +271,6 @@ class ShareSheet(private val activity: Activity, private val ui: Ui, private val
box.addView(buttons(
copyButton(r),
ui.button(L("分享"), "primary", height = 48) {
- // The same message 复制 copies: title, link, password and how long it stays open.
activity.startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain")
.putExtra(Intent.EXTRA_SUBJECT, SessionStore.displayTitle(session)).putExtra(Intent.EXTRA_TEXT, clipboardText(r)), L("分享")))
}), ui.lp(top = 10))
@@ -310,7 +299,6 @@ class ShareSheet(private val activity: Activity, private val ui: Ui, private val
}
}
- // One line, the middle left out when long (selectable text would wrap instead); 复制 copies it whole.
private fun field(text: String, color: Int = Palette.ink) = ui.text(text, 14f, color).apply {
typeface = Typeface.MONOSPACE
isSingleLine = true
@@ -319,8 +307,6 @@ class ShareSheet(private val activity: Activity, private val ui: Ui, private val
private fun clipboardText(r: ShareRecord) = r.message(SessionStore.displayTitle(session))
- /// 复制 copies the whole message. With a password its arrow (or a long press) offers the link or
- /// the password alone, for whoever sends them apart (the Mac's Menu with a primary action).
private fun copyButton(r: ShareRecord): View {
val all = { copy(clipboardText(r), "all"); render() }
val pw = r.password
@@ -379,10 +365,8 @@ class ShareSheet(private val activity: Activity, private val ui: Ui, private val
}
companion object {
- /// The sheet on screen, for the debug commands.
var open: ShareSheet? = null
- /// Not while the meeting is still going, nor before an import has its text.
fun canShare(app: CicadaApp, s: Session) =
!(s.lines.isEmpty() && (s.notes?.isEmpty ?: true)) && app.store.liveId != s.id && s.importing != true
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Ui.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Ui.kt
index 1ff2f02..252b8a6 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/Ui.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Ui.kt
@@ -20,9 +20,6 @@ import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
-/// The palette (AGENTS.md, Views.swift › Palette): ground #F3F4F6, white surfaces, ink #15171C,
-/// one accent #E8552B kept for "live" (the red dot, the timer, progress). Primary buttons are ink:
-/// white on the accent is under 4.5:1.
object Palette {
val ground = Color.parseColor("#F3F4F6")
val card = Color.WHITE
@@ -41,13 +38,8 @@ object Palette {
val onScrim = Color.parseColor("#D7D9DE")
}
-/// Line height as a multiple of the font size, exactly (CSS's line-height). setLineSpacing's
-/// multiplier scales the font's own line height instead, and Noto CJK's is already ~1.3: a
-/// "1.6" there came out as ~2.1 and the notes read double-spaced (the design's type table).
fun TextView.leading(factor: Float) { lineHeight = Math.round(textSize * factor) }
-/// View builders in code (no XML layouts), Material-sized: 48dp touch targets, 56dp rows and main
-/// buttons, ripples on everything tappable.
class Ui(val context: Context) {
fun dp(v: Number): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, v.toFloat(), context.resources.displayMetrics).toInt()
@@ -67,12 +59,8 @@ class Ui(val context: Context) {
fun title(text: String, size: Float = 28f) = text(text, size, Palette.ink, bold = true).apply { leading(1.25f); isAccessibilityHeading = true }
fun heading(text: String, size: Float = 17f) = text(text, size, Palette.ink, bold = true).apply { isAccessibilityHeading = true }
fun helper(text: String, color: Int = Palette.secondary) = text(text, 13f, color)
- /// A group's name over it: grey and regular (as on iOS), lined up with the rows' text.
fun sectionLabel(text: String) = text(text, 13f, Palette.secondary).apply { setPadding(dp(16), dp(18), 0, dp(4)); isAccessibilityHeading = true }
- /// The notes' type scale, the same on every live and record screen (the design's B table):
- /// a 13 grey label over 16 ink body text at 1.6, a 20 bold title. Bold is kept for titles
- /// and names, so a page of notes doesn't read as all bold.
object Type {
const val TITLE = 20f
const val BODY = 16f
@@ -89,7 +77,6 @@ class Ui(val context: Context) {
if (stroke != null) setStroke(dp(strokeDp), stroke)
}
- /// Touch feedback that keeps the shape: a ripple over `base`, clipped to it.
fun ripple(base: Drawable?, radius: Number = 0, dark: Boolean = false): Drawable {
val mask = GradientDrawable().apply { setColor(Color.WHITE); cornerRadius = dp(radius).toFloat() }
val tint = if (dark) 0x33FFFFFF else 0x1F15171C
@@ -107,14 +94,12 @@ class Ui(val context: Context) {
setPadding(dp(padding), dp(padding), dp(padding), dp(padding))
}
- /// A row with a switch; the whole row toggles it.
fun switchRow(label: String, helper: String?, on: Boolean, titleLines: Int = 1, changed: (Boolean) -> Unit): LinearLayout {
val sw = android.widget.Switch(context).apply {
isChecked = on
val states = arrayOf(intArrayOf(android.R.attr.state_checked), intArrayOf())
thumbTintList = ColorStateList(states, intArrayOf(android.graphics.Color.WHITE, Palette.secondary))
trackTintList = ColorStateList(states, intArrayOf(Palette.ink, Palette.outline))
- // The framework track is drawn faded; SRC paints the tint at full strength.
trackTintMode = android.graphics.PorterDuff.Mode.SRC
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
isClickable = false
@@ -135,7 +120,6 @@ class Ui(val context: Context) {
return row
}
- /// A white group of rows with thin dividers (lists, settings).
fun group(rows: List<View>, radius: Int = 22) = LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
background = rounded(Palette.card, radius)
@@ -181,7 +165,6 @@ class Ui(val context: Context) {
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
}
- /// A 48dp round icon button with a label for TalkBack.
fun iconButton(res: Int, label: String, color: Int = Palette.ink, size: Int = 24, dark: Boolean = false, onClick: () -> Unit) = FrameLayout(context).apply {
contentDescription = label
addView(ImageView(context).apply {
@@ -192,8 +175,6 @@ class Ui(val context: Context) {
tappable(this, 24, dark = dark, onClick = onClick)
}
- /// Main buttons, all pills: ink (primary; white on the accent is under 4.5:1), a quiet grey
- /// one, white (on the grey ground, lifted), or the pale accent (tonal).
fun button(label: String, kind: String = "primary", iconRes: Int? = null, height: Int = 56, onClick: () -> Unit): LinearLayout {
val (bg, fg) = when (kind) {
"primary" -> Palette.ink to Color.WHITE
@@ -215,15 +196,12 @@ class Ui(val context: Context) {
}
}
- /// A soft shadow under a white surface on the grey ground (the floating bars, round buttons).
fun lift(v: View, level: Int = 3) {
v.elevation = dp(level).toFloat()
v.outlineAmbientShadowColor = 0x6615171C
v.outlineSpotShadowColor = 0x6615171C
}
- /// A round 48dp white button for the top of a screen (back, share, more), on the grey ground
- /// lifted, on a white page grey.
fun roundButton(res: Int, label: String, onWhite: Boolean = false, onClick: () -> Unit) = FrameLayout(context).apply {
contentDescription = label
addView(ImageView(context).apply {
@@ -235,7 +213,6 @@ class Ui(val context: Context) {
if (!onWhite) lift(this, 1)
}
- /// A text button (dialog-style): dark-accent text, 48dp tall.
fun textButton(label: String, color: Int = Palette.link, onClick: () -> Unit) = text(label, 15f, color, bold = true).apply {
gravity = Gravity.CENTER
minHeight = dp(48)
@@ -248,7 +225,6 @@ class Ui(val context: Context) {
layoutParams = LinearLayout.LayoutParams(dp(size), dp(size))
}
- /// A small rounded label (meta chips, "对方可见", "正在听").
fun badge(label: String, fg: Int = Palette.link, bg: Int = Palette.accentPale, dot: Boolean = false, size: Float = 12f) = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
@@ -259,7 +235,6 @@ class Ui(val context: Context) {
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
- /// A square icon tile (leading icon in rows and descriptions).
fun tile(res: Int, size: Int = 40, bg: Int = Palette.ground, fg: Int = Palette.body) = FrameLayout(context).apply {
background = rounded(bg, size * 0.3)
addView(ImageView(context).apply {
@@ -269,7 +244,6 @@ class Ui(val context: Context) {
layoutParams = LinearLayout.LayoutParams(dp(size), dp(size))
}
- /// A list row: optional leading view, title and supporting text, optional trailing view, chevron.
fun listRow(title: CharSequence, supporting: CharSequence? = null, leading: View? = null, trailing: View? = null, chevron: Boolean = true,
titleView: View? = null, onClick: (() -> Unit)? = null) = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
@@ -289,8 +263,6 @@ class Ui(val context: Context) {
if (onClick != null) tappable(this, 0, onClick = onClick)
}
- /// Pill segments (iOS's segmented control, the design's B): a grey track, the chosen one a
- /// white pill (or ink, `ink`) inside it. `track` white for one on the grey ground.
fun segmented(options: List<Pair<String, String>>, selected: String, ink: Boolean = false, track: Int = Palette.ground, onPick: (String) -> Unit) = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
background = rounded(track, 24)
@@ -317,7 +289,6 @@ class Ui(val context: Context) {
clipToPadding = false; clipChildren = false
}
- /// A filter chip: a white pill, or ink when on.
fun chip(label: String, on: Boolean, onClick: () -> Unit) = text(label, 14f, if (on) Color.WHITE else Palette.ink, bold = on, medium = !on, lines = 1).apply {
gravity = Gravity.CENTER
minHeight = dp(40)
@@ -326,11 +297,9 @@ class Ui(val context: Context) {
tappable(this, 20, rounded(if (on) Palette.ink else Palette.card, 20), dark = on, onClick = onClick)
}
- /// Two or three views of one thing (纪要 / 字幕): pill segments, by index.
fun tabs(labels: List<String>, selected: Int, ink: Boolean = false, track: Int = Palette.ground, onPick: (Int) -> Unit) =
segmented(labels.mapIndexed { i, l -> "$i" to l }, "$selected", ink, track) { onPick(it.toInt()) }
- /// The app icon, rounded like the launcher shows it.
fun logo(size: Int = 64) = ImageView(context).apply {
setImageDrawable(context.getDrawable(R.mipmap.ic_launcher))
layoutParams = LinearLayout.LayoutParams(dp(size), dp(size))
@@ -339,7 +308,6 @@ class Ui(val context: Context) {
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
}
- /// A password-style field whose keyboard "done" key does `done`.
fun keyField(done: () -> Unit) = android.widget.EditText(context).apply {
hint = "sk-…"; setSingleLine()
inputType = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD
@@ -355,10 +323,6 @@ class Ui(val context: Context) {
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(1))
}
- /// An Activity's frame (the design's B, after the iOS app): a large 34 title on the top-level
- /// screens; round back / action buttons on the others, the title (if any) large under them;
- /// a body that scrolls; and an optional bar floating over the bottom of it (the main buttons,
- /// or the 会议记录 / 设置 navigation), the content scrolling under it.
fun screen(activity: Activity, title: String?, back: Boolean, ground: Int, actions: List<View> = emptyList(),
bottom: View? = null, scroll: Boolean = true, body: View, center: View? = null): FrameLayout {
activity.window.statusBarColor = ground
@@ -389,7 +353,6 @@ class Ui(val context: Context) {
})
val inner = readable(body)
val content = if (scroll) ScrollView(context).apply { isVerticalScrollBarEnabled = false; addView(inner); clipToPadding = false } else inner
- // What scrolls ends above the floating bar, but passes under it.
if (bottom != null) {
content.setPadding(content.paddingLeft, content.paddingTop, content.paddingRight, content.paddingBottom + dp(96))
(content as? ViewGroup)?.clipToPadding = false
@@ -403,8 +366,6 @@ class Ui(val context: Context) {
return root
}
- /// The top-level screens' floating navigation (iOS's tab bar, solid white instead of glass):
- /// 会议记录 and 设置 in one pill, search in a round one beside it.
fun nav(activity: Activity, current: String): LinearLayout = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
@@ -445,11 +406,9 @@ class Ui(val context: Context) {
addView(search, LinearLayout.LayoutParams(dp(64), dp(64)).apply { leftMargin = dp(12) })
}
- /// The ground fading in under a floating bar, so text scrolling under it doesn't fight it.
fun fade(color: Int = Palette.ground): Drawable =
GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, intArrayOf(color and 0x00FFFFFF, color, color)).apply { setGradientCenter(0.5f, 0.45f) }
- /// On a tablet or a wide window, the gutter that keeps content at a readable 640dp.
fun sideInset(): Int {
val w = context.resources.configuration.screenWidthDp
return if (w > 700) dp((w - 640) / 2) else 0
@@ -464,7 +423,6 @@ class Ui(val context: Context) {
}
}
- /// The floating bottom area: one or two pill buttons side by side over the fading ground.
fun bottomBar(vararg buttons: View, ground: Int = Palette.ground) = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
background = fade(ground)
@@ -475,8 +433,6 @@ class Ui(val context: Context) {
// MARK: Bottom sheets (no Material library: a Dialog at the bottom, our own shape)
- /// A sheet that rises from the bottom (in place of AlertDialog and PopupMenu): a grab bar,
- /// an optional title, then `content`.
fun sheet(activity: Activity, title: String?, content: View): android.app.Dialog {
val d = android.app.Dialog(activity)
d.requestWindowFeature(android.view.Window.FEATURE_NO_TITLE)
@@ -501,7 +457,6 @@ class Ui(val context: Context) {
return d
}
- /// One action in a sheet: a round grey icon, the label (and a grey line), red when it destroys.
fun sheetAction(res: Int, label: String, helper: String? = null, destructive: Boolean = false, onClick: () -> Unit) = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
@@ -518,7 +473,6 @@ class Ui(val context: Context) {
tappable(this, 16, onClick = onClick)
}
- /// Choose one of `options` in a sheet (replaces the single-choice AlertDialog).
fun choose(activity: Activity, title: String, options: List<Pair<String, String>>, selected: String, onPick: (String) -> Unit) {
val list = stack(0)
lateinit var d: android.app.Dialog
@@ -529,7 +483,6 @@ class Ui(val context: Context) {
gravity = Gravity.CENTER_VERTICAL
minimumHeight = dp(52)
setPadding(dp(16), dp(6), dp(12), dp(6))
- // Two lines: a model with why it's recommended runs long, more so in English.
addView(text(label, 16f, Palette.ink, bold = on, lines = 2), weight())
if (on) addView(icon(R.drawable.i_check, 20, Palette.ink), LinearLayout.LayoutParams(dp(20), dp(20)))
contentDescription = label
@@ -542,7 +495,6 @@ class Ui(val context: Context) {
d.show()
}
- /// Asks before something happens: a message and two pills, the safe one first-reached.
fun confirm(activity: Activity, title: String, message: String?, ok: String, cancel: String = cicada.Strings.L("取消"),
destructive: Boolean = false, onOk: () -> Unit) {
lateinit var d: android.app.Dialog
@@ -559,9 +511,6 @@ class Ui(val context: Context) {
d.show()
}
- /// A text to type (rename): the field, 取消 and 保存. The keyboard comes up with the sheet.
- /// `type`: an InputType for the field (an address or a model id wants the URL keyboard: a pinyin
- /// keyboard types "192。168" and ":").
fun input(activity: Activity, title: String, initial: String, helper: String? = null, hint: String? = null, type: Int? = null, onSave: (String) -> Unit) {
lateinit var d: android.app.Dialog
val box = android.widget.EditText(activity).apply {
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Updates.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Updates.kt
index 5bfcf82..fba9ed4 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/Updates.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Updates.kt
@@ -16,14 +16,9 @@ import cicada.Strings.L
import cicada.Strings.LF
import cicada.UpdateChecker
-/// 检查更新 (the Windows App's Updates part): finds a newer APK on GitHub Releases and says so on
-/// 首页 (below the start card, not while listening), in 设置 › 其他, and once per version in a
-/// notification. 更新 hands the APK link to the browser; the system installer does the rest.
class AppUpdates(private val app: CicadaApp) {
val checker = UpdateChecker(app.packageManager.getPackageInfo(app.packageName, 0).versionName ?: "0", app.settings.updateLastChecked)
- /// Release builds check; the dev build only once `updatefeed` points it somewhere.
@Volatile var enabled = !BuildConfig.DEBUG; private set
- /// 检查更新 in 设置: null, or the answer to the last manual check for a few seconds.
@Volatile var manual: String? = null; private set
private val clearManual = Runnable { manual = null; app.changed() }
@@ -38,7 +33,6 @@ class AppUpdates(private val app: CicadaApp) {
app.changed()
}
}
- // Updated since the last notification: it is about this version or an older one.
app.settings.updateNotified?.let { if (!UpdateChecker.isNewer(it, checker.current)) cancelNotification() }
if (!enabled) return
schedule()
@@ -47,7 +41,6 @@ class AppUpdates(private val app: CicadaApp) {
fun checkIfDue(age: Long) { if (enabled) app.background.execute { checker.checkIfDue(age) } }
- /// The debug command `updatefeed`: another release JSON, checked now.
fun setFeed(feed: String) {
checker.feed = feed.ifEmpty { UpdateChecker.FEED }
enabled = true
@@ -55,7 +48,6 @@ class AppUpdates(private val app: CicadaApp) {
Log.d("update: feed set")
}
- /// 检查更新: says 正在检查… / 已是最新版本 / 连不上 GitHub for a few seconds.
fun checkNow() {
if (manual == L("正在检查…")) return
enabled = true
@@ -71,7 +63,6 @@ class AppUpdates(private val app: CicadaApp) {
}
}
- /// 更新: the browser downloads the APK (or shows the release page when there is none).
fun download() { available?.let { open(it.apk ?: it.page); Log.d("update: download ${it.version}") } }
fun openNotes() { available?.let { open(it.page) } }
@@ -83,7 +74,6 @@ class AppUpdates(private val app: CicadaApp) {
// MARK: In the background
- /// About once a day while the phone has a network; the job survives a restart.
private fun schedule() {
try {
val js = app.getSystemService(JobScheduler::class.java)
@@ -97,8 +87,6 @@ class AppUpdates(private val app: CicadaApp) {
} catch (e: Exception) { Log.d("update: job not scheduled ${e.javaClass.simpleName}") }
}
- /// The job's check: a new version gets one notification, unless Cicada is in front (首页 says
- /// it) or a meeting is going on (the next run tells, the version not yet marked as told).
fun checkInBackground() {
if (!enabled) return
checker.check()
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Voice.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Voice.kt
index 5166678..9779f08 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/Voice.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Voice.kt
@@ -13,9 +13,6 @@ import java.util.Locale
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
-/// The system's text-to-speech, or the AI service's voice, for saying my translated words to the
-/// person in front of me. Only ever given a translation (ListenEngine.said checks that): never what
-/// I said myself.
class Voice(private val context: Context) {
enum class Result { Spoken, NoVoice, Failed }
@@ -24,7 +21,6 @@ class Voice(private val context: Context) {
private var ok = false
@Volatile var speaking = false; private set
- /// Starts the engine early (it takes ~1 s), so the first sentence isn't late.
fun warm() { engine() }
@Synchronized private fun engine(): TextToSpeech? {
@@ -48,8 +44,6 @@ class Voice(private val context: Context) {
return r >= TextToSpeech.LANG_AVAILABLE
}
- /// Speaks `text` in `lang`; `onStart` / `onEnd` come on a TTS thread. Call off the main thread
- /// (waits for the engine the first time).
fun speak(text: String, lang: String, onStart: () -> Unit, onEnd: () -> Unit): Result {
val t = engine() ?: return Result.Failed
val locale = Locale.forLanguageTag(lang)
@@ -70,11 +64,6 @@ class Voice(private val context: Context) {
private class Stopped : RuntimeException()
@Volatile private var track: AudioTrack? = null
- /// Reads `text` in the AI service's `voiceName` (Ming's with `language`, Ming's language_id), or
- /// in the user's own voice cloned from `reference`: its 24 kHz PCM goes into an AudioTrack as it
- /// arrives, so the first words play before the rest has come. Blocks until it has played (or
- /// `stop`). `onStart` comes with the first sound; `onEnd` always comes. Failed lets the caller
- /// fall back to the phone's voice.
fun speakCloud(ling: LingClient, text: String, voiceName: String?, language: String?,
onStart: () -> Unit, onEnd: () -> Unit, reference: Pair<String, String>? = null): Result {
val rate = LingClient.TTS_RATE
@@ -99,7 +88,6 @@ class Voice(private val context: Context) {
frames += pcm.size / 2
}
if (frames == 0L) return Result.Failed
- // What was written plays out before the track goes (a few seconds at most).
val until = System.currentTimeMillis() + frames * 1000 / rate + 2000
while (track === t && t.playbackHeadPosition < frames && System.currentTimeMillis() < until) Thread.sleep(40)
Log.d("voice: cloud done")
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/VoiceRecordActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/VoiceRecordActivity.kt
index a7bb271..ab9341f 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/VoiceRecordActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/VoiceRecordActivity.kt
@@ -27,9 +27,6 @@ import cicada.Wav
import java.io.File
import kotlin.concurrent.thread
-/// 我自己的声音: the Mac's VoiceCloneSheet as a page. Read a passage for 10–15 s → Ming writes down
-/// what it says → listen to the recording and to the clone → 用这个声音 keeps it (VoiceReference)
-/// and picks it for the language the picker was on (`id`). Nothing is kept until then.
class VoiceRecordActivity : Activity() {
private enum class Phase { Idle, Recording, Checking, Ready, Failed }
@@ -46,7 +43,6 @@ class VoiceRecordActivity : Activity() {
private var playingOriginal = false
private var unobserve: (() -> Unit)? = null
- /// My language: the passage is in it, and it decides 最像你 / 会带你的口音.
private val own get() = cicada.settings.targetCode
override fun onCreate(savedInstanceState: Bundle?) {
@@ -55,7 +51,6 @@ class VoiceRecordActivity : Activity() {
language = intent.getStringExtra("id") ?: cicada.listen.theirLanguage
page = ui.stack(0).apply { setPadding(ui.dp(24), 0, ui.dp(24), ui.dp(32)) }
setContentView(ui.screen(this, null, back = true, ground = Palette.card, body = page))
- // Debug (`show record <wav in files/>`): a pushed WAV stands in for the microphone.
intent.getStringExtra("wav")?.let { name ->
try { pcm = Wav.read(File(filesDir, name).inputStream()); seconds = pcm.size / Segmenter.RATE.toDouble(); phase = Phase.Recording; finishRecording(); return } catch (e: Exception) { Log.d("voice clone: no ${e.javaClass.simpleName}") }
}
@@ -114,7 +109,6 @@ class VoiceRecordActivity : Activity() {
}
}
- /// The big round button: a mic to start, a square to finish.
private fun recordButton(label: String) = FrameLayout(this).apply {
contentDescription = label
background = ui.rounded(Palette.accentPale, 44)
@@ -164,8 +158,6 @@ class VoiceRecordActivity : Activity() {
private var clockView: android.widget.TextView? = null
private var barView: ProgressBar? = null
- /// The clock, 10 times a second; at 15 s the recording finishes by itself. Only the clock and
- /// bar change: rebuilding the page would drop a tap on 读完了 halfway through.
private fun tick() {
if (phase != Phase.Recording || isDestroyed) return
seconds = pcm.size / Segmenter.RATE.toDouble()
@@ -182,7 +174,6 @@ class VoiceRecordActivity : Activity() {
r.release()
}
- /// Stops, then the Mac's checks: long enough, heard, not read too slowly.
private fun finishRecording() {
if (phase != Phase.Recording) return
stopRecorder()
@@ -196,7 +187,6 @@ class VoiceRecordActivity : Activity() {
app.main.post {
if (isDestroyed) return@post
when (result) {
- // The trimmed clip is what's tried and kept, and its length is what's shown.
is VoiceReference.Check.Ok -> { transcript = result.text; pcm = result.pcm; seconds = pcm.size / Segmenter.RATE.toDouble(); phase = Phase.Ready }
is VoiceReference.Check.Again -> { problem = Strings.LF(result.reason, *result.args.toTypedArray()); phase = Phase.Failed }
}
@@ -291,7 +281,6 @@ class VoiceRecordActivity : Activity() {
}
companion object {
- /// previewVoice's id while the unsaved recording is tried.
const val DRAFT = VoiceCatalog.CLONE
}
}
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Voiceprints.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Voiceprints.kt
index 9f283cb..e70c7d9 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/Voiceprints.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Voiceprints.kt
@@ -6,9 +6,6 @@ import cicada.Voiceprinter
import java.io.File
/// 说话人识别's voiceprints on the phone: the Mac's model (WeSpeaker ResNet34-LM, VoxCeleb, CC BY
-/// 4.0) run by linux/native/voiceprint.c, built with the NDK into libcicada-voice.so (src/main/jni).
-/// The weights are linux/models/voiceprint.bin, an asset copied out once (the C reads a file).
-/// Should the library not load, `create` gives null and listening carries on unlabelled.
class NativeVoiceprints private constructor(private val context: Context) : Voiceprinter {
private var model = 0L
private var tried = false
@@ -20,7 +17,6 @@ class NativeVoiceprints private constructor(private val context: Context) : Voic
}
if (m == 0L) return null
val out = FloatArray(DIMS)
- // One at a time: each already uses up to four cores.
return synchronized(this) { if (nativeEmbed(m, samples, samples.size, out) == 0) out else null }
}
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/VoicesActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/VoicesActivity.kt
index 22b7013..a0b6043 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/VoicesActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/VoicesActivity.kt
@@ -17,10 +17,6 @@ import cicada.VoiceCatalog
import cicada.VoiceOption
import cicada.VoiceReference
-/// 读出来的声音 (Settings › 我说 · 面对面): the Mac's voice picker (VoicePicker.swift) as a page.
-/// Each language remembers its own voice (`speakVoices`); the list is the service's voices for the
-/// language (Ming's on Ling), then the phone's, each with 试听. Opened on the language they speak
-/// now (the `id` extra); the pill switches language.
class VoicesActivity : Activity() {
private lateinit var ui: Ui
private lateinit var page: LinearLayout
@@ -51,7 +47,6 @@ class VoicesActivity : Activity() {
shown = key
page.removeAllViews()
- // "每种语言各记一个声音" for the language they speak now, "对方说…时用" for another, and the pill.
val current = VoiceCatalog.key(language) == VoiceCatalog.key(now)
val head = ui.row(10,
ui.helper(if (current) L("每种语言各记一个声音") else Strings.LF("对方说%@时用", VoiceCatalog.title(language))).apply { layoutParams = ui.weight() },
@@ -64,7 +59,6 @@ class VoicesActivity : Activity() {
page.addView(ui.helper(footnote(), Palette.tertiary).apply { setPadding(ui.dp(4), ui.dp(10), ui.dp(4), 0) })
}
- /// The language menu: the Mac's tabs, the one they speak now marked.
private fun pill(label: String) = ui.row(6,
ui.text(label, 14f, Palette.ink, medium = true, lines = 1),
ui.icon(R.drawable.i_chevron_down, 16, Palette.tertiary)).apply {
@@ -96,8 +90,6 @@ class VoicesActivity : Activity() {
return row
}
- /// 我自己的声音, last (the Mac's cloneRow): only Ling clones, so another service offers 去换成 Ling;
- /// without a recording, 录制; with one, 试听, how it was recorded, 重录 · 删除, and the radio.
private fun cloneRow(chosen: String): View {
val app = cicada
val ling = app.ling
@@ -120,12 +112,10 @@ class VoicesActivity : Activity() {
val selected = chosen == VoiceCatalog.CLONE
val own = VoiceCatalog.key(app.settings.targetCode) == VoiceCatalog.key(language)
val note = if (VoiceReference.savedIsSlow) L("读得偏慢") else if (own) L("最像你") else L("会带你的口音")
- // The Mac's one line, as two: 重录 · 删除 don't fit beside it on a phone in English.
val links = ui.row(0,
link(L("重录")) { record() },
ui.text(" · ", 13f, Palette.secondary),
link(L("删除")) {
- // A small link on a phone: asked first, unlike the Mac.
ui.confirm(this, L("删除"), L("我自己的声音"), L("删除"), destructive = true) { app.removeVoiceReference(); shown = null; build() }
})
val texts = ui.stack(2, ui.text(L("我自己的声音"), 16f, Palette.ink, bold = true, lines = 1),
@@ -168,7 +158,6 @@ class VoicesActivity : Activity() {
ui.tappable(this, 18, ui.rounded(if (primary) Palette.ink else Palette.card, 18, stroke = if (primary) null else Palette.line), dark = primary) { onClick() }
}
- /// 试听: a round play button (accent when the voice is the chosen one), a spinner while it plays.
private fun playButton(id: String, highlighted: Boolean, enabled: Boolean): View {
val app = cicada
val playing = app.previewing == id
@@ -189,7 +178,6 @@ class VoicesActivity : Activity() {
private fun radio(on: Boolean) = FrameLayout(this).apply {
background = GradientDrawable().apply { shape = GradientDrawable.OVAL; setStroke(ui.dp(2), if (on) Palette.accent else Palette.outline) }
if (on) addView(ui.dot(Palette.accent, 10), FrameLayout.LayoutParams(ui.dp(10), ui.dp(10), Gravity.CENTER))
- // listRow sizes its trailing view by content: an empty ring needs its own size.
minimumWidth = ui.dp(20); minimumHeight = ui.dp(20)
layoutParams = LinearLayout.LayoutParams(ui.dp(20), ui.dp(20))
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
@@ -202,10 +190,8 @@ class VoicesActivity : Activity() {
}
companion object {
- /// The name a voice shows by (the phone's and the user's own are UI text).
fun name(v: VoiceOption): String = if (v.id == VoiceCatalog.PHONE || v.id == VoiceCatalog.CLONE) L(v.name) else v.name
- /// "女 · 美式 · Ming" / "本机 · 最快": who it is and where it comes from.
fun summary(v: VoiceOption): String = when {
v.id == VoiceCatalog.PHONE -> listOf(L("本机"), L("最快")).joinToString(" · ")
v.id.startsWith(VoiceCatalog.MING) -> (v.tags.take(2).map { L(it) } + "Ming").joinToString(" · ")
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/WordListActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/WordListActivity.kt
index 4e743ab..dea81e5 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/WordListActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/WordListActivity.kt
@@ -13,10 +13,6 @@ import cicada.Strings.L
import cicada.Strings.LF
import cicada.Vocabulary
-/// 设置 › 词表 (the Mac's WordListSettings.swift): the two switches of 改正听错的词, and the word list
-/// itself: each word (tap to change its spelling), what it has been heard as (× takes one off, +
-/// adds one), where it came from and how often it fixed a line. A deleted word comes back with
-/// 撤销; 粘贴导入… takes many at once and says what it will do first.
class WordListActivity : Activity() {
private lateinit var ui: Ui
private lateinit var page: LinearLayout
@@ -24,7 +20,6 @@ class WordListActivity : Activity() {
private var shown: String? = null
private var query = ""
private var search: EditText? = null
- /// A deleted word, shown in its place with 撤销 for a few seconds.
private var deleted: Pair<Vocabulary.Term, Int>? = null
private var deletedAt = 0L
@@ -47,7 +42,6 @@ class WordListActivity : Activity() {
shown = key
page.removeAllViews()
- // The switches; without an AI service the first gives way to a way to set one up.
val usable = app.ling.usable
val fixRow = if (usable) ui.switchRow(L("会中改正听错的词"), LF("走 %@,只发文字", AiServiceActivity.name(app.ling.provider)), s.fixMisheard) {
s.fixMisheard = it; app.saveSettings()
@@ -58,7 +52,6 @@ class WordListActivity : Activity() {
if (!s.fixMisheard || !usable) { askRow.alpha = 0.45f; askRow.isEnabled = false; disable(askRow) }
page.addView(ui.group(listOf(fixRow, askRow)), ui.lp(top = 8))
- // 词 · N, and 粘贴导入….
page.addView(LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
@@ -108,7 +101,6 @@ class WordListActivity : Activity() {
v.setOnClickListener(null)
}
- /// Most recently useful first, then the rest newest first; the search keeps words or heard forms that match.
private fun shownTerms(terms: List<Vocabulary.Term>): List<Vocabulary.Term> {
val all = terms.reversed().sortedByDescending { it.used ?: java.time.Instant.EPOCH }
val q = Vocabulary.key(query)
@@ -124,7 +116,6 @@ class WordListActivity : Activity() {
row.addView(LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
- // The word: a tap changes its spelling; what it was heard as stays with it.
addView(ui.text(t.word, 17f, Palette.ink, bold = true, lines = 1).apply {
contentDescription = "${t.word},${L("点一下改写法")}"
minHeight = ui.dp(40); gravity = Gravity.CENTER_VERTICAL
@@ -132,7 +123,6 @@ class WordListActivity : Activity() {
}, ui.weight())
addView(ui.iconButton(R.drawable.i_trash, L("从词表里删掉"), Palette.tertiary, 20) { remove(t) })
})
- // What it has been heard as: × takes one off; + adds one (asking whose it is when another word has it).
val chips = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
var line = LinearLayout(this)
var used = 0
@@ -175,7 +165,6 @@ class WordListActivity : Activity() {
if (h.isEmpty() || h.length > 40) return@input
val owner = v.owners(h, t.word).firstOrNull()
if (owner == null) { v.confirm(h, t.word, t.source); return@input }
- // Already another word's: whose should it be? Both kept is asked about each time, never fixed silently.
lateinit var d: android.app.Dialog
val body = ui.stack(10,
ui.button(LF("改给 %@", t.word), "primary") { d.dismiss(); v.forget(h, owner); v.confirm(h, t.word, t.source) },
@@ -196,8 +185,6 @@ class WordListActivity : Activity() {
build()
}
- /// 粘贴导入: one per line, heard forms after "="; the counts follow what is pasted, and the
- /// button says how many go in.
private fun importSheet() {
val v = cicada.vocabulary
lateinit var d: android.app.Dialog
diff --git a/android/cli/build.gradle.kts b/android/cli/build.gradle.kts
index f7d688d..03ba92e 100644
--- a/android/cli/build.gradle.kts
+++ b/android/cli/build.gradle.kts
@@ -1,5 +1,3 @@
-// cicada-cli: the engines without Android. `test` runs the unit tests; `listen`, `hear`,
-// `segments` and `roundtrip` run them for real on the Mac (scripts/cli.sh).
plugins { id("org.jetbrains.kotlin.jvm"); application }
kotlin { jvmToolchain(21) }
dependencies { implementation(project(":core")) }
diff --git a/android/cli/src/main/kotlin/cicada/cli/AICheckTests.kt b/android/cli/src/main/kotlin/cicada/cli/AICheckTests.kt
index 6cef472..185a513 100644
--- a/android/cli/src/main/kotlin/cicada/cli/AICheckTests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/AICheckTests.kt
@@ -1,5 +1,3 @@
-// AI 服务检查 (AICheck.kt): the Mac's AICheckTests, plus the port's fourth step (hearing) and the
-// client's check and passive results against a fake transport. No network.
package cicada.cli
import cicada.*
@@ -43,7 +41,6 @@ object AICheckTests {
equal(AICheck.Failure(StepID.Text, Reason.Busy, null), AICheck.classify(LingException(LingException.Kind.RateLimited), StepID.Text), "429")
equal(AICheck.Failure(StepID.Key, Reason.ServerError, 503), AICheck.classify(http(503), StepID.Key), "5xx")
equal(null, AICheck.classify(LingException(LingException.Kind.Hijacked), StepID.Text), "hijacked")
- // The hear model: the same codes mean it takes no audio, not that it is missing.
for (code in listOf(400, 404, 415, 422)) equal(AICheck.Failure(StepID.Hear, Reason.Deaf, code), AICheck.classify(http(code), StepID.Hear), "hear $code")
equal(AICheck.Failure(StepID.Text, Reason.ServerError, 415), AICheck.classify(http(415), StepID.Text), "text 415")
equal(AICheck.Failure(StepID.Hear, Reason.Busy, null), AICheck.classify(LingException(LingException.Kind.RateLimited), StepID.Hear), "hear 429")
@@ -68,11 +65,9 @@ object AICheckTests {
}
fun hearIsNotText() {
- // Heard audio proves the address, the key and the hear model, never the text model.
val c = AICheck().fail(StepID.Reach, Reason.Unreachable).pass(StepID.Hear, 0.9)
equal(State.Untested, c[StepID.Text], "text unproven")
equal(State.Ok(0.9), c[StepID.Hear], "hear")
- // A deaf reply doesn't make the text model look fine either, nor clear its own failure.
val d = AICheck().fail(StepID.Hear, Reason.Deaf, 400)
equal(State.Untested, d[StepID.Text], "text still unproven")
val m = AICheck().fail(StepID.Text, Reason.NoModel, 404).pass(StepID.Hear, 1.0)
@@ -80,8 +75,6 @@ object AICheckTests {
}
fun blocking() {
- // The Mac's AIServiceStrip.blocking, plus the port's deaf hear model: a key, the credit, a
- // model or the settings. The network, a busy service and a server error fix themselves.
val needs = setOf(Reason.InvalidKey, Reason.MgmtKey, Reason.NoCredit, Reason.NoModel, Reason.NoJSON, Reason.BadAddress, Reason.Deaf)
for (r in Reason.values()) {
val b = AICheck.simulated(r).blocking("Ling", "openai/gpt-x", "google/omni-y")
@@ -91,7 +84,6 @@ object AICheckTests {
equal("Ling 的 key 用不了" to "修好之前听不了", AICheck.simulated(Reason.InvalidKey).blocking("Ling", "t", "h"), "key")
equal("ZenMux 上找不到 gpt-x 这个模型。" to "字幕照常,纪要先停下", AICheck.simulated(Reason.NoModel).blocking("ZenMux", "openai/gpt-x", "h"), "short model, notes only")
equal("omni-y 听不了声音。", AICheck.simulated(Reason.Deaf).blocking("ZenMux", "t", "google/omni-y")?.first, "deaf")
- // A heard segment after a bad key clears it: back to normal.
equal(null, AICheck.simulated(Reason.InvalidKey).pass(StepID.Hear, 1.0).blocking("Ling", "t", "h"), "fixed")
}
@@ -192,13 +184,11 @@ object AICheckTests {
}
fun clientHearCatalog() {
- // Answers the silent clip, but the service says it takes no audio in.
val s = AppSettings(aiProvider = "zenmux", aiHearModels = mutableMapOf("zenmux" to "x/text-only"))
val ling = client(Fake(::service), s)
ling.check()
equal(Reason.Deaf, ling.aiCheck.failure?.reason, "deaf by the catalog")
equal(false, ling.hears, "can't hear")
- // A custom service that lists models without saying what they take: the probe decides.
val custom = AppSettings(aiProvider = "custom", aiCustomBase = "https://x.example/v1", aiModels = mutableMapOf("custom" to "qwen3:14b"),
aiHearModels = mutableMapOf("custom" to "qwen3-omni"))
val plain = client(Fake { url, body -> if (url.endsWith("models")) Transport.Response(200, """{"data":[{"id":"qwen3:14b"},{"id":"qwen3-omni"}]}""") else service(url, body) }, custom, key = "sk-x-0000")
@@ -240,7 +230,6 @@ object AICheckTests {
down = false
ling.networkChanged()
check(ling.aiCheck.passed, "looked again: ${ling.aiCheck.summary}")
- // Only after an unreachable result: a good service isn't checked on every network change.
val calls = (ling.aiCheck.at)
ling.networkChanged()
equal(calls, ling.aiCheck.at, "no check")
@@ -250,22 +239,18 @@ object AICheckTests {
var answer: (String) -> Transport.Response = { reply("OK") }
val ling = client(Fake { url, body -> if (url.endsWith("models")) Transport.Response(200, MODELS) else answer(body) }, AppSettings(aiProvider = "zenmux"))
ling.check()
- // Heard audio in a meeting: the hear step, from a real request.
answer = { Transport.Response(400, "{}") }
try { ling.chat("c", "i", Priority.Translate, model = "qwen/qwen3.8-omni-flash", audio = byteArrayOf(1)) } catch (_: LingException) {}
equal(Reason.Deaf, ling.aiCheck.failure?.reason, "deaf from a meeting")
check(ling.aiCheck.passive, "passive")
- // The notes: a 429 is busy, not a failure; then a good reply clears it.
answer = { Transport.Response(429, "{}") }
try { ling.chat("c", "i", Priority.Translate) } catch (_: LingException) {}
answer = { reply("fine") }
- ling.chat("c", "i", Priority.Notes) // waits out the pause after the 429
+ ling.chat("c", "i", Priority.Notes)
equal(State.Ok::class, ling.aiCheck[StepID.Text]::class, "text proven")
- // The network goes in the middle of a meeting.
answer = { throw java.io.IOException("down") }
try { ling.chat("c", "i", Priority.Translate) } catch (_: LingException) {}
equal(Reason.Unreachable, ling.aiCheck.failure?.reason, "unreachable")
- // A server error once isn't worth repainting the settings for.
answer = { reply("back") }
ling.chat("c", "i", Priority.Translate)
answer = { Transport.Response(503, "{}") }
diff --git a/android/cli/src/main/kotlin/cicada/cli/FixTests.kt b/android/cli/src/main/kotlin/cicada/cli/FixTests.kt
index 40740ce..7d47fbb 100644
--- a/android/cli/src/main/kotlin/cicada/cli/FixTests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/FixTests.kt
@@ -1,5 +1,3 @@
-// 改正听错的词: the Mac's CorrectionTests, VocabularyTests and LiveFixesTests (cases from a
-// 21-minute meeting recording), and records with fixes read and written as the Mac does.
package cicada.cli
import cicada.*
@@ -51,8 +49,6 @@ object FixTests {
"aLineMingTranslatedIsFixedByOneMoreRequest" to ::aLineMingTranslatedIsFixed,
)
- /// The Mac's own transform for each character (generated with CFStringTransform, as
- /// Correction.swift reads it); the phone's ICU "Han-Latin; Latin-ASCII" gives the same syllables.
private val table: Map<Char, String> by lazy {
FixTests::class.java.getResourceAsStream("/pinyin.tsv")!!.bufferedReader().readLines()
.mapNotNull { l -> l.split('\t').takeIf { it.size == 2 && it[0].length == 1 }?.let { it[0][0] to it[1] } }.toMap()
@@ -65,7 +61,6 @@ object FixTests {
// MARK: Records
- /// As the Mac writes a line with fixes (JSONEncoder, sorted keys, nil left out).
val MAC_WITH_FIXES = """
{
"endedAt" : "2026-11-07T08:24:12Z",
@@ -121,7 +116,6 @@ object FixTests {
equal("解释这个Morpho的,质压和开布特", l.shown, "shown: applied fixes only")
equal(null, s.lines[1].fixes, "a line without fixes has none")
equal(MAC_WITH_FIXES, Json.write(s.toJson()), "written back byte for byte")
- // A copy (what the screens read) keeps them, apart from the record's own.
val c = l.copy(); c.fixes!![0].off = true
equal(null, l.fixes!![0].off, "copies are deep")
}
@@ -173,7 +167,6 @@ object FixTests {
equal(A, verdict("两个代笔", "两个代币", 0.9), "代笔")
equal(A, verdict("管理房", "管理方", 0.9), "管理房")
equal(A, verdict("追压", "质押", 0.85), "追压")
- // Only the changed part is compared: 花/概 share nothing, though the phrase around them does.
equal(D, verdict("花了大花", "花了大概", 0.85), "花了大花")
equal(A, verdict("FFT制押", "FFT质押", 0.9), "FFT制押")
}
@@ -199,7 +192,6 @@ object FixTests {
equal(D, verdict("莫纳", "Morpho", 0.7), "莫纳")
}
- /// A learned "S平 → X平" never reaches into "iOS平台"; on its own it still applies.
fun learnedWordsStayWhole() {
equal(null, Correction.word("S平", "iOS平台很好"), "inside iOS")
equal(null, Correction.word("A工", "DATA工具"), "inside DATA")
@@ -209,7 +201,6 @@ object FixTests {
equal("iOS平台和X平台", Correction.apply(listOf(LineFix("S平", "X平")), "iOS平台和S平台").text, "apply")
}
- /// A translation isn't a misheard name: one 对 to "X平台 → X platform" taught 平台 → platform.
fun translationsAreNotAsked() {
equal(D, verdict("X平台", "X platform", 0.9), "X平台")
equal(D, verdict("平台", "platform", 0.95), "平台")
@@ -345,7 +336,6 @@ object FixTests {
equal("in" to "in now", Correction.label(LineFix("in", "in now", user = true)), "added at the end")
equal("Great" to "OK Great", Correction.label(LineFix("Great", "OK Great", user = true)), "added at the start")
equal("质压" to "质押", Correction.label(LineFix("解除质压", "解除质押")), "a swap names the changed words")
- // 改回 says the whole span too.
val t = setup("lock that in.")
t.fx.edit("l0", t.id, "lock that in now.", everywhere = false, keep = false)
t.fx.revert(t.line("l0").fixes!!.first(), "l0", t.id)
@@ -354,23 +344,18 @@ object FixTests {
fun addedWordStaysOnItsLineAndNeverMatchesPunctuation() {
val line = "Great, let's lock that in."
- // "now" added before the full stop: the fix is the last word, unique in the line, not ".".
val e = Correction.userEdit(line, "Great, let's lock that in now.", line, emptyList())!!
equal("in", e.fix.from, "from"); equal("in now", e.fix.to, "to"); equal(false, e.swap, "not a swap")
equal("Great, let's lock that in now.", Correction.apply(listOf(e.fix), line).text, "applied")
- // A word added at the start.
val s = Correction.userEdit(line, "OK Great, let's lock that in.", line, emptyList())!!
equal("Great", s.fix.from, "start from"); equal("OK Great", s.fix.to, "start to"); equal(false, s.swap, "start not a swap")
equal("OK Great, let's lock that in.", Correction.apply(listOf(s.fix), line).text, "start applied")
- // A word that appears twice: grown until the span is unique.
val r = "in the room in the hall"
val t = Correction.userEdit(r, "in the room inside the hall", r, emptyList())!!
equal("in the room inside the hall", Correction.apply(listOf(t.fix), r).text, "unique span")
- // Chinese: an inserted word takes its neighbour.
val c = Correction.userEdit("好的我来看一下", "好的OK我来看一下", "好的我来看一下", emptyList())!!
equal("好的OK我来看一下", Correction.apply(listOf(c.fix), "好的我来看一下").text, "Chinese applied")
equal(false, c.swap, "Chinese not a swap")
- // A real swap is still a swap.
equal(true, Correction.userEdit("我木娜找了", "我Monad找了", "我木娜找了", emptyList())?.swap, "swap")
}
@@ -509,8 +494,6 @@ object FixTests {
equal("但质压这种", t.line("l0").shown, "stays reverted")
}
- /// The sentence's translation request carries the word list and the lines before it, and the
- /// fixes in its reply reach the line (Translator → LiveFixes), with no JSON mode.
fun fixesRideOnTheSentenceTranslation() {
val t = setup("我们先看这个", "解释这个莫拉的,质压很高")
t.fx.vocabulary.importText("Morpho = 莫法")
@@ -529,9 +512,6 @@ object FixTests {
equal(1, t.fx.pending(t.id).size, "the name asked about")
}
- /// The path a real meeting takes: Ming hears and translates a stretch, then (fixing on) the text
- /// model translates the line again with the misheard words pointed out. Its translation replaces
- /// Ming's and its fixes reach the record; with fixing off, no second request.
fun aLineMingTranslatedIsFixed() {
usePinyinTable()
for (on in listOf(true, false)) {
@@ -560,7 +540,6 @@ object FixTests {
src.onEnded = { ended.countDown() }
engine.start(src, "file")
ended.await()
- // No wait: stop() itself waits for the line's fixing request.
engine.stop()
val l = store.get(engine.sessionId!!)!!.lines.single()
if (on) {
diff --git a/android/cli/src/main/kotlin/cicada/cli/FolderExportTests.kt b/android/cli/src/main/kotlin/cicada/cli/FolderExportTests.kt
index 75181dd..96b9376 100644
--- a/android/cli/src/main/kotlin/cicada/cli/FolderExportTests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/FolderExportTests.kt
@@ -1,5 +1,3 @@
-// 存到文件夹: the Mac's FolderExportTests. The file name and frontmatter are a contract with the Mac
-// and the other ports (Tests/fixtures/folder-export): the same record gives the same bytes.
package cicada.cli
import cicada.*
@@ -55,7 +53,6 @@ object FolderExportTests {
}
}
- /// The name: the user's title, else the notes', else the imported file's, never the display title.
private fun namePrecedence() {
val s = session()
s.renamed = false
@@ -79,8 +76,6 @@ object FolderExportTests {
check(FolderExportIndex.load(File(Paths.root, "none.json")).folder.isEmpty(), "no index: an empty one")
}
- /// Settled means the final notes pass is over: it counts as running from the meeting's start
- /// until finish() is done, and says so when it ends without a key.
private fun waitsForTheFinalNotes() {
val store = SessionStore(loadNow = false)
val ling = LingClient(AIKey(PlainProtector, File(Paths.root, "no-key")))
diff --git a/android/cli/src/main/kotlin/cicada/cli/Main.kt b/android/cli/src/main/kotlin/cicada/cli/Main.kt
index b08aafe..6208b98 100644
--- a/android/cli/src/main/kotlin/cicada/cli/Main.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/Main.kt
@@ -1,22 +1,3 @@
-// cicada-cli: the Android engines without Android (scripts/cli.sh runs it).
-//
-// cicada-cli test the unit tests (no network)
-// cicada-cli listen <file.wav> [--target zh-CN] [--speed 1|0] [--notes] [--log] [--room]
-// Plays the file into ListenEngine as if the phone were playing it, prints each line as it
-// is recorded, then the record's folder. --notes waits for the final notes and prints them.
-// cicada-cli hear <file.wav> [--target zh-CN] one file to the hear model (Ming on Ling), raw reply printed
-// cicada-cli say <file.wav> [--to en] [--out said.wav]
-// 我说 · 面对面: what I say heard and translated, then read by the service's voice into a WAV
-// cicada-cli speak <text> [--voice US_Emma] [--lang ja] [--out speak.wav] one line in the service's voice
-// --reference <wav> [--own zh-CN]: in the voice of that recording (我自己的声音), checked first
-// cicada-cli segments <file.wav> [--room] where the segmenter cuts (--room: 面对面's gate)
-// cicada-cli roundtrip <session.json>… reads and writes records, says if a byte changed
-//
-// --provider ling|openrouter|zenmux the AI service (default ling), with its recommended models;
-// --hear-model <id> another hear model on it
-//
-// Records go to CICADA_HOME (default: a temp folder). The key comes from CICADA_KEY_FILE, else the
-// Mac app's dev or release key file for the service; it is never printed.
package cicada.cli
import cicada.*
@@ -38,7 +19,6 @@ fun loadStrings(ui: String) = Strings.load(ui) { rel ->
fun macKeyFile(service: String = "ling"): File? = System.getenv("CICADA_KEY_FILE")?.let(::File)
?: listOf("LiveSubs Dev", "LiveSubs").map { File(System.getProperty("user.home"), "Library/Application Support/$it/" + Paths.keyFile(service).name) }.firstOrNull { it.isFile }
-/// The AI service the settings name, with the Mac's key file for it.
fun client(settings: AppSettings) = LingClient(AIKey(PlainProtector, macKeyFile(settings.aiProvider)), config = settings::aiConfig)
fun main(argv: Array<String>) {
@@ -113,17 +93,14 @@ fun main(argv: Array<String>) {
exitProcess(0)
}
"speak" -> {
- // speak <text> [--voice US_Emma] [--lang ja] [--out speak.wav]: one line in a service voice.
Log.echo = args.contains("--log")
val ling = client(settings())
val voice = opt("--voice", "").ifEmpty { null }
val lang = opt("--lang", "").ifEmpty { null }
- // --reference <wav> [--own zh-CN]: the user's own voice, the recording checked as 录制 checks it.
val reference = opt("--reference", "").ifEmpty { null }?.let { path ->
val pcm = Wav.read(File(path).inputStream())
when (val r = VoiceReference.check(Translator(ling), pcm, opt("--own", "zh-CN"))) {
is VoiceReference.Check.Ok -> {
- // What 用这个声音 keeps: the trimmed clip, written and read back as the app does.
println("reference: %.1f s recorded, %.1f s kept, heard %d characters".format(pcm.size / 16000.0, r.pcm.size / 16000.0, r.text.length))
VoiceReference.save(r.pcm, r.text)
VoiceReference.reference()!!
diff --git a/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt b/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
index e878252..fa5e354 100644
--- a/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/ProviderTests.kt
@@ -1,5 +1,3 @@
-// AI 服务: the services other than Ling (Providers.kt), the same cases as the Linux port's
-// tests/test_providers.py. No network: LingClient runs against a fake transport.
package cicada.cli
import cicada.*
@@ -54,13 +52,11 @@ object ProviderTests {
private fun check(ok: Boolean, what: String) { if (!ok) throw AssertionError(what) }
private fun <T> equal(expected: T, actual: T, what: String) { if (expected != actual) throw AssertionError("$what: expected «$expected», got «$actual»") }
- /// Answers by URL and body; records what was sent and streamed.
private class Fake(
val respond: (String, String) -> Transport.Response,
val streams: ((String, String) -> Transport.Stream)? = null,
) : Transport {
val sent = mutableListOf<Pair<String, String>>()
- /// The Authorization header of each request in `sent`.
val auths = mutableListOf<String?>()
val streamed = mutableListOf<Pair<String, String>>()
override fun send(url: String, method: String, body: String?, headers: Map<String, String>, timeoutMs: Int): Transport.Response {
@@ -94,7 +90,6 @@ object ProviderTests {
equal("google/gemini-3.8-flash-tts", c.voiceModel, "voice")
val ling = AppSettings().aiConfig()
equal("Ming-3.0-audio-flash" to "Ling-3.1-flash", ling.hearModel to ling.textModel, "Ling")
- // Ling keeps its own key ("model"); a service never named falls back to Ling.
equal("Ling-3.0-flash", AppSettings(model = "Ling-3.0-flash").aiConfig().textModel, "Ling's model")
equal("ling", Providers.named("openai").id, "no OpenAI")
}
@@ -131,7 +126,6 @@ object ProviderTests {
equal("http://192.168.1.20:8000/v1/", Providers.customBase("192.168.1.20:8000/v1"), "http added for a nearby host")
equal("https://10.0.0.5.evil.com/v1/", Providers.customBase("10.0.0.5.evil.com/v1"), "https added for a lookalike")
check(Providers.isNearby("http://192.168.1.20:8000/v1/") && !Providers.isLocal("http://192.168.1.20:8000/v1/"), "nearby, not local")
- // A service on the local network needs no key either.
val s = AppSettings(aiProvider = "custom", aiCustomBase = "192.168.1.20:8000/v1", aiModels = mutableMapOf("custom" to "qwen3:14b"))
equal("", client(Fake({ _, _ -> reply("ok") }), s, key = null).currentKey(), "no key on the LAN")
}
@@ -156,7 +150,6 @@ object ProviderTests {
mapOf("choices" to listOf(mapOf("message" to message))) + (usage?.let { mapOf("usage" to it) } ?: emptyMap())
check(!AIConfig.thought(r(mapOf("content" to "周五发布。"))), "a plain answer")
check(AIConfig.thought(r(mapOf("content" to "周五发布。", "reasoning_content" to "The user wants…"))), "reasoning_content")
- // A reasoning parser on the server: the answer itself sits in reasoning_content.
check(AIConfig.thought(r(mapOf("content" to "", "reasoning_content" to "周五发布。"))), "answer in reasoning_content")
check(AIConfig.thought(r(mapOf("content" to "周五发布。", "reasoning" to "hmm"))), "reasoning (OpenRouter's name)")
check(AIConfig.thought(r(mapOf("content" to "<think>hmm</think>周五发布。"))), "<think>")
@@ -191,7 +184,6 @@ object ProviderTests {
ling.keyChanged()
ling.chat("c", "i", Priority.Translate)
check("chat_template_kwargs" in fake.sent[3].second, "back after settings change")
- // A second refusal is about something else: the field isn't given up.
val deaf = Fake({ _, _ -> Transport.Response(400, "{}") })
val other = client(deaf, s, key = null)
try { other.chat("c", "i", Priority.Translate); throw AssertionError("accepted") } catch (e: LingException) { equal(400, e.status, "the refusal") }
@@ -201,8 +193,6 @@ object ProviderTests {
}
fun jsonModeRefused() {
- // No JSON mode on this server (OpenRouter's Novita for Ling 3.1 Flash): 400 with or without
- // the kwargs. Asked again without JSON mode.
val s = AppSettings(aiProvider = "custom", aiCustomBase = "http://192.168.1.20:8000/v1", aiModels = mutableMapOf("custom" to "m"))
val fake = Fake({ _, b -> if ("response_format" in b) Transport.Response(400, "{}") else reply("好") })
val ling = client(fake, s, key = null)
@@ -221,7 +211,6 @@ object ProviderTests {
val ling = client(fake, s, key = null)
ling.check()
check(ling.aiCheck.failure == null, "passes: ${ling.aiCheck.summary}")
- // One that can't answer JSON at all still fails.
val plain = Fake({ url, b -> if (url.endsWith("models")) Transport.Response(404, "") else if ("response_format" in b) Transport.Response(400, "{}") else reply("ok") })
val other = client(plain, s, key = null)
other.check()
@@ -250,7 +239,6 @@ object ProviderTests {
val t = ling.aiCheck.translate
check(t != null && t.thinks, "thinking found: ${ling.aiCheck.summary}")
check(ling.aiCheck.slow && ling.aiCheck.failure == null, "works, but slow")
- // All 120 tokens spent thinking, no answer: still a thinking model, not a silent pass.
val noAnswer = Transport.Response(200, Json.write(mapOf("choices" to listOf(mapOf(
"message" to mapOf("content" to null, "reasoning" to "Okay, the user wants…"), "finish_reason" to "length"))), pretty = false))
val spent = client(Fake({ url, b -> if (url.endsWith("models")) Transport.Response(404, "") else if ("Translate the text" in b) noAnswer else reply("{\"ok\": true}") }), s, key = null)
@@ -301,7 +289,6 @@ object ProviderTests {
equal(AICheck.StepID.Hear to AICheck.Reason.Unreachable, f?.step to f?.reason, "the hear step: ${ling.aiCheck.summary}")
check(ling.checkMessage()!!.contains("192.168.1.21"), "names the hear server: ${ling.checkMessage()}")
equal(null, ling.aiCheck.proxy, "no proxy hint for a server on the local network")
- // A bad hear address stops at hearing, not at the text model's.
s.aiCustomHearBase = "http://hear.example.com/v1"
ling.keyChanged()
ling.check()
@@ -340,7 +327,6 @@ object ProviderTests {
t.googleOff = true
for (i in 0 until 3) equal(null, t.translate("We ship on Friday", "en", "zh-CN", Translator.Kind.Draft), "draft $i shows the original")
equal(0, fake.sent.size, "partial text goes nowhere: not Google, never the AI service")
- // Off, partial text still never reaches the AI service: only Google.
t.googleOff = false
equal("我们周五发布", t.translate("We ship on Friday", "en", "zh-CN", Translator.Kind.Draft), "draft via Google when off")
check(fake.sent.all { google(it.first) }, "a draft never goes to the AI service")
@@ -357,7 +343,6 @@ object ProviderTests {
equal(null, t.translate("We ship on Friday", "en", "zh-CN", Translator.Kind.Sentence), "service down: the original only")
check(t.sentencesUntranslated, "says the sentence went untranslated")
check(fake.sent.none { google(it.first) }, "Google is never asked")
- // Off again, Google stands in as before.
t.googleOff = false
check(!t.sentencesUntranslated, "flipping forgets the last sentence")
equal("我们周五发布", t.translate("We ship on Friday", "en", "zh-CN", Translator.Kind.Sentence), "Google stands in when off")
@@ -444,7 +429,6 @@ object ProviderTests {
fun requestShape() {
val fake = Fake({ _, _ -> reply("LANG: en\nORIGINAL: Hi.\nTRANSLATION: 嗨。", finish = null) })
val ling = client(fake, AppSettings(aiProvider = "zenmux"))
- // No finish reason: Ling's search essays come without one, other services may just omit it.
val r = ling.chat("c", "i", Priority.Translate, model = "qwen/qwen3.8-omni-flash", audio = byteArrayOf(1))
check(r.contains("ORIGINAL: Hi."), "accepted without a finish reason")
equal("https://zenmux.ai/api/v1/chat/completions", fake.sent[0].first, "url")
@@ -452,7 +436,6 @@ object ProviderTests {
equal(mapOf("enabled" to false), b["reasoning"], "reasoning off")
check("thinking" !in b, "no Ling field")
equal("input_audio", b["messages"].arr()[1].obj()!!["content"].arr()[0].obj()!!["type"], "input_audio")
- // Text calls use the service's text model.
ling.chat("c", "i", Priority.Translate)
equal("inclusionai/ling-3.0-flash", body(fake.sent[1].second)["model"], "text model")
}
@@ -509,17 +492,14 @@ object ProviderTests {
equal("https://zenmux.ai/api/v1/audio/speech", fake.streamed[0].first, "url")
equal(Triple("google/gemini-3.8-flash-tts", "Puck", true), Triple(b["model"], b["voice"], b["stream"]), "body")
check("language_id" !in b, "language_id is Ling's")
- // A voice that isn't this service's (a Ming name) becomes its first one.
ling.speech("Hello", voice = "US_Emma") {}
equal("Kore", body(fake.streamed[1].second)["voice"], "first voice")
- // OpenRouter streams the PCM bytes themselves, without `stream`.
val raw = Fake({ _, _ -> reply("ok") }, { _, _ -> Transport.Stream(200, "audio/pcm", ByteArrayInputStream(byteArrayOf(5, 0, 6, 0))) })
ling = client(raw, AppSettings(aiProvider = "openrouter"))
val pcm = java.io.ByteArrayOutputStream()
ling.speech("Hi") { pcm.write(it) }
equal(listOf<Byte>(5, 0, 6, 0), pcm.toByteArray().toList(), "raw PCM")
check("stream" !in body(raw.streamed[0].second), "no stream for OpenRouter")
- // One JSON with a WAV in it.
val wav = Wav.bytes(shortArrayOf(7, 8), 24000)
val one = Fake({ _, _ -> reply("ok") }, { _, _ ->
Transport.Stream(200, "application/json", ByteArrayInputStream(Json.write(mapOf("audio" to b64.encodeToString(wav))).toByteArray())) })
@@ -550,7 +530,6 @@ object ProviderTests {
check(ListenEngine.problem(LingException(LingException.Kind.Network), "ZenMux").second!!.contains("ZenMux"), "named")
equal("network" to "字幕和纪要等 Ling 恢复 · 连上后自动继续", ListenEngine.problem(LingException(LingException.Kind.Timeout), "Ling"), "what waits and that it goes on")
equal(null, ListenEngine.problem(LingException(LingException.Kind.Http, 400), "Ling").first, "Ling's 400 is not the model")
- // A gateway's 502 in front of the server: the service erring, not the network or the key.
equal("busy" to "ZenMux 暂时出错(HTTP 502),稍后再试。", ListenEngine.problem(LingException(LingException.Kind.Http, 502), "ZenMux"), "a 5xx is the service's trouble")
equal("busy" to "Ling 暂时出错(HTTP 503),稍后再试。", ListenEngine.problem(LingException(LingException.Kind.Http, 503), "Ling"), "Ling's too")
}
@@ -573,7 +552,6 @@ object ProviderTests {
private val notesKeys = AIKey(PlainProtector, service = { LingClient.NOTES_KEY })
- /// A custom service at main.example translating with "mt"; notes on "big", at notes.example with `own`.
private fun notesSettings(own: Boolean) = AppSettings(aiProvider = "custom", aiCustomBase = "https://main.example/v1",
aiModels = mutableMapOf("custom" to "mt", Providers.NOTES_MODEL to "big"), aiCustomNotesOwn = own,
aiCustomNotesBase = if (own) "https://notes.example/v1" else "")
@@ -602,7 +580,6 @@ object ProviderTests {
ling.chat("x", "Notes.", Priority.Notes)
equal("https://notes.example/v1/chat/completions", fake.sent[0].first, "their server")
equal("Bearer sk-main-1111111111", fake.auths[0], "no key of their own: the translation key")
- // The same service, another model: same address and key, even with a notes key file left over.
notesKeys.save("sk-notes-222222222")
val same = Fake({ _, _ -> reply("{}") })
val other = client(same, notesSettings(own = false), key = "sk-main-1111111111")
@@ -610,7 +587,6 @@ object ProviderTests {
equal("https://main.example/v1/chat/completions", same.sent[0].first, "translation's server")
equal("Bearer sk-main-1111111111", same.auths[0], "translation's key")
equal("big", model(same.sent[0].second), "notes' model")
- // Removing it brings the translation key back.
val own = client(Fake({ _, _ -> reply("{}") }), notesSettings(own = true), key = "sk-main-1111111111")
check(own.notesHasOwnKey, "has its own")
own.removeNotesKey()
@@ -630,7 +606,6 @@ object ProviderTests {
equal(null, ling.aiCheck.failure, "translation's steps untouched")
check(ling.aiCheck.notesFailed, "notes failed")
check(ling.aiCheck.notesLine("notes.example", "big", sharedKey = true)!!.contains("notes.example"), "names the notes server")
- // Refused once: the next notes ask isn't sent.
val n = fake.sent.size
try { ling.chat("x", "Notes.", Priority.Notes) } catch (_: LingException) {}
equal(n, fake.sent.size, "not sent again until settings change")
@@ -648,13 +623,11 @@ object ProviderTests {
val sameName = AppSettings(aiProvider = "custom", aiCustomBase = "https://main.example/v1",
aiModels = mutableMapOf("custom" to "mt", Providers.NOTES_MODEL to "mt")).aiConfig()
check(!sameName.notesApart, "the translation model named again is no split")
- // 同一个服务 keeps the typed address, unused.
val off = notesSettings(own = true).apply { aiCustomNotesOwn = false }.aiConfig()
equal("https://main.example/v1/", off.forNotes.base, "off: translation's address")
equal(null, off.notesBase, "off: not used")
val on = notesSettings(own = true).aiConfig()
equal("https://notes.example/v1/", on.forNotes.base, "on: their own")
- // Only the custom service splits.
val ling = AppSettings(aiProvider = "ling", aiModels = mutableMapOf(Providers.NOTES_MODEL to "big")).aiConfig()
check(!ling.notesApart && ling.forNotes.textModel == ling.textModel, "Ling never splits")
try {
@@ -679,7 +652,6 @@ object ProviderTests {
fun notesCheck() {
try {
- // Notes' server takes no JSON and answers none: their row fails, translation passes.
val fake = Fake({ url, b ->
when {
url.endsWith("models") -> if ("notes.example" in url) Transport.Response(200, """{"data":[{"id":"big"},{"id":"bigger"}]}""")
@@ -699,12 +671,10 @@ object ProviderTests {
equal(KeyState.Ok, ling.keyState, "the key works")
equal(listOf("big", "bigger"), ling.notesCatalog, "notes' own list for their menu")
check(fake.sent.none { "notes.example" in it.first && it.second.contains("Translate the text") }, "the sentence went to translation only")
- // Fixed: notes pass.
val good = Fake({ url, _ -> if (url.endsWith("models")) Transport.Response(404, "") else reply("{\"ok\": true}") })
val ok = client(good, s, key = "sk-main-1111111111")
ok.check()
check(ok.aiCheck.notes is AICheck.Notes.Ok && !ok.aiCheck.notesFailed, "notes ok: ${ok.aiCheck.summary}")
- // Notes on the same service: no row of their own; the JSON check is translation's.
val same = client(Fake({ url, _ -> if (url.endsWith("models")) Transport.Response(404, "") else reply("{\"ok\": true}") }),
AppSettings(aiProvider = "custom", aiCustomBase = "https://main.example/v1", aiModels = mutableMapOf("custom" to "mt"),
aiHearModels = mutableMapOf("custom" to "omni")), key = "sk-main-1111111111")
@@ -713,7 +683,6 @@ object ProviderTests {
} finally { notesKeys.remove() }
}
- /// The start gate's time, moved on by each wait instead of waiting.
private class StepClock : GateClock() {
var t = 1_000_000L
override fun now() = t
@@ -721,17 +690,14 @@ object ProviderTests {
}
fun gatePerServer() {
- // Notes' server is out of requests: its 429s pause it, not translation's server.
val fake = Fake({ url, _ -> if ("notes.example" in url) Transport.Response(429, "", "20") else reply("好") })
val s = notesSettings(own = true)
val k = AIKey(PlainProtector, service = { s.aiProvider }).apply { save("sk-main-1111111111") }
val ling = LingClient(k, fake, config = s::aiConfig, clock = StepClock())
try { ling.chat("x", "Notes.", Priority.Notes); throw AssertionError("answered") }
catch (e: LingException) { equal(LingException.Kind.RateLimited, e.kind, "notes gave up") }
- // A translation fails at once while its own server is cooling down; this one isn't.
equal("好", ling.chat("y", "Translate.", Priority.Translate), "translation starts at once")
check(ling.keyState != KeyState.Invalid, "key fine")
- // chat_template_kwargs refused by the notes' server only: translation keeps sending it.
val kw = Fake({ url, b -> if ("notes.example" in url && "chat_template_kwargs" in b) Transport.Response(422, "{}") else reply("{}") })
val two = client(kw, s, key = "sk-main-1111111111")
two.chat("x", "Notes.", Priority.Notes)
diff --git a/android/cli/src/main/kotlin/cicada/cli/SearchTests.kt b/android/cli/src/main/kotlin/cicada/cli/SearchTests.kt
index 722b731..9d92dd9 100644
--- a/android/cli/src/main/kotlin/cicada/cli/SearchTests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/SearchTests.kt
@@ -1,4 +1,3 @@
-// 会议记录's search: the Mac's TranscriptSearchTests, plus where the marks go.
package cicada.cli
import cicada.*
@@ -16,7 +15,6 @@ object SearchTests {
private fun aNameAlsoFindsHowItWasMisheard() {
val notes = listOf(NoteTerm("江充", "", mutableListOf("江松")), NoteTerm("Ling", "", mutableListOf()))
equal(listOf("江充", "江松"), TranscriptSearch.terms("江充", notes), "name")
- // Searching the misheard form finds the right one too; an unrelated term stays out.
equal(listOf("江松", "江充"), TranscriptSearch.terms(" 江松 ", notes), "misheard")
equal(emptyList<String>(), TranscriptSearch.terms(" ", notes), "blank")
equal(listOf("ling", "Ling"), TranscriptSearch.terms("ling", notes), "case")
@@ -33,7 +31,6 @@ object SearchTests {
private fun everyOccurrenceIsMarked() {
val text = "Budget, budget, done"
equal(listOf("Budget", "budget"), TranscriptSearch.ranges(text, listOf("budget")).map { text.substring(it) }, "marks")
- // Terms that overlap mark the text once.
equal(listOf(0..5, 8..13), TranscriptSearch.ranges(text, listOf("budget", "udge")), "overlap")
equal(emptyList<IntRange>(), TranscriptSearch.ranges(text, listOf("")), "empty term")
}
diff --git a/android/cli/src/main/kotlin/cicada/cli/ShareTests.kt b/android/cli/src/main/kotlin/cicada/cli/ShareTests.kt
index b6bb422..f4e8356 100644
--- a/android/cli/src/main/kotlin/cicada/cli/ShareTests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/ShareTests.kt
@@ -1,6 +1,3 @@
-// 分享…: the Mac's ShareTests (the share document is a contract with the server and the other
-// apps: the same record gives the same bytes, Tests/fixtures/share), plus the crypto Android does
-// itself (Ed25519, PBKDF2) and the client's requests against a fake server.
package cicada.cli
import cicada.*
@@ -25,7 +22,6 @@ object ShareTests {
"shareMessageInTheUiLanguage" to ::message,
)
- /// 生成并复制's clipboard: title, link, password with how long it stays open (the Mac's clipboardText).
private fun message() {
val now = java.time.Instant.parse("2026-11-08T10:00:00Z")
fun record(days: Long, pw: String?) =
@@ -83,7 +79,6 @@ object ShareTests {
private fun speakerNumbersWithoutNames() {
setUp()
val s = session()
- // Two voices with five substantive lines each get numbers; their names stay out.
s.lines = (0 until 10).map { i ->
TranscriptLine(id = "v$i", t = i.toDouble(), speaker = "them", src = "this is line number $i", dst = "第 $i 句话", srcLang = "en", dstLang = "zh", voice = if (i % 2 == 0) 3 else 7)
}.toMutableList()
@@ -106,7 +101,6 @@ object ShareTests {
private fun password() {
val salt = ByteArray(16) { 1 }
- // Same as the browser's crypto.subtle PBKDF2-SHA256, 32 bytes (server/test/api.test.mjs).
val v = SharePassword.verifier("ruby-41-lake", salt, 1000)
equal("eab69fcd00a0517794c156495dd76ad1fbfb036ea03df3d59a68a33519009c81", hex(v), "PBKDF2 vector")
check(!v.contentEquals(SharePassword.verifier("ruby-41-laka", salt, 1000)), "another password differs")
@@ -114,13 +108,11 @@ object ShareTests {
}
private fun blockedHitsMapBack() {
- // The server counts lines of what was sent; the app maps them back to the record.
val hits = listOf(ShareHit("lines", 2, 3, listOf("credential")))
equal(setOf(4, 5), ShareHit.recordLines(hits, listOf(0, 1, 4, 5, 6)), "record lines")
}
private fun ed25519Vectors() {
- // RFC 8032 §7.1, tests 1–3 and the 1023-byte message's key.
val cases = listOf(
Triple("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", "",
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"),
@@ -139,7 +131,6 @@ object ShareTests {
}
private fun ed25519Jdk() {
- // The JDK has Ed25519 (Android only from 13): it must accept ours for random keys and messages.
val random = java.util.Random(7)
repeat(8) { n ->
val seed = ByteArray(32).also(random::nextBytes)
@@ -149,7 +140,6 @@ object ShareTests {
v.initVerify(KeyFactory.getInstance("Ed25519").generatePublic(spec))
v.update(msg)
check(v.verify(Ed25519.sign(seed, msg)), "JDK verifies signature $n")
- // Ed25519 is deterministic: the JDK's own signature is the same bytes.
val s = Signature.getInstance("Ed25519")
s.initSign(KeyFactory.getInstance("Ed25519").generatePrivate(java.security.spec.PKCS8EncodedKeySpec(bytes("302e020100300506032b657004220420") + seed)))
s.update(msg)
@@ -157,7 +147,6 @@ object ShareTests {
}
}
- /// A fake server that checks what auth.js checks: the proof of work, then each signature.
private fun clientSigns() {
setUp()
val home = File(Paths.root, "share-test").apply { deleteRecursively(); mkdirs() }
@@ -207,7 +196,7 @@ object ShareTests {
equal("ruby-41-lake", ShareStore.read(s.id)?.password, "record kept, with its password")
equal(3, client.stats(listOf(shared.record.id))[shared.record.id]?.views, "stats")
equal(1, registrations, "registered once")
- forget = true // the server lost this phone: registers again, once
+ forget = true
check(client.revoke(shared.record, s.id), "revoked")
equal(2, registrations, "registered again after unknown_device")
equal(null, ShareStore.read(s.id), "record forgotten")
diff --git a/android/cli/src/main/kotlin/cicada/cli/Tests.kt b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
index 0f1b295..63d75e3 100644
--- a/android/cli/src/main/kotlin/cicada/cli/Tests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
@@ -1,6 +1,3 @@
-// Unit tests for the engines: `scripts/test.sh` (cicada-cli test). The Windows suite's cases, plus
-// byte-for-byte checks of the Mac's JSON format. A failed check throws and the runner reports it.
-// No network: LingClient runs against a fake transport.
package cicada.cli
import cicada.*
@@ -200,7 +197,6 @@ object Tests {
equal(MAC, Json.write(s.toJson()), "written back byte for byte")
}
- /// A Mac record of an imported file heard partly in the room: Android writes it back whole.
fun keepsTheMacsImportAndRoomFields() {
val mac = MAC.replace(" \"id\" : \"20261102-101639\",\n", " \"id\" : \"20261102-101639\",\n \"importing\" : true,\n")
.replace(" \"startedAt\"", " \"room\" : true,\n \"sourceFile\" : \"周会.m4a\",\n \"sourcePath\" : \"\\/Users\\/me\\/周会.m4a\",\n \"startedAt\"")
@@ -214,11 +210,8 @@ object Tests {
equal("周会", SessionStore.displayTitle(untitled), "an imported file is known by its name until the notes name it")
}
- /// The Mac's voiceprint library (1.10) adds voiceProfiles / voiceSuggestions; Android has no
- /// such library but must not drop them when it saves the record again.
fun keepsFieldsItDoesNotKnow() {
val ref = "{\n \"1\" : {\n \"id\" : \"6F9619FF-8B86-D011-B42D-00C04FC964FF\",\n \"name\" : \"Emma\",\n \"similarity\" : 0.75\n }\n }"
- // Sorted keys: both come after voiceNames, the last key of MAC.
val mac = MAC.removeSuffix("\n}") + ",\n \"voiceProfiles\" : $ref,\n \"voiceSuggestions\" : $ref\n}"
check(mac.contains("\"voiceProfiles\"") && mac.contains("\"voiceSuggestions\""), "test record has the fields")
val s = Session.read(mac)!!
@@ -258,7 +251,6 @@ object Tests {
check(store.get(empty.id) == null, "an empty live meeting is still dropped when it ends")
}
- /// The Mac's LanguagesTests for followSystemTarget / myLanguage.
fun followSystemLikeTheMac() {
equal("zh-CN", Languages.myLanguage(listOf("en-US", "zh-Hans-CN")), "Chinese when the list has it")
equal("ja", Languages.myLanguage(listOf("ja-JP", "en-US")), "else the first")
@@ -311,8 +303,6 @@ object Tests {
check(md.contains("**[00:00] 对方** \nhi\n"), "markdown export")
}
- /// Markdown, SRT and Word as the Mac writes them; speaker numbers only once two voices
- /// have said enough, and a name the user gives shows in them.
fun exportsLikeTheMac() {
val them = (1..5).flatMap { i ->
listOf(TranscriptLine(id = "a$i", t = i * 10.0, speaker = "them", src = "we should ship it now", dst = "我们现在就该发布", voice = 1),
@@ -386,7 +376,6 @@ object Tests {
equal("ja", Translator.parseHeard("lang: ja-JP\noriginal: はい\ntranslation: 是", "zh-CN", null)!!.lang, "labels in any case")
}
- // Same cases as the Windows and Linux ports' noise tests.
fun dropsNoise() {
for (o in listOf("嗯。", "Mm.", "uh, um", "呃呃呃呃呃", "嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯,嗯。", "滴答".repeat(50),
"hmmmm", "うーん", "음…", "喂?", "No no no no no no",
@@ -441,14 +430,11 @@ object Tests {
// MARK: Segmenter
- /// A 300 Hz tone that swells and fades four times a second like syllables; steady when not, or
- /// rising and falling by `wobble` twice a second like a fan.
fun tone(seconds: Double, amp: Double = 0.3, syllables: Boolean = true, wobble: Double = 0.0) = ShortArray((seconds * 16000).toInt()) {
val env = if (syllables) 0.55 + 0.45 * sin(2 * PI * 4 * it / 16000) else 1.0 + wobble * sin(2 * PI * 0.5 * it / 16000)
(sin(2 * PI * 300 * it / 16000) * env * amp * 32767).toInt().toShort()
}
fun silence(seconds: Double) = ShortArray((seconds * 16000).toInt())
- /// Typing: a key click every 0.2 s, 6 ms of decaying crackle peaking near -12 dBFS (scripts/vad-clips.py).
private fun keys(seconds: Double) = silence(seconds).also { out ->
var at = 1600
while (at < out.size - 96) {
@@ -456,16 +442,13 @@ object Tests {
at += 3200
}
}
- /// A sine at `freq` that swells and fades four times a second like syllables.
private fun hz(freq: Double, seconds: Double, amp: Double) = ShortArray((seconds * 16000).toInt()) {
(sin(2 * PI * freq * it / 16000) * (0.55 + 0.45 * sin(2 * PI * 4 * it / 16000)) * amp * 32767).toInt().toShort()
}
- /// One word on its own ("Thanks."): a 300 Hz tone that swells from nothing and fades back.
private fun word(seconds: Double, amp: Double): ShortArray {
val n = (seconds * 16000).toInt()
return ShortArray(n) { (sin(2 * PI * 300 * it / 16000) * Math.pow(sin(PI * it / n), 2.0) * amp * 32767).toInt().toShort() }
}
- /// A 7 kHz tone faded in and out over 0.3 s: crosses zero like a hiss, swells like a word.
private fun hiss(seconds: Double, amp: Double): ShortArray {
val n = (seconds * 16000).toInt()
return ShortArray(n) { (sin(2 * PI * 7000 * it / 16000) * minOf(1.0, it / 4800.0, (n - it) / 4800.0) * amp * 32767).toInt().toShort() }
@@ -491,8 +474,6 @@ object Tests {
}
fun cutsLongSpeech() {
- // After a first short stretch: 7 s of speech, a 0.3 s dip (shorter than a pause), 4 s
- // more: one cut, at the dip.
val list = cut(tone(1.0), silence(1.0), tone(7.0), tone(0.3, 0.004), tone(4.0), silence(1.0))
equal(3, list.size, "the first, then the long one split in two")
check(list[1].seconds in 6.9..7.4, "cut inside the dip, got ${list[1].seconds}")
@@ -507,15 +488,12 @@ object Tests {
equal(0, cut(silence(0.5), keys(3.0), silence(1.0)).size, "typing alone makes no segment")
}
- /// A room's hiss, about -60 dBFS.
private fun room(seconds: Double, seed: Long = 7): ShortArray {
val r = java.util.Random(seed)
return ShortArray((seconds * 16000).toInt()) { (r.nextGaussian() * 0.001 * 32767).toInt().toShort() }
}
private fun mix(a: ShortArray, b: ShortArray) = ShortArray(a.size) { (a[it] + b[it]).coerceIn(-32768, 32767).toShort() }
- /// 面对面 (#30): a phone's mic hears a voice across the table around -50 dBFS, under the fixed
- /// -40 dBFS line, so the meeting showed 等有人说话… for 8 minutes. The room's gate hears it.
fun roomGateHearsAcrossTheTable() {
val gate = VoiceGate()
equal(0.004, gate.threshold, "before the room is known")
@@ -541,8 +519,6 @@ object Tests {
equal(1, cut(silence(1.0), word(1.2, 0.022), silence(1.0)).size, "one smooth run of voice on its own, no dips inside")
equal(1, cut(silence(1.0), tone(0.5, 0.022, syllables = false), tone(0.15, 0.0025, syllables = false), silence(1.0)).size,
"a quiet word whose fade (an \"s\", a breath) falls under gate / 4 still swells: a meeting's quiet opening line")
- // Wherever the 30 ms frames fall (a few ms more lead-in), a quiet phrase with brief dips between
- // its words stays a word, and a hum or a faded hiss in silence stays out.
fun flat(s: Double, a: Double) = tone(s, a, syllables = false)
val phrase = concat(flat(0.35, 0.022), flat(0.04, 0.0055), flat(0.4, 0.022), flat(0.04, 0.0055), flat(0.35, 0.022), flat(0.06, 0.0025))
for (ms in 0 until 30 step 2) {
@@ -565,8 +541,6 @@ object Tests {
// MARK: Notes
- /// A heard form only a fix wrote ("platform" for 平台) isn't one: it would teach the translator
- /// and the next fix the same mistake.
fun termsKeepOnlyFormsTheRecognizerWrote() {
val l = TranscriptLine("a", 0.0, "them", "我们 twoty 平台", null, "zh-CN", "en", fixes = mutableListOf(LineFix("平台", "platform")))
val terms = listOf(NoteTerm("X平台", "n", mutableListOf("Xplatform", "platform", "Twoty")))
@@ -630,10 +604,8 @@ object Tests {
fun keepsFrozenTopicsAndTakesTheRepliesTail() {
val old = (0 until 5).map { topic(it * 100.0, "t$it") }
- // The model echoed everything, renamed the current topic and added one.
val reply = listOf(topic(0.0, "t0"), topic(100.0, "t1 改"), topic(300.0, "t3"), topic(400.0, "t4 改"), topic(500.0, "t5"))
equal("t0,t1,t2,t3,t4 改,t5", NotesEngine.merge(old, 3, reply).joinToString(",") { it.title }, "frozen kept, the reply's tail after them")
- // The first update over many lines: nothing to echo, so every topic is the model's own.
val five = (0 until 5).map { topic(it * 100.0, "t$it") }
equal("t0,t1,t2,t3,t4", NotesEngine.merge(emptyList(), 0, five).joinToString(",") { it.title }, "nothing frozen")
equal("t0,t1,t2,t3,t4", NotesEngine.merge(listOf(topic(0.0, "t0")), 0, five).joinToString(",") { it.title }, "nothing frozen keeps every topic")
@@ -643,7 +615,6 @@ object Tests {
val terms = { names: String -> names.split(",").map { NoteTerm(it) } }
equal("A,B,C,D", NoteTerm.keepingOrder(terms("A,B,C"), terms("C,D,A,B")).joinToString(",") { it.name }, "terms keep their place, new ones after")
equal("B,E,D", NoteTerm.keepingOrder(terms("A,B,C"), terms("E,B,D")).joinToString(",") { it.name }, "dropped terms leave, new ones keep the reply's order")
- // A runaway summary is cut to its first sentence.
val runaway = topic(0.0, "t0").apply { summary = "对方展示AI眼镜后觉得是完全新的体验,提议可以出发回去。" + "最新对方又补充了一些内容,".repeat(20) }
equal("对方展示AI眼镜后觉得是完全新的体验,提议可以出发回去。", NotesEngine.merge(emptyList(), 0, listOf(runaway))[0].summary, "a runaway summary")
equal(NotesEngine.TOPIC_SUMMARY_LIMIT + 1, NotesEngine.shortened("长".repeat(200)).length, "or cut to the limit")
@@ -651,8 +622,6 @@ object Tests {
}
fun fullLiveNotesJoinTheShortestSettledPair() {
- // Twelve topics, t3 and t4 the shortest neighbours (t3 to t5 is 100 s): a new topic
- // still starts, and those two become one.
val starts = listOf(0, 100, 200, 300, 330, 400, 600, 700, 800, 900, 1000, 1100)
val old = starts.mapIndexed { i, s -> topic(s.toDouble(), "t$i", listOf("a$i", "b$i", "c$i")) }
val reply = listOf(topic(1000.0, "t10"), topic(1100.0, "t11"), topic(1200.0, "t12"))
@@ -683,7 +652,6 @@ object Tests {
}
fun longMeetingsAreNotedInPartsByTime() {
- // A line every 10 s: 90 min stays whole, 4 h becomes four parts of an hour.
equal(listOf(0 until 540), NotesEngine.parts(notesLines(540)), "90 minutes in one")
val four = NotesEngine.parts(notesLines(1440))
equal(4, four.size, "4 hours in four")
@@ -697,7 +665,6 @@ object Tests {
check(p.contains("[L241 40:00 对方] line 240"), "original line numbers")
check(!p.contains("[L238 "), "no earlier lines")
check(p.contains("This part ran 39:50"), "the part's length")
- // Each of three parts gets two of the eight topics.
check(p.contains("use at most 2 topics"), "the part's share of topics")
val merge = NotesEngine.mergePrompt(listOf("{\"summary\":\"a\"}", "{\"summary\":\"b\"}"), all, "English")
check(merge.contains("Part 2 of 2:\n{\"summary\":\"b\"}"), "the parts' notes")
@@ -711,8 +678,6 @@ object Tests {
check(ten.all { t -> kept.any { t.title in it.title.split(" / ") } }, "every topic joined, none dropped")
equal("0.0", NotesEngine.thinned(ten, 1, 3000.0).joinToString(",") { it.start.toString() }, "one")
equal(3, NotesEngine.thinned(ten.take(3), 4, 3000.0).size, "fewer stay")
- // A 2.5-hour meeting's last part, asked for 2 topics, came back with 3: the budget topic's
- // end as its own. Kept first and last, the budget topic at 125 min was lost.
val part = listOf(topic(6000.0, "营销发布安排", listOf("a")), topic(7500.0, "预算评审", listOf("b")), topic(8982.0, "预算评审(续)", listOf("c")))
val two = NotesEngine.thinned(part, 2, 8990.0)
equal("营销发布安排,预算评审", two.joinToString(",") { it.title }, "the topic kept over its continuation")
@@ -774,7 +739,7 @@ object Tests {
equal("Live notes", Strings.L("实时纪要"), "plain strings still load")
loadStrings("ja")
equal("1文", Strings.LF("%lld 句", 1), "no stringsdict: the .strings value")
- loadStrings("zh-Hans") // the other tests read the Chinese
+ loadStrings("zh-Hans")
val p = Strings.parsePlurals("<?xml version=\"1.0\"?>\n<!DOCTYPE plist>\n<plist version=\"1.0\"><dict><key>a &amp; b</key><dict>" +
"<key>NSStringLocalizedFormatKey</key><string>%#@x@ &lt;</string><key>x</key><dict><key>one</key><string>%lld y</string>" +
"<key>other</key><string>%lld ys</string></dict></dict></dict></plist>")
@@ -821,7 +786,6 @@ object Tests {
return LingClient(key, fake, clock = clock)
}
- /// The start gate's time, moved on by each wait instead of waiting (one request at a time).
private class FakeClock : GateClock() {
val start = 1_000_000L
var t = start
@@ -861,8 +825,6 @@ object Tests {
}
fun lingRidesOut429s() {
- // Ling's 429s come in runs (two in a row lost a line with one retry): heard audio backs off
- // 1, 2, 4 s and gets through; text translation fails at once so the caller can fall back.
val calls = AtomicInteger()
val clock = FakeClock()
val ling = client(Fake { if (calls.incrementAndGet() <= 3) busy() else reply("LANG: en\nORIGINAL: Hi.\nTRANSLATION: 嗨。") }, clock)
@@ -892,7 +854,6 @@ object Tests {
val clock = FakeClock()
equal("ok", client(Fake { if (calls.incrementAndGet() == 1) busy("5") else reply("ok") }, clock).chat("c", "i", Priority.Notes), "answered after the wait")
check(clock.waits[0] in 5.0..5.5, "waited as asked, got ${clock.waits}")
- // Asked to wait minutes: an outage, so the line goes now rather than after it.
val outage = Fake { busy("120") }
try { client(outage, FakeClock()).chat("c", "i", Priority.Translate, model = LingClient.AUDIO_MODEL, audio = byteArrayOf(1)); throw AssertionError("waited") }
catch (e: LingException) { equal(LingException.Kind.RateLimited, e.kind, "given up") }
@@ -910,11 +871,9 @@ object Tests {
val fake = Fake { if (calls.incrementAndGet() == 1) busy() else reply("notes") }
val ling = client(fake, clock)
try { ling.chat("first", "i", Priority.Translate) } catch (_: LingException) {}
- // A translation that wouldn't retry fails at once, without spending a request on the limit…
try { ling.chat("second", "i", Priority.Translate); throw AssertionError("sent during the pause") }
catch (e: LingException) { equal(LingException.Kind.RateLimited, e.kind, "busy") }
equal(1, fake.calls.size, "nothing sent")
- // …and one that would waits at the gate until the pause is over, then goes.
equal("notes", ling.chat("notes", "i", Priority.Notes), "notes after the pause")
check(clock.waits.sum() in 1.0..1.5, "held for the pause, got ${clock.waits}")
}
@@ -950,7 +909,6 @@ object Tests {
val ling = client(fake)
val a = thread { ling.chat("first", "i", Priority.Notes) }
Thread.sleep(20)
- // Queued while the gate is closed: the translation goes before the earlier notes call.
val b = thread { ling.chat("notes", "i", Priority.Notes) }
Thread.sleep(20)
val c = thread { ling.chat("translate", "i", Priority.Translate) }
@@ -962,8 +920,6 @@ object Tests {
}
fun listenEndToEnd() {
- // Two stretches of "speech", told apart by length (1 s, then 1.6 s); the fake Ming answers
- // the first one slower, and lines still come out in order.
val fake = Fake { body ->
if (body.contains("Ming-3.0-audio-flash")) {
val url = content(body, 1).arr()[0].obj()!!["audio_url"].obj()!!["url"] as String
@@ -995,8 +951,6 @@ object Tests {
}
fun listenServerErrors() {
- // A gateway answering 502 to every stretch: no subtitles, so from the third in a row the banner
- // says the service is erring (not after one or two); the next stretch heard clears it.
val calls = java.util.concurrent.atomic.AtomicInteger()
val fake = Fake { body ->
if (!body.contains("Ming-3.0-audio-flash")) reply("{}")
@@ -1011,7 +965,6 @@ object Tests {
val engine = ListenEngine(ling, Translator(ling), store, NotesEngine(ling, store), AppSettings(target = "zh-CN"))
val seen = java.util.Collections.synchronizedList(mutableListOf<Pair<String?, Int>>())
engine.onChange { seen.add(engine.problem to calls.get()) }
- // Four times real time: each reply is back before the next stretch goes, as in a meeting.
val src = PcmAudioSource({ concat(*Array(4) { concat(tone(1.0), silence(3.0)) }) }, speed = 4.0)
val ended = CountDownLatch(1)
src.onEnded = { ended.countDown() }
@@ -1050,8 +1003,6 @@ object Tests {
}
fun holdToSayAndEchoGate() {
- // The other side speaks English; I hold and say something (a different length of tone),
- // then the phone "speaks" while a tone plays: that must not become the other side's line.
val fake = Fake { body ->
val system = content(body, 0) as String
if (system.contains("into English")) reply("LANG: zh-CN\nORIGINAL: 你好。\nTRANSLATION: Hello.")
@@ -1084,7 +1035,7 @@ object Tests {
equal("Hello." to "en", spoken, "spoken in their language")
engine.muted = true
src.push(concat(tone(2.0), silence(1.2)))
- Thread.sleep(300) // mute lasts as long as the voice plays: let the worker take what came in meanwhile
+ Thread.sleep(300)
engine.muted = false
src.push(silence(1.0))
Thread.sleep(300)
@@ -1097,7 +1048,6 @@ object Tests {
}
fun anUnreachableServiceIsTriedOncePer15s() {
- // The service doesn't answer; Google does.
val fake = Fake { body -> if (body.contains("Subtitle:")) Transport.Response(500, "") else Transport.Response(200, "[[[\"你好\",\"Hello\"]]]") }
val old = LingClient.spacing
LingClient.spacing = 0.0
@@ -1118,7 +1068,6 @@ object Tests {
}
fun anUntranslatedSentenceIsNeitherSentNorRecorded() {
- // Ming hears me but returns no translation, and Ling and Google both fail.
val fake = Fake { body ->
if (body.contains("Ming-3.0-audio-flash")) reply("LANG: zh-CN\nORIGINAL: 你好。")
else Transport.Response(500, "")
@@ -1159,13 +1108,11 @@ object Tests {
engine.onSaid = { text, _ -> spoken = text }
val src = ManualSource()
engine.start(src, "mic")
- // Nobody spoke: the room's hush only, loud enough for the old check (rms 0.004).
val hush = ShortArray(16000 * 2) { ((if (it % 2 == 0) 1 else -1) * 0.004 * 32767).toInt().toShort() }
engine.hold(); src.push(hush); engine.release(); src.push(silence(0.3))
Thread.sleep(600)
equal(0, asked, "a silent hold isn't sent to the service")
equal("没听到声音,靠近手机再说", engine.sayProblem, "and says why")
- // Ming hears only 嗯: nothing said.
engine.hold(); src.push(tone(1.2)); engine.release(); src.push(silence(0.3))
val until = System.currentTimeMillis() + 4000
while (asked == 0 && System.currentTimeMillis() < until) Thread.sleep(20)
@@ -1232,7 +1179,6 @@ object Tests {
check(found[1]!!.evidence.startsWith("00:40 “Thanks"), "evidence is the line: ${found[1]!!.evidence}")
equal(mapOf(0 to "Christina"), refuted.toMap(), "no evidence near the voice")
equal(0, SpeakerNamer.read("not json", lines).first.size, "not JSON")
- // Without JSON mode (a host that refuses it) the reply may come fenced.
equal("George", SpeakerNamer.read("```json\n{\"speakers\": [{\"speaker\": 2, \"name\": \"George\", \"evidence\": \"L11\"}]}\n```", lines).first[1]?.name, "fenced")
check(SpeakerNamer.content(lines)!!.contains("说话人1"), "Ling sees the numbers")
check(SpeakerNamer.holds(found[1]!!, 1, lines), "the guess stands while its line does")
@@ -1255,7 +1201,6 @@ object Tests {
check(NotesEngine.prompt(MeetingNotes(), lines, 0, "Chinese", false).contains("对方] "), "no voices: 对方")
}
- /// Ming cuts "so we will ship" | "on Friday then." mid-sentence; `voices` says whose each half is.
private fun halves(voices: List<Int>): Pair<List<Pair<Int?, String>>, Int> {
val fake = Fake { body ->
if (body.contains("Ming-3.0-audio-flash")) {
@@ -1271,7 +1216,6 @@ object Tests {
val ling = client(fake)
val store = SessionStore()
val engine = ListenEngine(ling, Translator(ling), store, NotesEngine(ling, store), AppSettings(target = "zh-CN"))
- // Each "voiceprint" is the voice to give: one dimension, and a clusterer stand-in below.
engine.speakers = object : SpeakerTagger(object : Voiceprinter {
override fun embed(samples: ShortArray) = synchronized(order) { floatArrayOf(order.next().toFloat()) }
}) { override fun label(vector: FloatArray?, seconds: Double) = vector?.get(0)?.toInt() }
@@ -1307,7 +1251,7 @@ object Tests {
val store = SessionStore()
val engine = ListenEngine(ling, Translator(ling), store, NotesEngine(ling, store), AppSettings(target = "zh-CN"))
engine.speakers = object : SpeakerTagger(object : Voiceprinter {
- override fun embed(samples: ShortArray): FloatArray { Thread.sleep(600); return floatArrayOf(1f) } // a phone that can't keep up
+ override fun embed(samples: ShortArray): FloatArray { Thread.sleep(600); return floatArrayOf(1f) }
}) { override fun label(vector: FloatArray?, seconds: Double) = if (vector == null) null else 0 }
val src = PcmAudioSource({ concat(*Array(5) { concat(tone(1.0), silence(1.0)) }) }, speed = 0.0)
val ended = CountDownLatch(1)
@@ -1391,7 +1335,7 @@ object Tests {
val w = watch()
equal(null, w.tick(5_000.0, zoom, true), "a muted webinar is still a meeting")
equal(null, w.pending, "no prompt")
- val plain = watch(followApps = false) // Android: a call says nothing
+ val plain = watch(followApps = false)
equal(null, plain.tick(600.0, zoom, true), "prompts")
equal(MeetingEndWatch.Reason.Silence, plain.pending?.reason, "silence counts")
}
@@ -1417,7 +1361,6 @@ object Tests {
}
fun endsAtTheGivenTime() {
- // An ended-by-itself meeting is stored as ending at the time given, not when it stopped.
val store = SessionStore()
val s = store.begin(java.time.Instant.parse("2026-11-04T10:00:00Z"))
store.append(s.id, TranscriptLine(id = "h1-1", t = 1.0, src = "Hi", srcLang = "en", dstLang = "zh-CN"))
@@ -1432,7 +1375,7 @@ object Tests {
fun findsTheNewestAndroidRelease() {
val feed = Json.write(listOf(
- release("v1.10.0", "Cicada-1.10.0.dmg"), // Mac only: skipped
+ release("v1.10.0", "Cicada-1.10.0.dmg"),
release("v1.11.0", "Cicada-1.11.0-Android.apk", draft = true),
release("v1.12.0", "Cicada-1.12.0-Android.apk", pre = true),
release("v1.9.2", "Cicada-1.9.2-Windows-x64.zip", "Cicada-1.9.2-Android.apk"),
diff --git a/android/cli/src/main/kotlin/cicada/cli/VoiceTests.kt b/android/cli/src/main/kotlin/cicada/cli/VoiceTests.kt
index a8e5087..5090f28 100644
--- a/android/cli/src/main/kotlin/cicada/cli/VoiceTests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/VoiceTests.kt
@@ -1,5 +1,3 @@
-// 读出来的声音 (Voices.kt): the Mac's catalog, default and fallback rules, and what goes to Ling.
-// No network: LingClient runs against a fake transport.
package cicada.cli
import cicada.*
@@ -23,7 +21,6 @@ object VoiceTests {
fun trimmed() {
val rate = Segmenter.RATE
- // 1 s before, 12 s of reading, 1.5 s after (the pause before 读完了).
val clip = tone(12.0, pad = 0.0).let { ShortArray(rate) + it + ShortArray(rate * 3 / 2) }
val t = VoiceReference.trim(clip)
check(kotlin.math.abs(t.size / rate.toDouble() - 12.4) < 0.05, "12 s and 0.2 s each side, got ${t.size / rate.toDouble()}")
@@ -54,7 +51,6 @@ object VoiceTests {
return LingClient(k, fake, config = s::aiConfig)
}
- /// A tone at 16 kHz: `seconds` long, silence before and after.
private fun tone(seconds: Double, pad: Double = 0.5): ShortArray {
val rate = Segmenter.RATE
val out = ShortArray(((seconds + 2 * pad) * rate).toInt())
@@ -130,13 +126,11 @@ object VoiceTests {
"message" to mapOf("content" to "LANG: zh-CN\nORIGINAL: $original\nTRANSLATION: Hello everyone."), "finish_reason" to "stop"))), pretty = false))
val short = VoiceReference.check(Translator(client(heard("大家好"), AppSettings())), tone(8.0, pad = 0.0), "zh-CN")
equal(VoiceReference.Check.Again("录音太短了,请至少朗读 %lld 秒", listOf(10)), short, "under 10 s")
- // 12 s read as 12 characters: one a second, too slow for a meeting.
val slow = VoiceReference.check(Translator(client(heard("大家好我是这次会议的主持人"), AppSettings())), tone(12.0), "zh-CN")
equal(VoiceReference.Check.Again("读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次"), slow, "slow")
val passage = "大家好,我是这次会议的主持人。今天我们主要讨论新产品的上线计划,包括时间安排、测试范围和市场推广。"
val ok = VoiceReference.check(Translator(client(heard(passage), AppSettings())), tone(11.0), "zh-CN")
equal(VoiceReference.Check.Ok(passage, VoiceReference.trim(tone(11.0))), ok, "heard at an ordinary pace, the trimmed clip kept")
- // 9.5 s of reading padded to 15 s by pauses: the reading is what counts.
val padded = VoiceReference.check(Translator(client(heard(passage), AppSettings())), tone(9.5, pad = 2.75), "zh-CN")
equal(VoiceReference.Check.Again("录音太短了,请至少朗读 %lld 秒", listOf(10)), padded, "pauses don't count")
val none = VoiceReference.check(Translator(client(heard("嗯"), AppSettings())), tone(11.0), "zh-CN")
diff --git a/android/core/build.gradle.kts b/android/core/build.gradle.kts
index e36aa9a..6736053 100644
--- a/android/core/build.gradle.kts
+++ b/android/core/build.gradle.kts
@@ -1,4 +1,3 @@
-// The engines: Kotlin stdlib and java.* only, so they build, test and run on the Mac.
plugins { id("org.jetbrains.kotlin.jvm") }
kotlin { jvmToolchain(21) }
java { toolchain { languageVersion = JavaLanguageVersion.of(21) } }
diff --git a/android/core/src/main/kotlin/cicada/AICheck.kt b/android/core/src/main/kotlin/cicada/AICheck.kt
index 8f3c19f..35e5474 100644
--- a/android/core/src/main/kotlin/cicada/AICheck.kt
+++ b/android/core/src/main/kotlin/cicada/AICheck.kt
@@ -3,30 +3,13 @@ package cicada
import cicada.Strings.L
import cicada.Strings.LF
-/// What the last look at the AI service found, step by step (AICheck.swift): can this phone reach
-/// it, does it take the key, does the text model answer, does the hear model take audio. A failed
-/// step stops the ones after it, so the settings can say exactly where it broke and offer the one
-/// thing that fixes it. The port has a fourth step the Mac doesn't: it hears through the service.
-///
-/// Most of the time the answer comes from real requests (hearing, notes, translation): every call
-/// reports back here, so a meeting keeps the steps current without any extra request. An explicit
-/// check runs only when the service, model or key changes, at launch, on 重新检查, and when the
-/// network changes after the service was unreachable. Immutable: LingClient swaps in a new one.
data class AICheck(
val steps: List<Step> = StepID.values().map { Step(it, State.Untested) },
- /** When the newest result came in (epoch ms); null before any. */
val at: Long? = null,
- /** The newest result came from a real request in a meeting, not from a check. */
val passive: Boolean = false,
- /** Where the phone's proxy stands when the service can't be reached: only read, to word the hint. */
val proxy: ProxyHint? = null,
- /** OpenRouter only: dollars left (the smaller of the key's limit and the account's credits). */
val balance: Double? = null,
- /** A custom service: how long one real sentence took, and whether the model thought first. */
val translate: Speed? = null,
- /** A custom service whose notes go to another model or server: how that one answered. Null
- * while notes use the translation model (then `steps` say it all). A notes failure doesn't
- * stop translation: `failure` and `passed` stay about translation. */
val notes: Notes? = null,
) {
sealed class Notes {
@@ -42,8 +25,6 @@ data class AICheck(
}
data class Speed(val seconds: Double, val thinks: Boolean) {
- /// A sentence that takes this long often misses the 6 s a translation is given
- /// (Translator.translate) and falls back to Google.
val slow get() = thinks || seconds >= SLOW_AFTER
companion object { const val SLOW_AFTER = 3.0 }
}
@@ -54,19 +35,15 @@ data class AICheck(
sealed class State {
object Running : State()
- /** `seconds` of the request that proved it; null when it came with another step's request. */
data class Ok(val seconds: Double? = null) : State()
- /** 429: the service is busy but the key works. Counts as passed. */
object Busy : State()
data class Fail(val reason: Reason, val code: Int? = null) : State()
object Skipped : State()
- /** Nothing has proven it yet. */
object Untested : State()
}
data class Step(val id: StepID, val state: State)
- /// A phone has no proxy app port to look for (the Mac's appRunning): only the system's.
enum class ProxyHint { SystemOn, None }
data class Failure(val step: StepID, val reason: Reason, val code: Int?)
@@ -75,32 +52,24 @@ data class AICheck(
fun with(id: StepID, state: State) = copy(steps = steps.map { if (it.id == id) Step(id, state) else it })
- /// The first step that failed, and why.
val failure: Failure? get() {
for (s in steps) { val st = s.state; if (st is State.Fail) return Failure(s.id, st.reason, st.code) }
return null
}
val running get() = steps.any { it.state == State.Running } || notes == Notes.Running
- /** Translation works but the notes' own model or server doesn't (a busy one fixes itself). */
val notesFailed get() = notes?.reason.let { it != null && it != Reason.Busy }
val busy get() = steps.any { it.state == State.Busy }
- /** Every step passed (busy counts; a step nothing has tested yet does not block). */
val passed get() = at != null && failure == null && !running
val lowBalance get() = (balance ?: Double.POSITIVE_INFINITY) < LOW_BALANCE
- /** Text works but every sentence is slow (a thinking model): translations will fall back. */
val slow get() = textFailure == null && translate?.slow == true
- /** The failure, unless it is only the hear model's (a custom service's rows show that apart). */
val textFailure get() = failure?.takeIf { it.step != StepID.Hear }
- /** Something only the user can fix (a busy service fixes itself). */
val needsUser: Boolean get() {
val f = failure ?: return lowBalance
return f.reason != Reason.Busy && f.reason != Reason.ServerError
}
- /// `step` failed and the ones after it were never reached. `reached`: a reply came back, so the
- /// steps that request proves before it passed (false when nothing was sent, like a management key).
fun fail(step: StepID, reason: Reason, code: Int? = null, reached: Boolean = true): AICheck {
val proves = proves(step)
var after = false
@@ -109,9 +78,7 @@ data class AICheck(
s.id == step -> { after = true; Step(s.id, State.Fail(reason, code)) }
after -> Step(s.id, State.Skipped)
reached && s.id in proves && !isOk(s.state) -> Step(s.id, State.Ok())
- // The text step comes before hearing but a hear request says nothing about it.
s.id !in proves && s.state == State.Skipped -> Step(s.id, State.Untested)
- // Nothing was sent: the step a check had started on was never tried.
s.state == State.Running -> Step(s.id, State.Untested)
else -> s
}
@@ -119,9 +86,6 @@ data class AICheck(
return copy(steps = next, proxy = if (reason == Reason.Unreachable) proxy else null)
}
- /// One request proved `step` and what it rests on (a chat proves the address, the key and the
- /// text model; heard audio the address, the key and the hear model). Clears what failed before;
- /// steps that were skipped are open again.
fun pass(step: StepID, seconds: Double?): AICheck {
val proves = proves(step)
val next = steps.map { s ->
@@ -137,7 +101,6 @@ data class AICheck(
// MARK: Words
- /// Why the failed step failed, in one sentence. `model`: the text model; `hearModel`: the hear model.
fun message(service: String, host: String, model: String, hearModel: String): String? {
val f = failure ?: return if (busy) LF("%@ 现在很忙,key 没问题。开会时会自动重试。", service) else null
return when (f.reason) {
@@ -154,10 +117,6 @@ data class AICheck(
}
}
- /// What stops listening or the notes until the user changes something (the Mac's
- /// AIServiceStrip.blocking): (what's wrong, what it stops). Not the network, a busy service or
- /// a server error: those fix themselves. Said beyond 设置, on the listening notification and the
- /// live screens. Models by their short name (after the last "/").
fun blocking(service: String, textModel: String, hearModel: String): Pair<String, String>? {
val f = failure ?: return null
val stops = L("修好之前听不了")
@@ -173,8 +132,6 @@ data class AICheck(
}
}
- /// Why translations are slow, and what to do (a custom service).
- /// `googleOff`: 语音和文字只发给你的服务 is on, so a sentence that takes too long isn't handed to Google.
fun slowLine(googleOff: Boolean = false): String? {
val t = translate?.takeIf { slow } ?: return null
val secs = String.format(Strings.locale, "%.1f", t.seconds)
@@ -184,8 +141,6 @@ data class AICheck(
else LF("翻一句要 %@ 秒,超过 6 秒会改用 Google。换一个更小的模型会快一些。", secs)
}
- /// The notes' own model or server's problem, in one sentence. `sharedKey`: notes use the
- /// translation key, so a refused key wants one of their own.
fun notesLine(host: String, model: String, sharedKey: Boolean): String? {
val n = notes as? Notes.Fail ?: return null
return when (n.why) {
@@ -201,7 +156,6 @@ data class AICheck(
}
}
- /// The proxy line under "can't reach": what this phone's proxy looks like, and what to do.
fun proxyLine(service: String, host: String): String? {
if (failure?.reason != Reason.Unreachable) return null
return when (proxy ?: return null) {
@@ -210,14 +164,12 @@ data class AICheck(
}
}
- /// "OpenRouter 余额快用完了(还剩 $0.40)" when it is.
fun balanceLine(service: String): String? {
val b = balance ?: return null
if (!lowBalance) return null
return LF("%@ 余额快用完了(还剩 $%@)", service, String.format(java.util.Locale.US, "%.2f", maxOf(0.0, b)))
}
- /// Debug and logs: "reach=ok key=fail(invalidKey) text=skipped hear=skipped".
val summary: String get() {
val parts = steps.joinToString(" ") { s ->
val v = when (val st = s.state) {
@@ -241,7 +193,6 @@ data class AICheck(
fun isOk(s: State) = s is State.Ok
- /// The steps a request that reached `step` also proves.
fun proves(step: StepID): Set<StepID> = when (step) {
StepID.Reach -> setOf(StepID.Reach)
StepID.Key -> setOf(StepID.Reach, StepID.Key)
@@ -251,7 +202,6 @@ data class AICheck(
fun lower(name: String) = name.replaceFirstChar { it.lowercaseChar() }
- /// A reason by its debug name ("noModel"), for `ai-check-sim`.
fun reasonNamed(name: String): Reason? = Reason.values().firstOrNull { lower(it.name).equals(name, ignoreCase = true) }
fun title(id: StepID, host: String): String = when (id) {
@@ -261,9 +211,6 @@ data class AICheck(
StepID.Hear -> L("听对方")
}
- /// Which step a failed request stops at, and why. `step` is the step the request was
- /// proving: the text model for a chat, the hear model for heard audio (a 400/404/415/422
- /// there means the model doesn't take audio, not that it is missing).
fun classify(e: LingException, step: StepID): Failure? = when (e.kind) {
LingException.Kind.Network, LingException.Kind.Timeout -> Failure(StepID.Reach, Reason.Unreachable, null)
LingException.Kind.InvalidKey -> Failure(StepID.Key, Reason.InvalidKey, null)
@@ -278,11 +225,8 @@ data class AICheck(
LingException.Kind.NoKey, LingException.Kind.Hijacked, LingException.Kind.Parse -> null
}
- /// What a hear model that doesn't take audio answers.
val DEAF_CODES = listOf(400, 404, 415, 422)
- /// The prefix of a key says whose it is: `sk-or-` OpenRouter, `sk-payg` ZenMux, `sk-mgmt`
- /// ZenMux's management key (it can't call models). Null: nothing to tell.
fun owner(key: String): Pair<String, Boolean>? {
val k = key.trim()
return when {
@@ -293,15 +237,12 @@ data class AICheck(
}
}
- /// Every model id in a `/models` reply (null when the reply can't be read or lists none).
fun listedModels(body: String): Set<String>? {
val root = Json.parseObject(body) ?: return null
val ids = root["data"].arr().mapNotNull { it.obj()?.get("id").str() }.filter { it.isNotEmpty() }
return if (ids.isEmpty()) null else ids.toSet()
}
- /// The ids a `/models` reply says take audio in. Null when it says nothing about what models
- /// take (a custom service, Ollama): then only the silent-audio probe can tell.
fun listedHearing(body: String): Set<String>? {
val root = Json.parseObject(body) ?: return null
var told = false
@@ -316,8 +257,6 @@ data class AICheck(
return if (told) ids else null
}
- /// OpenRouter: dollars left from `/key` (`limit_remaining`, null without a key limit) and
- /// `/credits` (bought minus used); the smaller one is what the next meeting can spend.
fun balance(key: Map<String, Any?>?, credits: Map<String, Any?>?): Double? {
val k = key?.get("data").obj()?.get("limit_remaining").num()
val d = credits?.get("data").obj()
@@ -330,7 +269,6 @@ data class AICheck(
}
}
- /// A made-up result for `reason` (debug screenshots of every state).
fun simulated(reason: Reason): AICheck {
val r = AICheck()
return when (reason) {
diff --git a/android/core/src/main/kotlin/cicada/Audio.kt b/android/core/src/main/kotlin/cicada/Audio.kt
index 86adcb3..91bb8b7 100644
--- a/android/core/src/main/kotlin/cicada/Audio.kt
+++ b/android/core/src/main/kotlin/cicada/Audio.kt
@@ -7,19 +7,13 @@ import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
-/// Where listening gets its sound: 16 kHz mono Int16, pushed from any thread. On Android the
-/// playback capture or the microphone; in tests, the CLI and the sample meeting, a file.
interface AudioSource {
- /// Set before start(); called on the source's own thread.
var onSamples: ((ShortArray) -> Unit)?
- /// Called once when the source can't go on: null when a file finished, else why.
var onEnded: ((String?) -> Unit)?
fun start()
fun stop()
}
-/// Debug (the Mac's silentListen): a meeting with no audio at all, its lines given by
-/// ListenEngine.debugHeard, to try what follows a finished sentence without playing anything.
class SilentAudioSource : AudioSource {
override var onSamples: ((ShortArray) -> Unit)? = null
override var onEnded: ((String?) -> Unit)? = null
@@ -27,7 +21,6 @@ class SilentAudioSource : AudioSource {
override fun stop() {}
}
-/// Plays 16 kHz samples into listening, in real time or as fast as it can (`speed` 0).
class PcmAudioSource(private val load: () -> ShortArray, private val speed: Double = 1.0) : AudioSource {
override var onSamples: ((ShortArray) -> Unit)? = null
override var onEnded: ((String?) -> Unit)? = null
@@ -41,7 +34,7 @@ class PcmAudioSource(private val load: () -> ShortArray, private val speed: Doub
val pcm = try { load() } catch (e: Exception) {
Log.d("file source: unreadable ${e.javaClass.simpleName}"); onEnded?.invoke("unreadable"); return@Thread
}
- val chunk = Segmenter.RATE / 10 // 100 ms, like a capture callback
+ val chunk = Segmenter.RATE / 10
val started = System.nanoTime()
var i = 0
while (i < pcm.size && !stopped) {
@@ -53,7 +46,6 @@ class PcmAudioSource(private val load: () -> ShortArray, private val speed: Doub
}
i += chunk
}
- // A second of silence so the last sentence's pause is heard.
onSamples?.invoke(ShortArray(Segmenter.RATE))
onEnded?.invoke(null)
}, "PcmAudioSource").apply { isDaemon = true }.start()
@@ -62,7 +54,6 @@ class PcmAudioSource(private val load: () -> ShortArray, private val speed: Doub
override fun stop() { stopped = true }
}
-/// One stretch of speech as sent to Ming: the bytes and their media type.
class Clip(val bytes: ByteArray, val type: String) {
companion object { fun wav(pcm: ShortArray) = Clip(Wav.bytes(pcm), "audio/wav") }
}
@@ -77,7 +68,6 @@ object Wav {
return b.array()
}
- /// A PCM16 WAV of any rate and channel count, as 16 kHz mono.
fun read(input: InputStream): ShortArray {
val all = input.use { it.readBytes() }
val b = ByteBuffer.wrap(all).order(ByteOrder.LITTLE_ENDIAN)
@@ -112,7 +102,6 @@ object Wav {
throw IllegalArgumentException("no data chunk")
}
- /// Box average then pick: plenty for speech going to a recognizer.
fun resample(mono: DoubleArray, rate: Int): ShortArray {
fun clamp(x: Double) = x.coerceIn(Short.MIN_VALUE.toDouble(), Short.MAX_VALUE.toDouble()).toInt().toShort()
if (rate == Segmenter.RATE) return ShortArray(mono.size) { clamp(mono[it]) }
diff --git a/android/core/src/main/kotlin/cicada/Correction.kt b/android/core/src/main/kotlin/cicada/Correction.kt
index a2880ce..ee55aee 100644
--- a/android/core/src/main/kotlin/cicada/Correction.kt
+++ b/android/core/src/main/kotlin/cicada/Correction.kt
@@ -1,16 +1,10 @@
package cicada
-/// A word the AI service said speech recognition got wrong in a finished line ("莫拉" → "Morpho"),
-/// field for field the Mac's LineFix. The line keeps what was heard (`src`) and carries its fixes,
-/// so a record moves between the platforms unchanged.
data class LineFix(
var from: String,
var to: String,
- /// Waiting for the user (a name sound can't check): not applied until confirmed.
var ask: Boolean? = null,
- /// The user said no (改回 or 不对): kept so the same line isn't fixed that way again.
var off: Boolean? = null,
- /// The user's own: said 对, or wrote it (改这句…). A later pass never drops or overrides it.
var user: Boolean? = null,
) {
val applied: Boolean get() = ask != true && off != true
@@ -22,11 +16,6 @@ data class LineFix(
}
}
-/// 改正听错的词 (the Mac's Correction.swift): which of the service's proposed fixes to take, and
-/// the line as shown once they are in. The service's own confidence isn't enough: in a 21-minute
-/// test it rated "快销 → 区块" and "苍蝇 → 方向" above 0.85. So a Chinese word may only be swapped
-/// for one that sounds alike (pinyin), a Latin word only for a near spelling, and a new name only
-/// once the user says so.
object Correction {
data class Edit(val from: String, val to: String, val confidence: Double)
@@ -36,43 +25,31 @@ object Correction {
const val SPELLING_AT = 0.8
const val ASK_AT = 0.8
- /// Toneless lowercase pinyin of one character ("" when it has none). The app sets the phone's
- /// ICU transform ("Han-Latin; Latin-ASCII"), the counterpart of the Mac's system transform;
- /// the tests and the CLI set a table generated from the same transform. Unset: nothing sounds alike.
@Volatile var pinyinOf: (Char) -> String = { "" }
private fun word(c: Char) = c.code < 128 && c.isLetterOrDigit()
- /// The part an edit changes, as a word: "解除质压" → "解除质押" is "质压" → "质押" (at least two
- /// characters, so one refusal doesn't block every 压 → 押), and a Latin word stays whole
- /// ("Un450P三" → "Uniswap V3", not "450P三" → "iswap V3").
fun core(from: String, to: String): Pair<String, String> {
val a = from; val b = to
var i = 0
while (i < minOf(a.length, b.length) && a[i] == b[i]) i++
var j = 0
while (j < minOf(a.length, b.length) - i && a[a.length - 1 - j] == b[b.length - 1 - j]) j++
- // Only a change that starts or ends inside a Latin word takes the rest of the word.
if ((i < a.length && word(a[i])) || (i < b.length && word(b[i]))) { while (i > 0 && word(a[i - 1])) i-- }
if ((a.length - j - 1 >= 0 && word(a[a.length - j - 1])) || (b.length - j - 1 >= 0 && word(b[b.length - j - 1]))) {
while (j > 0 && word(a[a.length - j])) j--
}
- // Two characters at least, taken from the Chinese side: "FFT制押" → "FFT质押" is "制押" → "质押".
while (a.length - j - i < 2 || b.length - j - i < 2) {
if (j > 0 && !word(a[a.length - j])) j-- else if (i > 0 && !word(a[i - 1])) i-- else break
}
return a.substring(i, maxOf(i, a.length - j)) to b.substring(i, maxOf(i, b.length - j))
}
- /// A fix as the UI names it (听成 X → Y, 已改回 X): the changed words, or the whole fix when
- /// it only adds or drops words ("in" → "in now", whose changed part alone would be "" → "now").
fun label(f: LineFix): Pair<String, String> {
val c = core(f.from, f.to)
return if (c.first.isEmpty() || c.second.isEmpty()) f.from to f.to else c
}
- /// `known`: the user confirmed this heard form for this word (the word list). `rejected`: they
- /// said no to it in this meeting.
fun decide(e: Edit, known: (String, String) -> Boolean, rejected: (String, String) -> Boolean): Verdict {
val (cf, ct) = core(e.from, e.to)
if (cf.isEmpty() || ct.isEmpty() || cf.lowercase() == ct.lowercase() || rejected(e.from, e.to) || rejected(cf, ct)) return Verdict.Drop
@@ -82,18 +59,12 @@ object Correction {
if (!latinFrom && !latinTo && han(cf) && han(ct) && soundsAlike(cf, ct)) return Verdict.Apply
if (latinFrom && latinTo && cf.all { it.code < 128 } && ct.all { it.code < 128 } && e.confidence >= SPELLING_AT &&
distance(cf.lowercase(), ct.lowercase()) <= 2) return Verdict.Apply
- // A new name (Chinese heard as a Latin name, or a respelled one): sound can't check it. A
- // name has a capital or a digit; "X平台 → X platform" is a translation, and one 对 to it
- // taught the word list 平台 → platform, which then rewrote every 平台 in the meeting.
if (latinTo && e.confidence >= ASK_AT && nameShaped(ct)) return Verdict.Ask
return Verdict.Drop
}
- /// Latin text that could be a name: a capital or a digit in it (Morpho, GPT4o), not "platform".
fun nameShaped(s: String): Boolean = s.any { it.code < 128 && (it.isUpperCase() || it.isDigit()) }
- /// A Chinese word "fixed" into a plain English one (平台 → platform): a translation, not a
- /// misheard name.
fun translation(heard: String, word: String): Boolean =
han(heard) && word.any { it.code < 128 && it.isLetter() } && word.all { it.code < 128 } && !nameShaped(word)
@@ -107,8 +78,6 @@ object Correction {
return "" to syllable
}
- /// Same number of syllables, and on average three quarters alike: a syllable counts whole when
- /// equal, half when its initial or its final matches (质/追, 销/照). 苍蝇/方向 is a quarter.
fun soundsAlike(a: String, b: String): Boolean {
val x = pinyin(a); val y = pinyin(b)
if (x.size != y.size || x.isEmpty() || x.any { it.isEmpty() } || y.any { it.isEmpty() }) return false
@@ -137,11 +106,7 @@ object Correction {
return row[b.length]
}
- /// The service's reply to a sentence sent with fixes asked for:
- /// {"translation": "…", "fixes": [{"from", "to", "confidence"}]}. Null when it isn't that shape.
- /// Fixes whose words aren't in the subtitle are dropped: the service sometimes quotes them rephrased.
fun parse(reply: String, subtitle: String): Pair<String, List<Edit>>? {
- // Asked for JSON in the prompt only: take the outermost {…}, fenced or not.
val open = reply.indexOf('{'); val close = reply.lastIndexOf('}')
if (open < 0 || close <= open) return null
val o = Json.parseObject(reply.substring(open, close + 1)) ?: return null
@@ -156,9 +121,6 @@ object Correction {
return translation.trim() to edits
}
- /// What a line's fixes become after the service answered for it again (a joined line): the
- /// user's decisions stay (said no, said yes, wrote it), and of the rest only what is proposed
- /// again. So a pass that no longer proposes a fix takes it back.
fun merge(old: List<LineFix>, new: List<LineFix>): List<LineFix> {
val kept = old.filter { it.off == true || it.user == true }
val fresh = new.filter { n ->
@@ -170,17 +132,9 @@ object Correction {
data class UserEdit(val fix: LineFix, val heard: String, val swap: Boolean)
- /// 改这句…: the user rewrote the line as shown. What changed, as a fix on top of the others: the
- /// changed span grown to whole tokens (a Latin word, or one CJK character), and further, a token
- /// at a time, until it holds a letter and is the only such span in the line. An added word
- /// ("lock that in." → "lock that in now.") is then "in" → "in now" on this line, never "." on
- /// every line. `swap` is whether words were replaced (not only added or dropped): only a swap
- /// may go to the rest of the meeting and teach the word list. `heard` is the words in `src`
- /// when they are there, else the heard words of the fix the user corrected again.
fun userEdit(shown: String, edited: String, src: String, fixes: List<LineFix>): UserEdit? {
val new = edited.trim()
if (new.isEmpty() || new == shown) return null
- // Code points, as the Mac's Characters: a span never splits a surrogate pair.
val a = shown.codePoints().toArray(); val b = new.codePoints().toArray()
fun str(x: IntArray, from: Int, to: Int) = String(x, from, to - from)
var p = 0
@@ -188,9 +142,8 @@ object Correction {
var q = 0
while (q < minOf(a.size, b.size) - p && a[a.size - 1 - q] == b[b.size - 1 - q]) q++
val swap = a.size - p - q > 0 && b.size - p - q > 0
- // Tokens of the shown line: a run of ASCII letters and digits, else one character.
fun latin(c: Int) = c < 128 && Character.isLetterOrDigit(c)
- val tokens = mutableListOf<IntRange>() // start until end (exclusive)
+ val tokens = mutableListOf<IntRange>()
var k = 0
while (k < a.size) {
var e = k + 1
@@ -209,7 +162,6 @@ object Correction {
return n
}
fun replacement() = str(b, start, b.size - (a.size - end))
- // A dropped word ("in now." → "in.") grows too, so neither side of the fix is empty.
while (span().codePoints().noneMatch { Character.isLetterOrDigit(it) } || count(span()) != 1 || replacement().isEmpty()) {
val before = tokens.lastOrNull { it.last + 1 <= start }
val after = tokens.firstOrNull { it.first >= end }
@@ -223,13 +175,8 @@ object Correction {
return UserEdit(LineFix(from, to, user = true), heard, swap)
}
- /// The line as shown: each applied fix replaces its words where they still are. `marks` are
- /// the replaced words (start, end in UTF-16 units), for the dotted underline.
class Applied(val text: String, val marks: List<IntRange>)
- /// Where `s` stands as words of its own in `text` (its start, or null): a Latin edge of it never
- /// runs on into a Latin word around it. `core` pads a fix to two characters, so the word list
- /// learned "S平 → X平", which matched inside "iOS平台" and made it "iOX平台".
fun word(s: String, text: String): Int? {
if (s.isEmpty()) return null
var from = 0
@@ -247,8 +194,7 @@ object Correction {
fun apply(fixes: List<LineFix>, src: String): Applied {
var text = src
- val spans = mutableListOf<Pair<String, Int>>() // replacement and its offset, kept valid as text changes
- // The user's own last: written against the line as it was shown, other fixes in.
+ val spans = mutableListOf<Pair<String, Int>>()
val ordered = fixes.filter { it.user != true } + fixes.filter { it.user == true }
for (f in ordered) {
if (!f.applied || f.from.isEmpty()) continue
diff --git a/android/core/src/main/kotlin/cicada/Ed25519.kt b/android/core/src/main/kotlin/cicada/Ed25519.kt
index fd6c3b7..32073a8 100644
--- a/android/core/src/main/kotlin/cicada/Ed25519.kt
+++ b/android/core/src/main/kotlin/cicada/Ed25519.kt
@@ -3,15 +3,8 @@ package cicada
import java.math.BigInteger
import java.security.MessageDigest
-/// Ed25519 signing (RFC 8032), for the share service's device key (ShareClient). Android has it
-/// built in only from Android 13 (API 33) and the app runs from Android 10, so this is the RFC's
-/// reference algorithm on BigInteger, with the platform's SHA-512: slow by crypto standards (tens
-/// of milliseconds a signature), which is nothing for one request. Signing only; the server
-/// verifies. Tested against RFC 8032's vectors and the JDK's own Ed25519 (cli Tests).
-/// Not constant-time: the key only names this phone to the share service (rate limits and owning
-/// its links), and nothing else on the phone can time the signing.
object Ed25519 {
- private val TWO = BigInteger.valueOf(2) // BigInteger.TWO is Android 13+
+ private val TWO = BigInteger.valueOf(2)
private val P = BigInteger.ONE.shiftLeft(255).subtract(BigInteger.valueOf(19))
private val Q = BigInteger.ONE.shiftLeft(252).add(BigInteger("27742317777372353535851937790883648493"))
private val D = BigInteger.valueOf(-121665).multiply(inv(BigInteger.valueOf(121666))).mod(P)
@@ -30,10 +23,9 @@ object Ed25519 {
val x2 = yy.subtract(BigInteger.ONE).multiply(inv(D.multiply(yy).add(BigInteger.ONE))).mod(P)
var x = x2.modPow(P.add(BigInteger.valueOf(3)).shiftRight(3), P)
if (x.multiply(x).subtract(x2).mod(P).signum() != 0) x = x.multiply(SQRT_M1).mod(P)
- return if (x.testBit(0)) P.subtract(x) else x // the base point's x is even
+ return if (x.testBit(0)) P.subtract(x) else x
}
- // Extended coordinates (X, Y, Z, T), x = X/Z, y = Y/Z, xy = T/Z.
private fun add(a: Array<BigInteger>, b: Array<BigInteger>): Array<BigInteger> {
val pa = a[1].subtract(a[0]).multiply(b[1].subtract(b[0])).mod(P)
val pb = a[1].add(a[0]).multiply(b[1].add(b[0])).mod(P)
@@ -83,10 +75,8 @@ object Ed25519 {
return a to h.copyOfRange(32, 64)
}
- /// The 32-byte public key of a 32-byte private seed.
fun publicKey(seed: ByteArray): ByteArray = compress(mul(expand(seed).first, G))
- /// A 64-byte signature of `message`.
fun sign(seed: ByteArray, message: ByteArray, publicKey: ByteArray = publicKey(seed)): ByteArray {
val (a, prefix) = expand(seed)
val r = number(sha512(prefix, message)).mod(Q)
diff --git a/android/core/src/main/kotlin/cicada/Export.kt b/android/core/src/main/kotlin/cicada/Export.kt
index 6980a77..62e99f6 100644
--- a/android/core/src/main/kotlin/cicada/Export.kt
+++ b/android/core/src/main/kotlin/cicada/Export.kt
@@ -7,17 +7,11 @@ import java.time.format.FormatStyle
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
-/// What the transcript shows for the other side's lines (the Mac's SpeakerLabels, SpeakerID.swift).
-/// A voice gets a number only once it has `SHOWN_AFTER` substantive lines, and only when at least
-/// two voices have, so a one-to-one call stays 对方. Numbers follow the order voices got there.
-/// The voices come from SpeakerTagger (Speakers.kt) or records made on another platform.
object SpeakerLabels {
const val SHOWN_AFTER = 5
- /// Speaker numbers on (设置 › 说话人识别), kept in step by the app.
@Volatile var voices = true
- /// Long enough to say whose voice it is: three words, or four characters of CJK.
fun substantive(text: String): Boolean {
val words = text.split(Regex("\\s+")).filter { w -> w.any { it.isLetter() } }
if (words.size >= 3) return true
@@ -26,7 +20,6 @@ object SpeakerLabels {
}.count() >= 4
}
- /// Voice id → 1-based speaker number, for the voices on show.
fun voiceNumbers(lines: List<TranscriptLine>): Map<Int, Int> {
val count = HashMap<Int, Int>(); val reached = HashMap<Int, Int>()
lines.forEachIndexed { i, l ->
@@ -40,7 +33,6 @@ object SpeakerLabels {
return shown.mapIndexed { i, v -> v to i + 1 }.toMap()
}
- /// Line id → 1-based speaker number; lines without one show as 对方.
fun numbers(lines: List<TranscriptLine>): Map<String, Int> {
if (!voices) return emptyMap()
val number = voiceNumbers(lines)
@@ -49,7 +41,6 @@ object SpeakerLabels {
return out
}
- /// Speaker number → name: the user's, else Ling's guess (unless the user turned it down).
fun names(s: Session): Map<Int, String> {
if (s.voiceNames == null && s.voiceGuesses == null) return emptyMap()
val out = HashMap<Int, String>()
@@ -61,20 +52,17 @@ object SpeakerLabels {
return out
}
- /// Speaker number → its voice id (to store a name under the voice).
fun voiceOf(lines: List<TranscriptLine>, number: Int): Int? = voiceNumbers(lines).entries.firstOrNull { it.value == number }?.key
fun label(number: Int, names: Map<Int, String>): String = names[number] ?: Strings.LF("说话人 %lld", number)
- /// The notes with names: Ling wrote "说话人 6" before anyone named them (SpeakerLabels.named on
- /// the Mac). A copy; the record keeps what Ling wrote.
fun named(notes: MeetingNotes, names: Map<Int, String>): MeetingNotes {
val n = MeetingNotes.from(notes.toJson())
if (names.isEmpty()) return n
fun swap(text: String): String {
if (!text.contains("说话人") && !text.contains("Speaker")) return text
var out = text
- for ((k, name) in names.entries.sortedByDescending { it.key }) // 说话人 12 before 说话人 1
+ for ((k, name) in names.entries.sortedByDescending { it.key })
for (form in listOf("说话人 $k", "说话人$k", "Speaker $k")) out = out.replace(form, name)
return out
}
@@ -84,12 +72,8 @@ object SpeakerLabels {
return n
}
- /// Whether lines say who spoke. An imported file has no "other side" to call 对方: its lines
- /// are named only once its voices are told apart.
fun saysWho(s: Session, numbers: Map<String, Int>): Boolean = s.sourceFile == null || numbers.isNotEmpty()
- /// Who said a line: 你 · 同传 (said with 我说, so the other side heard its translation), a
- /// speaker's name or number, else 对方 (未识别 once others have numbers).
fun speakerName(l: TranscriptLine, numbers: Map<String, Int>, names: Map<Int, String>): String {
if (l.speaker == "me") return Strings.L("你 · 同传")
numbers[l.id]?.let { return label(it, names) }
@@ -97,8 +81,6 @@ object SpeakerLabels {
}
}
-/// Exports, as the Mac writes them (TranscriptExport, SessionStore.swift): Markdown, SRT subtitles
-/// and a Word document. Plain JVM, so the CLI tests them.
object TranscriptExport {
fun header(s: Session): String {
val mins = (s.durationSeconds / 60).toInt()
@@ -149,7 +131,6 @@ object TranscriptExport {
s.lines.forEachIndexed { i, l ->
val next = if (i + 1 < s.lines.size) s.lines[i + 1].t else l.t + 4
val end = maxOf(l.t + 1, minOf(next, l.t + 8))
- // Your own lines (我说) say so, as the record does.
val tag = if (l.speaker == "me") "[${Strings.L("同传")}] " else ""
b.append("${i + 1}\n${ts(l.t)} --> ${ts(end)}\n$tag${l.shown}\n")
l.dst?.takeIf { it != l.shown && it.isNotEmpty() }?.let { b.append("$it\n") }
@@ -158,8 +139,6 @@ object TranscriptExport {
return b.toString()
}
- /// A .docx with the Mac's layout: title, header, notes, then the transcript. Written as
- /// WordprocessingML by hand (a zip of three XML files): no library.
fun docx(s: Session): ByteArray {
val body = StringBuilder()
fun add(text: String, size: Double, bold: Boolean = false, color: String = "000000", after: Double = 4.0) {
@@ -214,6 +193,5 @@ object TranscriptExport {
return out.toByteArray()
}
- /// A file name for an export: the title without the characters file systems refuse.
fun fileName(s: Session, ext: String) = SessionStore.displayTitle(s).replace(Regex("[\\\\/:*?\"<>|]"), "-") + "." + ext
}
diff --git a/android/core/src/main/kotlin/cicada/FolderExport.kt b/android/core/src/main/kotlin/cicada/FolderExport.kt
index a8dc9de..3092621 100644
--- a/android/core/src/main/kotlin/cicada/FolderExport.kt
+++ b/android/core/src/main/kotlin/cicada/FolderExport.kt
@@ -6,25 +6,16 @@ import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
-/// 存到文件夹: the file a settled meeting becomes (docs/folder-export.md, the Mac's
-/// FolderExport.swift). The name and frontmatter are a contract with the Mac and the other ports
-/// (Tests/fixtures/folder-export); the body is 导出 Markdown's. The app writes it through SAF.
object FolderExportFormat {
- /// The record's own name: what the user called it, else the notes' title, else the imported
- /// file's name. Never displayTitle, which is localized and carries a date.
fun name(s: Session): String {
if (s.renamed ?: !s.title.startsWith("会议 ")) return s.title
s.notes?.title?.takeIf { it.isNotEmpty() }?.let { return it }
- // Swift's deletingPathExtension: ".hidden" keeps its name.
s.sourceFile?.let { f -> val dot = f.lastIndexOf('.'); return if (dot > 0) f.substring(0, dot) else f }
return ""
}
private val banned = "/\\:*?\"<>|#^[]".codePoints().toArray().toSet()
- /// A name every system accepts and a vault can link to: no path, wildcard or link characters,
- /// at most 120 UTF-8 bytes (vaults sync between systems, so the union of their rules). By code
- /// point, so an emoji is never cut in half.
fun safeName(name: String): String {
val spaced = StringBuilder()
name.codePoints().forEach { cp -> if (cp in banned || cp < 0x20) spaced.append(' ') else spaced.appendCodePoint(cp) }
@@ -50,7 +41,6 @@ object FolderExportFormat {
return if (safe.isEmpty()) date else "$date $safe"
}
- /// `stem.md`, or `stem 2.md`, `stem 3.md`… when a name is taken.
fun fileName(stem: String, taken: (String) -> Boolean): String {
var n = 1
while (true) {
@@ -60,8 +50,6 @@ object FolderExportFormat {
}
}
- /// A JSON-style double-quoted string, which YAML reads as is. Not Json.write's: that escapes "/"
- /// as the Mac's JSONEncoder does, and the frontmatter keeps it.
fun quote(s: String): String {
val b = StringBuilder("\"")
s.codePoints().forEach { cp ->
@@ -109,9 +97,6 @@ object FolderExportFormat {
DateTimeFormatter.ofPattern(pattern, Locale.ROOT).withZone(zone).format(at)
}
-/// What 存到文件夹 wrote, next to the records (FolderExport.json, as on the Mac): the folder (here a
-/// SAF tree URI), each record's file name, and the records still to write. `uris` is Android's own:
-/// each file's document URI, a hint only (a path-based provider changes it on rename).
class FolderExportIndex(
var folder: String = "",
val files: MutableMap<String, String> = mutableMapOf(),
diff --git a/android/core/src/main/kotlin/cicada/Json.kt b/android/core/src/main/kotlin/cicada/Json.kt
index e71bb8d..dd67e79 100644
--- a/android/core/src/main/kotlin/cicada/Json.kt
+++ b/android/core/src/main/kotlin/cicada/Json.kt
@@ -2,13 +2,6 @@ package cicada
import java.math.BigDecimal
-/// A small JSON reader and writer, so the engines need neither org.json (Android only, unsorted)
-/// nor a library. Values are Map<String, Any?> (insertion-ordered), List<Any?>, String, Long,
-/// Double, Boolean and null.
-///
-/// `write(pretty = true)` produces what the Mac's JSONEncoder writes with [.prettyPrinted,
-/// .sortedKeys], byte for byte: `"key" : value`, two-space indent, `[\n\n ]` for an empty array,
-/// `\/` for a slash, shortest doubles with no ".0", so a record read and written back is unchanged.
object Json {
class ParseException(message: String) : Exception(message)
@@ -117,8 +110,6 @@ object Json {
}
}
- /// `slashes = false` writes "/" as it is, like JSONEncoder's .withoutEscapingSlashes (the share
- /// document, ShareProjection.swift).
fun write(value: Any?, pretty: Boolean = true, slashes: Boolean = true): String {
val b = StringBuilder()
emit(b, value, pretty, 0, slashes)
@@ -134,7 +125,6 @@ object Json {
is Double -> b.append(number(v))
is Float -> b.append(number(v.toDouble()))
is Map<*, *> -> {
- // Sorted like Swift's .sortedKeys; nulls are left out, as Swift leaves out nil optionals.
val entries = v.entries.filter { it.value != null }.sortedBy { it.key as String }
if (entries.isEmpty()) { b.append(if (pretty) "{\n\n" + " ".repeat(depth) + "}" else "{}"); return }
b.append('{')
@@ -163,8 +153,6 @@ object Json {
}
}
- /// Shortest round-trip digits, as Swift prints a Double: "2" not "2.0", no exponent for the
- /// values records hold.
fun number(d: Double): String {
if (d.isNaN() || d.isInfinite()) return "0"
if (d == Math.rint(d) && Math.abs(d) < 1e15) return d.toLong().toString()
@@ -191,8 +179,6 @@ object Json {
}
}
-// Lenient accessors for decoded JSON.
-
@Suppress("UNCHECKED_CAST")
fun Any?.obj(): Map<String, Any?>? = this as? Map<String, Any?>
fun Any?.arr(): List<Any?> = this as? List<Any?> ?: emptyList()
diff --git a/android/core/src/main/kotlin/cicada/Ling.kt b/android/core/src/main/kotlin/cicada/Ling.kt
index 80a4591..410fb7d 100644
--- a/android/core/src/main/kotlin/cicada/Ling.kt
+++ b/android/core/src/main/kotlin/cicada/Ling.kt
@@ -7,8 +7,6 @@ import java.net.SocketTimeoutException
import java.net.URL
import java.util.Base64
-/// Turns the key into bytes on disk and back. Android wraps it with a Keystore key (this app
-/// only); the plain one is for the CLI and tests.
interface KeyProtector {
val tag: String
fun protect(data: ByteArray): ByteArray
@@ -21,10 +19,6 @@ object PlainProtector : KeyProtector {
override fun unprotect(data: ByteArray) = data
}
-/// The user's AI keys, one file per service in the app's private folder (`ling-api-key`,
-/// `ai-key-<service>`, as on the Mac): never in settings, logs or exports. `service` says which
-/// one is in use; switching services keeps the others' keys. On Android each file holds
-/// "keystore:" + base64 of the Keystore-sealed bytes. `file` pins one file (the CLI reads the Mac's).
class AIKey(private val protector: KeyProtector, private val file: File? = null, var service: () -> String = { "ling" }) {
val path: File get() = file ?: Paths.keyFile(service())
private val cache = HashMap<String, String?>()
@@ -70,14 +64,11 @@ class AIKey(private val protector: KeyProtector, private val file: File? = null,
cache[p.path] = null
}
- /// Reads the files again (a dev build's key pushed in with adb).
@Synchronized fun reload() { cache.clear() }
- /// Another key file in the same store, sealed the same way (the custom service's notes key).
fun sibling(service: String) = AIKey(protector, service = { service })
companion object {
- /// "sk-••••••••••••3f9a" for display.
fun masked(key: String) = if (key.length <= 8) "sk-…" else key.take(3) + "•".repeat(12) + key.takeLast(4)
}
}
@@ -86,31 +77,21 @@ enum class Priority { Speak, Translate, Notes }
enum class KeyState { None, Unchecked, Checking, Ok, Invalid, Unreachable }
-/// 继续 on the key step with a key already saved (the guide opened again from 设置): an empty field,
-/// or the saved key again, keeps it, unless it was found invalid. Onboarding opens past the key step
-/// on the same condition.
fun keepsSavedKey(typed: String, saved: String?, state: KeyState) =
saved != null && state != KeyState.Invalid && (typed.isEmpty() || typed == saved)
-/// `retryAfter`: seconds the service asked us to wait (a 429's Retry-After), when it said.
class LingException(val kind: Kind, val status: Int = 0, val retryAfter: Double? = null) : Exception(if (kind == Kind.Http) "http$status" else kind.name) {
enum class Kind { NoKey, InvalidKey, RateLimited, Hijacked, Timeout, Http, Network, Parse }
}
-/// Time for LingClient's start gate, in ms; tests hand in one that moves on by itself.
open class GateClock {
open fun now(): Long = System.currentTimeMillis()
- /// Waits on `lock` (held) for `ms`, or until notified; 0 is until notified.
open fun wait(lock: Object, ms: Long) = lock.wait(ms)
}
-/// How requests leave the app: HttpURLConnection, or a fake in tests.
interface Transport {
- /// `retryAfter`: the Retry-After header, as sent.
class Response(val status: Int, val body: String, val retryAfter: String? = null)
- /// A reply read as it arrives (speech): its type and the open body, which the caller closes.
class Stream(val status: Int, val contentType: String, val body: InputStream)
- /// Throws SocketTimeoutException on a timeout and IOException when the network fails.
fun send(url: String, method: String, body: String?, headers: Map<String, String>, timeoutMs: Int): Response
fun stream(url: String, body: String, headers: Map<String, String>, timeoutMs: Int): Stream =
send(url, "POST", body, headers, timeoutMs).let { Stream(it.status, "application/json", it.body.byteInputStream()) }
@@ -152,53 +133,33 @@ object UrlTransport : Transport {
}
}
-/// One instance for the app, for whichever AI service the settings name (`config`, read on every
-/// call). Request *starts* go through one gate in priority order: Ling allows about 2 a second
-/// across every model (≥ 0.6 s apart, overlapping is fine), the aggregators far more. Ling's
-/// gateway shapes every call (see Ling.swift): thinking is always disabled, and the content goes in
-/// the system message with a fixed user instruction, because a question-like user message gets a
-/// search essay back; such replies are dropped. The other services get the same messages.
-/// Calls block: run them off the main thread.
class LingClient(
private val key: AIKey,
private val transport: Transport = UrlTransport,
val config: () -> AIConfig = { Providers.configFrom(AppSettings()) },
private val clock: GateClock = GateClock(),
- /** The custom service's notes server's own key (另一个服务): `ai-key-custom-notes`, as on the Mac. */
private val notesKeys: AIKey = key.sibling(NOTES_KEY),
) {
companion object {
- /// The key file of the custom service's notes server.
const val NOTES_KEY = "custom-notes"
val BASE = Providers.LING.base!!
val DEFAULT_MODEL = Providers.LING.textModels[0].id
val AUDIO_MODEL = Providers.LING.hearModels[0].id
- /// A chat reply's text holds a JSON object (a fence or a sentence around it is fine).
fun answersJSON(text: String?): Boolean {
if (text == null) return false
val a = text.indexOf('{'); val z = text.lastIndexOf('}')
return a in 0 until z && Json.parseObject(text.substring(a, z + 1)) != null
}
- /// Seconds before each retry of a 429 (Ling.swift › retryWaits). Notes retry a few times; the
- /// rest fail fast so the caller can fall back, except heard audio. A meeting's: there a lost
- /// reply loses the words, and Ling's 429s came in runs of up to ~10 s (two in a row lost a line
- /// with one retry, about 2 a minute in 2026-11 testing), so it keeps at it for about 15 s. What
- /// the user says (Speak) retries once: late is worse than a short "try again". `patient`
- /// (the final notes) keeps at it for about a minute: a model limited upstream (OpenRouter's
- /// Ling 3.1 by DeepInfra, 2026-11) came back after ~15 s, and a meeting left without its
- /// notes is worse than notes a little late.
fun retryWaits(priority: Priority, audio: Boolean = false, patient: Boolean = false): List<Double> = when {
priority == Priority.Notes -> if (patient) listOf(1.0, 2.0, 4.0, 8.0, 16.0, 30.0) else listOf(1.0, 2.0, 4.0)
audio -> if (priority == Priority.Translate) listOf(1.0, 2.0, 4.0, 8.0) else listOf(1.0)
else -> emptyList()
}
- /// Longest Retry-After worth waiting for; longer is an outage, not a busy moment.
const val MAX_PAUSE = 30.0
- /// A Retry-After header in seconds: a number, or an HTTP date. Null when absent or unreadable.
fun retryAfterSeconds(value: String?, nowMs: Long = System.currentTimeMillis()): Double? {
val v = value?.trim()?.takeIf { it.isNotEmpty() } ?: return null
v.toDoubleOrNull()?.let { return maxOf(0.0, it) }
@@ -207,19 +168,13 @@ class LingClient(
maxOf(0.0, (at - nowMs) / 1000.0)
} catch (_: java.time.format.DateTimeParseException) { null }
}
- /// Ming, Gemini TTS and Kokoro all speak 24 kHz mono 16-bit.
const val TTS_RATE = 24000
- /// Failures of a model rather than of the service or the key: the key still works.
val MODEL_REASONS = setOf(AICheck.Reason.Busy, AICheck.Reason.Deaf, AICheck.Reason.NoModel, AICheck.Reason.NoJSON)
- // Search essays (Ling.swift), and the canned refusal some audio prompts get.
private val HIJACK_PREFIXES = listOf("根据现有检索证据", "暂未找到足够可靠的信息", "根据检索", "作为一个人工智能语言模型")
- /// Tests only: overrides the service's spacing.
@Volatile var spacing: Double? = null
- /// A short quiet WAV (16 kHz mono 16-bit), to ask a model whether it takes audio at all.
fun silenceWav(seconds: Double = 0.5): ByteArray = Wav.bytes(ShortArray((16000 * seconds).toInt()))
- /// The samples of a WAV (its `data` chunk); the bytes themselves when there's no header.
fun pcmFromWav(wav: ByteArray): ByteArray {
if (wav.size < 12 || String(wav, 0, 4, Charsets.US_ASCII) != "RIFF") return wav
var at = 12
@@ -235,22 +190,15 @@ class LingClient(
@Volatile var keyState = if (currentKey() == null) KeyState.None else KeyState.Unchecked; private set
@Volatile var rateLimitedAt: Long? = null; private set
- /// Step by step, where the service stands (`keyState` is its short form for older callers).
@Volatile var aiCheck = AICheck(); private set
- /// The last time the service's voice spoke (or failed to) for 我说: (ok, epoch ms).
@Volatile var lastVoice: Pair<Boolean, Long>? = null; private set
@Volatile var textCatalog: List<String> = emptyList(); private set
@Volatile var hearCatalog: List<String> = emptyList(); private set
- /// Reads this phone's proxy settings to word the "can't reach" hint (never used to connect).
@Volatile var proxyHint: (() -> AICheck.ProxyHint)? = null
- /// Debug control only: the next checks end this way (for screenshots of every state).
@Volatile var simulateCheck: AICheck.Reason? = null
- /// Debug control only: report this OpenRouter balance instead of the real one.
@Volatile var simulateBalance: Double? = null
private val checkLock = Any()
- /// Which servers refused `chat_template_kwargs` once (by host): leave it out there until settings change.
@Volatile private var noTemplateKwargs: Set<String> = emptySet()
- /// Notes' own server's text models from its `/models` (empty while notes share translation's address).
@Volatile var notesCatalog: List<String> = emptyList(); private set
private val listeners = mutableListOf<() -> Unit>()
@@ -259,7 +207,6 @@ class LingClient(
val provider: Provider get() = config().provider
- /// The key for the service in use. A custom service on this phone or the local network may need none: "".
fun currentKey(): String? {
val c = config()
val k = key.read()
@@ -269,81 +216,55 @@ class LingClient(
val hasKey get() = currentKey() != null
- /// The key notes are sent with: with 另一个服务, their own key file if there is one, else the
- /// translation key ("不填就用上面的 key").
fun notesKey(): String? {
if (config().notesOwnService) notesKeys.read()?.let { return it }
return currentKey()
}
- /// Notes have a key file of their own (另一个服务 only).
val notesHasOwnKey get() = config().notesOwnService && notesKeys.read() != null
- /// Notes' own key (另一个服务), saved; the caller checks again.
fun setNotesKey(raw: String): Boolean = raw.trim().isNotEmpty() && notesKeys.save(raw)
- /// Notes go back to the translation key.
fun removeNotesKey() = notesKeys.remove()
val usable get() = hasKey && keyState != KeyState.Invalid
- /// The service's own voice reads my words to the other side (otherwise the phone's voice).
val speaks get() = usable && config().hasVoices
- /// The user's own voice: only Ling clones.
val clones get() = speaks && config().provider.clones
- /// Whether the hear model takes audio: false once it refused (a check or a meeting), true once
- /// it heard, null until then (always true on Ling: Ming).
val hears: Boolean? get() = when (val s = aiCheck[AICheck.StepID.Hear]) {
is AICheck.State.Ok, AICheck.State.Busy -> true
is AICheck.State.Fail -> if (s.reason == AICheck.Reason.Deaf) false else null
else -> if (config().isLing) true else null
}
- /// How long the last good check's newest request took, in seconds.
val seconds: Double? get() = aiCheck.steps.mapNotNull { (it.state as? AICheck.State.Ok)?.seconds }.lastOrNull()
- /// Listening and 我说 can work: the hear model wasn't found to refuse audio.
val canHear get() = usable && hears != false && config().let { it.hearModel.isNotEmpty() && it.hearBase != null }
- /// The service's name for messages ("这个服务" for a custom address, localized) and its host.
val serviceName: String get() = provider.let { if (it.id == "custom") Strings.L("这个服务") else it.name }
val serviceHost: String get() = host(config().base ?: provider.base)
- /// Who a status line names: a custom service by its address, which says more than 这个服务
- /// and reads right in "The … key doesn't work".
val serviceLabel: String get() = serviceHost.let { if (provider.id == "custom" && it.isNotEmpty()) it else serviceName }
- /// Where the hear model is asked: the service's host unless a custom service names its own.
val hearHost: String get() = config().let { c -> if (c.hearsElsewhere) host(c.hearBase) else serviceHost }
- /// Who a line about hearing names (连不上 …, … 的 key 无效): a custom service by the address it
- /// hears at, as the live screen's banner does, not 其他(兼容 OpenAI).
val hearName: String get() = if (provider.id == "custom") hearHost.ifEmpty { provider.name } else provider.name
private fun host(base: String?) = base?.let { try { java.net.URI(it).host } catch (_: Exception) { null } } ?: ""
- /// The failed (or busy) step's sentence, for the screens; a hear model on its own server that
- /// can't be reached names that server.
fun checkMessage(): String? = config().let {
val host = if (aiCheck.failure?.step == AICheck.StepID.Hear) hearHost else serviceHost
aiCheck.message(serviceLabel, host, it.textModel, it.hearModel)
}
- /// The server that can't be reached is on this phone or the local network: a proxy has nothing
- /// to do with it, so there's no proxy hint.
fun unreachableNearby(r: AICheck = aiCheck): Boolean {
val c = config()
val base = if (r.failure?.step == AICheck.StepID.Hear) c.hearBase else c.base
return r.failure?.reason == AICheck.Reason.Unreachable && base != null && Providers.isNearby(base)
}
- /// AICheck.classify, except that a hear model on its own server that can't be reached fails
- /// the hear step: the text model's address is fine.
private fun classify(e: LingException, step: AICheck.StepID, c: AIConfig): AICheck.Failure? {
val f = AICheck.classify(e, step) ?: return null
return if (step == AICheck.StepID.Hear && c.hearsElsewhere && f.reason == AICheck.Reason.Unreachable)
AICheck.Failure(AICheck.StepID.Hear, AICheck.Reason.Unreachable, null) else f
}
- /// Something only the user can fix, in one line ("Ling 的 key 用不了 · 修好之前听不了"): the
- /// listening notification and the live screens. Null without a key (onboarding asks for it).
val blocking: String? get() {
if (!hasKey) return null
val (what, stops) = config().let { aiCheck.blocking(serviceLabel, it.textModel, it.hearModel) } ?: return null
return what.trimEnd('。', '.') + " · " + stops
}
- /// The key, the service or its models changed: forget what the last check found.
fun keyChanged() {
key.reload()
notesKeys.reload()
@@ -356,14 +277,7 @@ class LingClient(
changed()
}
- /// The cheapest requests that prove each step: Ling's tiny model, else one token from the text
- /// model (OpenRouter also reads its key info and credits, for the balance). A custom service
- /// translates one real sentence instead, timed, to catch a model that thinks before every
- /// answer, and must also return JSON (the notes need it). Another service's hear model must take audio
- /// (half a second of silence), and the model list then tells whether both models still exist.
fun check(): KeyState {
- // One at a time (a service change and a key import come close together), and the probes'
- // own replies are not passive results.
synchronized(checkRun) {
checking++
try { return runCheck() } finally { checking-- }
@@ -386,28 +300,21 @@ class LingClient(
return finishCheck(r.fail(AICheck.StepID.Reach, AICheck.Reason.BadAddress, reached = false), c)
if (AICheck.owner(k)?.second == true)
return finishCheck(r.fail(AICheck.StepID.Key, AICheck.Reason.MgmtKey, reached = false), c)
- // The probes below go through chat(), which reports to observe(): it waits while running.
var step = AICheck.StepID.Text
try {
var started = System.nanoTime()
if (c.isLing) {
chat("Reply with OK.", "Reply.", Priority.Speak, maxTokens = 5, timeout = 10.0, model = "Ling-3.0-tiny")
- // Ming hears on every Ling key: nothing to probe.
r = r.pass(AICheck.StepID.Text, (System.nanoTime() - started) / 1e9).pass(AICheck.StepID.Hear, null)
} else {
if (c.textModel.isEmpty()) throw LingException(LingException.Kind.Http, 404)
if (c.provider.id == "custom") {
- // A real sentence, the way a meeting translates: one token says nothing about a
- // model that thinks for six seconds before every answer.
var thinks = false
var answered = false
try {
chat("Translate the text into Simplified Chinese. Reply with the translation only.\n\nWe will ship the new version on Friday after the design review.",
"Translate.", Priority.Speak, maxTokens = 120, timeout = 30.0) { answered = true; thinks = AIConfig.thought(it) }
} catch (e: LingException) {
- // A model that thinks can spend all its tokens on thinking and answer nothing:
- // it did answer, slowly, and that is what this step is here to say (the Mac
- // reads only the reply's thinking, not its words).
if (!answered || (e.kind != LingException.Kind.Parse && e.kind != LingException.Kind.Hijacked)) throw e
}
val seconds = (System.nanoTime() - started) / 1e9
@@ -418,7 +325,6 @@ class LingClient(
}
if (c.provider.id == "openrouter") r = r.copy(balance = openRouterBalance(c, k))
if (c.notesApart) {
- // Notes at their own model or server: their failure is theirs, translation goes on.
r = r.copy(notes = AICheck.Notes.Running)
synchronized(checkLock) { aiCheck = r }
changed()
@@ -429,8 +335,6 @@ class LingClient(
chat(ask, "Reply.", Priority.Speak, json = true, maxTokens = 20, timeout = 30.0, jsonFallback = false)
} catch (e: LingException) {
if (e.kind != LingException.Kind.Http) throw e
- // JSON mode refused (some hosts of a model do): meetings then ask without it, so
- // what counts is whether the model still answers with a JSON object.
val said = try { chat(ask, "Reply.", Priority.Speak, maxTokens = 20, timeout = 30.0) } catch (_: LingException) { null }
if (!answersJSON(said)) r = r.fail(AICheck.StepID.Text, AICheck.Reason.NoJSON, e.status)
}
@@ -444,7 +348,6 @@ class LingClient(
chat("Transcribe the audio.", "Reply with what is said, or NONE.", Priority.Speak, maxTokens = 10, timeout = 20.0,
model = c.hearModel, audio = silenceWav())
} catch (e: LingException) {
- // Heard, and answered with something we drop anyway: it takes audio.
if (e.kind != LingException.Kind.Hijacked && e.kind != LingException.Kind.Parse) throw e
}
r = r.pass(AICheck.StepID.Hear, (System.nanoTime() - started) / 1e9)
@@ -455,7 +358,6 @@ class LingClient(
if (f != null) {
r = if (f.reason == AICheck.Reason.Busy) r.pass(f.step, null).with(f.step, AICheck.State.Busy) else r.fail(f.step, f.reason, f.code)
} else if (e.kind == LingException.Kind.Hijacked || e.kind == LingException.Kind.Parse) {
- // A reply came back: the service and key are fine, the words just weren't usable.
r = r.pass(step, null)
}
} catch (e: InterruptedException) {
@@ -467,10 +369,6 @@ class LingClient(
val listed = fetchCatalog()
val hearOwn = hearListed
if (listed != null) {
- // A model the service no longer lists fails here, before a meeting finds out. On a custom
- // service, one a real sentence just went through exists whatever the list says (an alias,
- // a name typed by hand). A hear model on its own server isn't on this list: that server's
- // own was read for it.
val hearing = if (c.hearsElsewhere) hearOwn else listed.second
val proven = c.provider.id == "custom" && r[AICheck.StepID.Text] is AICheck.State.Ok
if (!proven && c.textModel !in listed.first) r = r.fail(AICheck.StepID.Text, AICheck.Reason.NoModel)
@@ -480,8 +378,6 @@ class LingClient(
return finishCheck(r, c)
}
- /// Notes' own model or server: one JSON request the way a meeting's notes ask (straight to the
- /// server: a check doesn't wait out 429s), then, at another address, its model list for the menu.
private fun checkNotes(config: AIConfig): AICheck.Notes {
if (config.notesBadAddress) return AICheck.Notes.Fail(AICheck.Reason.BadAddress)
val c = config.forNotes
@@ -500,7 +396,6 @@ class LingClient(
AICheck.Notes.Ok(seconds())
} catch (e: LingException) {
if (e.kind == LingException.Kind.Http && (e.status == 400 || e.status == 422)) {
- // JSON mode refused: meetings then ask without it, so what counts is a JSON object back.
json.remove("response_format")
val said = try {
postChat(url, json, k, 60.0, notes = true)["choices"].arr().firstOrNull().obj()?.get("message").obj()?.get("content").str()
@@ -531,7 +426,6 @@ class LingClient(
return keyState
}
- /// OpenRouter's dollars left; null when it can't tell (never fails the check).
private fun openRouterBalance(c: AIConfig, k: String): Double? {
val base = c.base ?: return null
fun get(path: String) = try {
@@ -540,8 +434,6 @@ class LingClient(
return AICheck.balance(get("key"), get("credits"))
}
- /// The short form older callers read: Invalid stops every request; Unreachable is any failure
- /// of the service itself. A missing or deaf model is a model problem: the key still works.
private fun syncKeyState() {
if (!hasKey) { keyState = KeyState.None; return }
val c = aiCheck
@@ -554,12 +446,9 @@ class LingClient(
}
}
- /// A real request (hearing, notes, translation) came back: keep the steps current without a
- /// check. One server error in a meeting isn't worth repainting the settings for.
private fun observe(failure: LingException?, seconds: Double = 0.0, audio: Boolean = false, notes: Boolean = false) {
if (!hasKey || simulateCheck != null) return
if (notes) {
- // Notes at their own model or server: theirs alone, translation's steps are untouched.
val now = if (failure != null) {
val f = AICheck.classify(failure, AICheck.StepID.Text) ?: return
if (f.reason == AICheck.Reason.ServerError) return
@@ -607,17 +496,12 @@ class LingClient(
}
}
- /// The network came back (or changed) while the service was unreachable: look again. Blocks.
fun networkChanged() {
if (!hasKey || aiCheck.failure?.reason != AICheck.Reason.Unreachable || aiCheck.running) return
Log.d("ai: network changed while unreachable, checking again")
check()
}
- /// The service's models, for the model pickers: those that chat, and those that hear. Quietly
- /// just the recommended ones when the service has no `/models`. Returns every listed id and,
- /// when the reply says which take audio, those (to tell whether the chosen models exist). A
- /// hear model on its own server: that server's list fills the hear picker and `hearListed`.
fun fetchCatalog(): Pair<Set<String>, Set<String>?>? {
val c = config()
val k = currentKey() ?: return null
@@ -637,7 +521,6 @@ class LingClient(
return listed to AICheck.listedHearing(body)
}
- /// Notes' own address's text models, for its menu. Quietly empty when it has no `/models`.
fun fetchNotesCatalog() {
val c = config()
val base = c.forNotes.base
@@ -649,8 +532,6 @@ class LingClient(
changed()
}
- /// Which models the hear model's own server says take audio (null: it says nothing, or the
- /// hear model shares the text model's address).
@Volatile private var hearListed: Set<String>? = null
private fun models(base: String, k: String): String? {
@@ -658,14 +539,6 @@ class LingClient(
return if (res.status == 200) res.body else null
}
- /// One chat completion. `content` goes in the system message, `instruction` is the fixed user
- /// message, `audio` (of `audioType`) goes before it for the hear model. Notes and heard audio
- /// retry 429s with backoff (retryWaits); the rest fail fast so the caller can fall back.
- /// `patient` (the final notes) keeps retrying for about a minute. A 429 holds every request
- /// start for a while (rateLimited), and a retry keeps its place in the queue, so lines stay in order.
- /// Audio goes to the hear model's address (a custom service may name its own). `reply` sees the
- /// whole reply (the check reads whether the model thought). A JSON request refused with 400 is
- /// asked again without JSON mode unless `jsonFallback` is off (the check asks again itself).
fun chat(
content: String, instruction: String, priority: Priority, json: Boolean = false,
maxTokens: Int = 1024, timeout: Double = 30.0, model: String? = null, audio: ByteArray? = null,
@@ -673,8 +546,6 @@ class LingClient(
reply: ((Map<String, Any?>) -> Unit)? = null,
): String {
val all = config()
- // Notes (实时纪要, 说话人) go to their own model or server when set; never with their key to
- // translation's server because their own address can't be used.
val notesSide = priority == Priority.Notes && audio == null && all.notesApart
if (notesSide && all.notesBadAddress) throw LingException(LingException.Kind.NoKey)
val c = if (notesSide) all.forNotes else all
@@ -697,7 +568,6 @@ class LingClient(
var attempt = 1
var ticket: Long? = null
while (true) {
- // One that wouldn't retry fails at once while the service is cooling down: its caller falls back.
ticket = acquire(priority, c.provider.spacing, gate, ticket, failIfPaused = waits.isEmpty())
val started = System.nanoTime()
try {
@@ -705,8 +575,6 @@ class LingClient(
postChat(base + "chat/completions", body, k, timeout, notesSide)
} catch (e: LingException) {
if (!jsonFallback || e.kind != LingException.Kind.Http || e.status != 400 || body.remove("response_format") == null) throw e
- // Some hosts of a model refuse JSON mode (on OpenRouter, Novita for Ling 3.1 Flash)
- // while the model answers JSON anyway: the prompt asks for it, the parsers find it.
Log.d("ling: $priority JSON mode refused (400), asking again without it")
postChat(base + "chat/completions", body, k, timeout, notesSide)
}
@@ -715,7 +583,6 @@ class LingClient(
val text = choice?.get("message").obj()?.get("content").str() ?: throw LingException(LingException.Kind.Parse)
val finish = choice?.get("finish_reason").str()
val trimmed = text.trim()
- // Ling's search essays come without a finish reason; other services may simply omit it.
if ((finish == null && c.isLing) || HIJACK_PREFIXES.any { trimmed.startsWith(it) }) {
Log.d("ling: $priority search-style reply dropped")
throw LingException(LingException.Kind.Hijacked)
@@ -726,7 +593,6 @@ class LingClient(
observe(null, (System.nanoTime() - started) / 1e9, audio = audio != null, notes = notesSide)
return trimmed
} catch (e: LingException) {
- // A reply we drop (a search essay) still proves the service answers.
observe(e.takeIf { it.kind != LingException.Kind.Hijacked }, audio = audio != null, notes = notesSide)
if (e.kind != LingException.Kind.RateLimited) throw e
val wait = rateLimited(if (waits.isEmpty()) 1.0 else waits[minOf(attempt, waits.size) - 1], e.retryAfter, gate)
@@ -737,15 +603,8 @@ class LingClient(
}
}
- /// The service's voice for `text`, handed to `onPcm` as raw 24 kHz mono 16-bit PCM while it
- /// arrives. `voice` is one of the service's (another, e.g. a Ming name, becomes its first);
- /// `language` is Ming's language_id, Ling only; `reference` (a WAV data URI and what it says,
- /// VoiceReference) clones the user's voice instead, Ling only. Replies come three ways and all
- /// are read: server-sent base64 chunks (Ling, ZenMux), raw PCM (OpenRouter), or one JSON
- /// `{"audio": <WAV>}`.
fun speech(text: String, voice: String? = null, language: String? = null, timeout: Double = 20.0,
reference: Pair<String, String>? = null, onPcm: (ByteArray) -> Unit) {
- // The voice isn't part of a check (it costs money): its real outcome is what 现在能用的 says.
try {
speak(text, voice, language, if (reference != null) maxOf(timeout, 30.0) else timeout, reference, onPcm)
lastVoice = true to System.currentTimeMillis(); changed()
@@ -753,7 +612,6 @@ class LingClient(
lastVoice = false to System.currentTimeMillis(); changed()
throw e
}
- // Anything else came from onPcm: the phone stopped it on purpose, not a failure.
}
private fun speak(text: String, voice: String?, language: String?, timeout: Double, reference: Pair<String, String>?, onPcm: (ByteArray) -> Unit) {
@@ -761,8 +619,6 @@ class LingClient(
val c = config()
val voiceBase = c.voiceBase
if (!c.hasVoices || voiceBase == null) throw LingException(LingException.Kind.NoKey)
- // Only Ling clones: elsewhere a reference would read in someone else's voice, so refuse
- // and let the caller fall back.
if (reference != null && !c.provider.clones) throw LingException(LingException.Kind.NoKey)
val body = linkedMapOf<String, Any?>("model" to c.voiceModel, "input" to text, "response_format" to "pcm")
if (c.isLing) {
@@ -771,7 +627,6 @@ class LingClient(
else body["voice"] = voice ?: "UK_Charlotte"
if (language != null) body["language_id"] = language
} else {
- // OpenRouter documents no `stream` (it streams the bytes anyway); ZenMux needs it.
if (c.provider.id != "openrouter") body["stream"] = true
val ids = c.voices.map { it.id }
body["voice"] = if (voice in ids) voice else ids.firstOrNull() ?: c.customVoice ?: "Kore"
@@ -810,13 +665,12 @@ class LingClient(
val pcm = pcmFromWav(Base64.getDecoder().decode(audio)); bytes += pcm.size; onPcm(pcm)
}
else -> {
- val buf = ByteArray(4800) // 0.1 s at 24 kHz: playback starts early
+ val buf = ByteArray(4800)
var odd: Byte? = null
while (true) {
val n = input.read(buf)
if (n < 0) break
if (n == 0) continue
- // Whole samples only: a chunk can end mid-sample.
var chunk = if (odd != null) byteArrayOf(odd) + buf.copyOf(n) else buf.copyOf(n)
odd = if (chunk.size % 2 == 1) chunk.last() else null
if (odd != null) chunk = chunk.copyOf(chunk.size - 1)
@@ -839,12 +693,6 @@ class LingClient(
return h
}
- /// A chat completion. A custom server that refuses `chat_template_kwargs` (a strict gateway
- /// answers 400 or 422 to fields it doesn't know) is asked again without it, and, when that
- /// works, isn't sent it again until settings change. A second refusal was about something else
- /// (a hear model that takes no audio, no JSON mode): the field stays, in `body` too, so a
- /// request asked again without JSON mode still turns thinking off.
- /// `notes`: a request to the notes' own model or server (a refused key is theirs, not translation's).
private fun postChat(url: String, body: Map<String, Any?>, k: String, timeout: Double, notes: Boolean = false): Map<String, Any?> {
try {
return post(url, Json.write(body, pretty = false), k, timeout, notes)
@@ -883,26 +731,18 @@ class LingClient(
return try { Json.parse(res.body).obj() } catch (_: Json.ParseException) { null } ?: throw LingException(LingException.Kind.Parse)
}
- // Start gate: request starts ≥ `spacing` apart, the most urgent waiting one first, none while
- // the server is cooling down after a 429. One per server (by host): notes on another server
- // don't wait behind translation, and a 429 there doesn't hold translation back.
-
private class Ticket(val priority: Priority, val seq: Long)
private class StartGate {
val lock = Object()
val waiting = mutableListOf<Ticket>()
var lastStart = Long.MIN_VALUE / 2
- /// After a 429 no request starts here before this (`rateLimited`).
var pausedUntil = 0L
}
private val gates = HashMap<String, StartGate>()
private val seq = java.util.concurrent.atomic.AtomicLong()
- /// The gate of the server at `base`.
private fun gate(base: String?): StartGate = synchronized(gates) { gates.getOrPut(host(base)) { StartGate() } }
- /// Waits for this request's turn to start. `ticket` is a retry's first one, which keeps its
- /// place ahead of requests queued after it. Returns the ticket.
private fun acquire(priority: Priority, serviceSpacing: Double, g: StartGate, ticket: Long? = null, failIfPaused: Boolean = false): Long {
val spacing = LingClient.spacing ?: serviceSpacing
synchronized(g.lock) {
@@ -928,10 +768,6 @@ class LingClient(
}
}
- /// After a 429: no request starts at that server for `backoff` seconds, or as long as it asked
- /// (Retry-After; Ling sends none), plus a little jitter. The queue waits at the gate instead of
- /// each request spending its retries on the same limit. Null when that is over MAX_PAUSE (the
- /// gate still holds for MAX_PAUSE): an outage, not a busy moment.
private fun rateLimited(backoff: Double, retryAfter: Double?, g: StartGate): Double? {
val wait = maxOf(backoff, retryAfter ?: 0.0) + Math.random() * 0.5
synchronized(g.lock) {
diff --git a/android/core/src/main/kotlin/cicada/ListenEngine.kt b/android/core/src/main/kotlin/cicada/ListenEngine.kt
index f37968c..1a60ead 100644
--- a/android/core/src/main/kotlin/cicada/ListenEngine.kt
+++ b/android/core/src/main/kotlin/cicada/ListenEngine.kt
@@ -5,12 +5,6 @@ import java.util.concurrent.Future
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
-/// Listening end to end: audio → segments → the AI service's hear model (Ming on Ling: language,
-/// original, translation in one call) → lines in the record, plus live notes. UI-free; the app shows the record and listens to
-/// `onChange` (called on worker threads: post to the main thread).
-///
-/// Ming takes ~2.2 s whatever the segment's length, so segments overlap in flight: request starts
-/// still go through LingClient's gate, and lines are delivered in segment order.
class ListenEngine(
private val ling: LingClient,
private val translator: Translator,
@@ -34,17 +28,11 @@ class ListenEngine(
private var candidate: String? = null
private var candidateVotes = 0
private val listeners = mutableListOf<() -> Unit>()
- /// One thread records delivered lines, so lines (and their voices) go in strictly in segment order.
private val deliverLock = Any()
- /// 说话人识别 (Speakers.kt), set by the app; null or unavailable leaves every line 对方.
@Volatile var speakers: SpeakerTagger? = null
- /// 改正听错的词, set by the app: the word list's forms fixed as lines arrive, and the service's
- /// proposals with each finished line's translation (null: no fixing at all).
@Volatile var fixes: LiveFixes? = null
- /// A line got a voice (the meeting's id): the app asks Ling for names.
@Volatile var onVoice: ((String) -> Unit)? = null
- /// Voiceprints one at a time beside Ming (each already uses up to four cores).
private val voicePool = Executors.newSingleThreadExecutor { r -> Thread(r, "Voiceprints").apply { isDaemon = true } }
private val voiceprints = HashMap<Int, Future<FloatArray?>>()
private var voicesWaiting = 0
@@ -52,32 +40,18 @@ class ListenEngine(
@Volatile var listening = false; private set
@Volatile var sessionId: String? = null; private set
- /// What this meeting is heard from ("playback", "mic", "file").
@Volatile var sourceKind: String? = null; private set
- /// The meeting's language so far (null until Ming has heard something).
val spoken: String? get() = synchronized(gate) { hint }
- /// Segments sent and not yet back: the UI shows "…" while this is above zero.
val pending: Int get() = synchronized(gate) { segments.size }
- /// The last error worth showing ("Ling key 无效", "连不上 ZenMux"), cleared by the next good reply.
@Volatile var problem: String? = null; private set
- /// What kind it is ("key", "busy", "network"), for the screens to pick an icon by.
@Volatile var problemKind: String? = null; private set
- /// Stretches in a row the service answered with a 5xx (under `gate`).
private var serverErrors = 0
@Volatile var level = 0.0; private set
- /// Seconds of audio heard this meeting (the capture is alive while this grows).
@Volatile var heardSeconds = 0.0; private set
- /// The loudest recent level: 0 for a while means the source is silent (e.g. an app that blocks capture).
@Volatile var peak = 0.0; private set
- /// Compresses a segment before upload (the app sets AAC: WAV is ~10x larger, ~146 MB an hour
- /// of speech on mobile data). Null or a throw falls back to WAV, which Ming always takes. Only
- /// for Ling: the other services' `input_audio` is WAV (Qwen, Gemini and Doubao were tested
- /// with WAV only), so they cost the bigger upload.
@Volatile var encoder: (ShortArray) -> Clip? = { null }
- // The notes' language is read from 设置 when they're written, from launch on: notes generated
- // for an old meeting before anything was listened to used to fall back to Simplified Chinese.
init {
translator.glossary = { notes.glossary() }
notes.language = { Languages.englishName(settings.notesCode) }
@@ -89,26 +63,17 @@ class ListenEngine(
val target: String get() = settings.targetCode
private val END = ShortArray(0)
- // Hold and release go through the audio queue, so buffers recorded before the press stay the
- // other side's and those recorded before the release are still mine.
private val HOLD = ShortArray(0)
private val RELEASE = ShortArray(0)
// MARK: 我说 (面对面 only): hold, say something, release → Ming → spoken in their language.
- /// Words were recognised, theirs or mine (a line arrived or grew): what MeetingEndWatch counts.
var onWords: (() -> Unit)? = null
- /// Speaks my words to the person in front of me: `text` is always a translation (see `speakable`).
var onSaid: ((text: String, lang: String) -> Unit)? = null
- /// The button is down.
@Volatile var holding = false; private set
- /// My words are at Ming.
@Volatile var saying = false; private set
- /// Set while the phone speaks: the mic would hear the translation as the other side, so the
- /// segmenter gets silence instead.
@Volatile var muted = false
- /// Why the last press said nothing ("没听清,再说一次"); cleared by the next press.
@Volatile var sayProblem: String? = null; private set
private val mine = ArrayList<ShortArray>()
private var holdStart = 0.0
@@ -116,8 +81,6 @@ class ListenEngine(
val canSay: Boolean get() = listening && sourceKind == "mic"
- /// Who I'm talking to speaks the meeting's language; before they have said anything (or when
- /// it is mine), English, or Chinese for an English speaker (the Mac always falls back to English).
val theirLanguage: String get() {
val me = target
val heard = spoken
@@ -133,18 +96,13 @@ class ListenEngine(
changed()
}
- /// The app couldn't speak a translation ("手机没有这个语言的语音").
fun sayFailed(why: String) { sayProblem = why; changed() }
- /// Debug: audio as if the source had just delivered it (the emulator's microphone is silent).
fun inject(pcm: ShortArray) {
var i = 0
while (i < pcm.size) { audio?.offer(pcm.copyOfRange(i, minOf(pcm.size, i + 1600))); i += 1600 }
}
- /// Debug (the Mac's `heard:`): a finished sentence as if the hear model gave it untranslated, in
- /// a meeting listening to SilentAudioSource. The record, its translation and fixes, and the
- /// screens all follow, as for a heard line.
fun debugHeard(text: String, lang: String? = null) {
val id = sessionId ?: return
if (!listening) return
@@ -160,8 +118,6 @@ class ListenEngine(
changed()
}
- /// Sees every buffer as heard, on the audio thread (保存会议录音, an import's progress): it
- /// must only hand the buffer on.
@Volatile var tap: ((ShortArray) -> Unit)? = null
fun start(from: AudioSource, kind: String) {
@@ -179,12 +135,10 @@ class ListenEngine(
notes.begin(session.id)
speakers?.reset()
fixes?.meetingStarted()
- // 面对面: the line follows the room, as the Mac's and Windows' room mic do.
val segmenter = Segmenter(if (kind == "mic") VoiceGate() else null)
segmenter.onSegment = ::send
val queue = LinkedBlockingQueue<ShortArray>()
audio = queue
- // One worker owns the segmenter: audio callbacks only queue buffers.
worker = Thread({
var mineOpen = false
while (true) {
@@ -193,7 +147,6 @@ class ListenEngine(
if (buf === HOLD) { mineOpen = true; synchronized(mine) { mine.clear() }; holdStart = heardSeconds; continue }
if (buf === RELEASE) { if (mineOpen) { mineOpen = false; finishSaying() }; continue }
if (mineOpen) synchronized(mine) { mine.add(buf) }
- // Silence, not nothing, so the segmenter's clock keeps step with the meeting's.
segmenter.feed(if (mineOpen || muted) ShortArray(buf.size) else buf)
level = Wav.rms(buf)
peak = maxOf(peak * 0.995, level)
@@ -203,26 +156,20 @@ class ListenEngine(
}, "ListenWorker").apply { isDaemon = true; start() }
source = from
from.onSamples = { tap?.invoke(it); queue.offer(it) }
- // Listening before the source starts: a source that fails at once calls onEnded → stop(),
- // which must see this meeting as running to end it.
listening = true
from.start()
Log.d("listen: started ${session.id} source=$kind target=$target")
changed()
}
- /// Stops listening, waits (briefly) for segments still at Ming, ends the record and starts the
- /// final notes. Blocks until the record is saved: call off the main thread.
fun stop(endedAt: java.time.Instant? = null) {
if (!listening) return
- // This meeting's id now: a new one may start while this waits for Ming below.
val id = sessionId ?: return
listening = false
source?.let { it.onSamples = null; it.stop() }
audio?.offer(END)
worker?.join(5000)
val deadline = System.currentTimeMillis() + 15_000
- // Again until none is left: a stretch Ming answers may start its line's fixing request.
while (System.currentTimeMillis() < deadline) {
val waiting = synchronized(gate) { inFlight.filter { !it.isDone } }
if (waiting.isEmpty()) break
@@ -242,7 +189,6 @@ class ListenEngine(
for (b in mine) { b.copyInto(all, at); at += b.size }
mine.clear(); all
}
- // Spoken, not just loud enough: a silent press came back from the service as "嗯" and was said as "Hmm." (the Mac's PressSpeech).
if (pcm.size < Segmenter.RATE / 2 || !PressSpeech.spoken(pcm)) {
sayProblem = if (pcm.size < Segmenter.RATE / 2) Strings.L("按住说完再松开") else Strings.L("没听到声音,靠近手机再说")
changed(); return
@@ -267,13 +213,10 @@ class ListenEngine(
val probe = TranscriptLine(speaker = "me", src = heard.original, dst = dst, srcLang = heard.lang, dstLang = their)
val text = speakable(probe)
Log.d("listen: said ${heard.lang} -> $their, ${if (text != null) "speaking" else "not spoken"}")
- // As on the Mac: a sentence that didn't translate is neither sent nor recorded. One
- // already in their language was heard as it is, so it is kept.
if (text == null && !sameLanguage) { sayProblem = Strings.L("这句没翻译成 · 没有说出去"); return }
val n = synchronized(gate) { ++saidCount }
val line = TranscriptLine(id = "m$n", t = t, speaker = "me", src = heard.original, dst = dst,
srcLang = heard.lang, dstLang = their)
- // The other side's next words start their own line, never joined onto mine.
synchronized(gate) { last = null }
store.append(id, line.copy())
onWords?.invoke()
@@ -284,7 +227,6 @@ class ListenEngine(
e.kind == LingException.Kind.Http && e.status in listOf(400, 404) && name != "Ling" -> Strings.L("这个模型听不了声音,换一个支持音频输入的")
e.kind == LingException.Kind.NoKey || e.kind == LingException.Kind.InvalidKey ->
if (name == "Ling") Strings.L("Ling key 无效") else Strings.LF("%@ 的 key 无效", Strings.L(name))
- // One held sentence: say it didn't go out and why; the meeting's own line covers the rest.
e.kind == LingException.Kind.Network || e.kind == LingException.Kind.Timeout ->
Strings.LF("这句没说出去 · 连不上 %@", Strings.L(name))
else -> Strings.L("没听清,再说一次")
@@ -308,8 +250,6 @@ class ListenEngine(
private fun send(seg: Segment) {
if (voicesOn) {
- // Subtitles wait for a line's voice, so on a phone too slow to keep up a line goes
- // unlabelled (对方) rather than every subtitle falling further behind.
val behind = synchronized(gate) { (voicesWaiting >= 2).also { if (!it) voicesWaiting++ } }
if (behind) Log.d("speakers: voiceprints behind, segment ${seg.index} left unlabelled")
else {
@@ -325,7 +265,6 @@ class ListenEngine(
}
}
val lang = synchronized(gate) { segments[seg.index] = seg; hint }
- // Timing only (never text): where the segment sits in the audio, to measure delay.
Log.d("listen: segment ${seg.index} sent at ${"%.2f".format(seg.start)}+${"%.2f".format(seg.seconds)}")
changed()
val future = pool.submit {
@@ -333,8 +272,6 @@ class ListenEngine(
val started = System.currentTimeMillis()
try {
val clip = encode(seg.samples)
- // Into what the meeting's language translates to; a segment that turns out to be
- // in my own language under "follow system" is translated again (record).
val asked = settings.targetFor(lang)
heard = translator.hear(clip, asked, lang, seg.seconds)?.let { h ->
if (settings.targetFor(h.lang) == asked) h else h.copy(translation = null)
@@ -342,8 +279,6 @@ class ListenEngine(
synchronized(gate) { serverErrors = 0 }
problem = null; problemKind = null
} catch (e: LingException) {
- // A server error (a gateway's 502) is said from the third in a row, as on the Mac: one
- // isn't worth a banner, but a meeting with no subtitles and no reason is worse.
val shown = synchronized(gate) {
serverErrors = if (serverError(e)) serverErrors + 1 else 0
!serverError(e) || serverErrors >= SERVER_ERRORS_SHOWN
@@ -363,7 +298,6 @@ class ListenEngine(
synchronized(gate) { inFlight.add(future); inFlight.removeAll { it.isDone } }
}
- /// Hands finished segments on in order: one slow reply holds back those after it.
private fun deliver() {
val ready = mutableListOf<Pair<Segment, Heard?>>()
synchronized(deliverLock) {
@@ -382,8 +316,6 @@ class ListenEngine(
if (ready.isNotEmpty()) changed()
}
- /// The segment's voice, or null when unsure. A line with hardly a letter ("." from a breath or
- /// a click) gets no voiceprint; like the Mac, every labelled segment counts towards its voice.
private fun voice(print: Future<FloatArray?>?, seg: Segment, heard: Heard): Int? {
if (print == null || heard.original.count { it.isLetter() } < 2) return null
val vector = try { print.get(20, TimeUnit.SECONDS) } catch (e: Exception) {
@@ -395,8 +327,6 @@ class ListenEngine(
private fun record(seg: Segment, heard: Heard, voice: Int?) {
val id = sessionId ?: return
val target = settings.targetFor(heard.lang)
- // The meeting's language moves only after two segments agree, so one misheard stretch
- // doesn't flip the hint (the Mac waits for confidence the same way).
synchronized(gate) {
val h = hint
if (h == null) hint = heard.lang
@@ -410,7 +340,6 @@ class ListenEngine(
var joined = false
synchronized(gate) {
val prev = last
- // Two voices never share a line: a half sentence joins only the same voice (or an unknown one).
if (prev != null && continues(prev, seg.start - lastEnd, heard) && (voice == null || prev.voice == null || voice == prev.voice)) {
prev.src = join(prev.src, heard.original, heard.lang)
prev.dst = if (prev.dst == null || heard.translation == null) null else join(prev.dst!!, heard.translation, target)
@@ -424,18 +353,14 @@ class ListenEngine(
lastEnd = seg.start + seg.seconds
}
val copy = synchronized(gate) { line.copy() }
- // A line the hear model translated itself: finished sentences are being translated again.
if (!joined && heard.translation != null) translator.sentencesUntranslated = false
if (joined) store.replace(id, copy) else store.append(id, copy)
fixes?.applyKnown(copy.id, id)
if (voice != null) onVoice?.invoke(id)
onWords?.invoke()
- // A line Ming translated itself: with 改正听错的词 on, the AI service translates it again with
- // the misheard words pointed out (Ming's stays when that fails).
if (!joined && line.dst != null && line.srcLang != target && fixes != null) {
val src = line.src
- // Waited for like a stretch at Ming: the meeting's last line gets its fixes before it ends.
val f = pool.submit {
val dst = translator.fixLine(src, line.srcLang, target) ?: return@submit
val updated = synchronized(gate) {
@@ -448,12 +373,10 @@ class ListenEngine(
}
synchronized(gate) { inFlight.add(f) }
}
- // A joined sentence is translated again as a whole; a line Ming didn't translate gets text translation.
if ((joined || line.dst == null) && line.srcLang != target) {
val src = line.src
pool.execute {
val dst = translator.translate(src, line.srcLang, target, Translator.Kind.Sentence)
- // Untranslated: the live screens may now say why (translator.sentencesUntranslated).
if (dst == null) { changed(); return@execute }
val updated = synchronized(gate) {
if (dst == null || line.src != src) return@execute
@@ -467,18 +390,14 @@ class ListenEngine(
}
companion object {
- /// Server errors in a row before listening says so (ListenEngine.swift's cloudFailures).
const val SERVER_ERRORS_SHOWN = 3
fun serverError(e: LingException) = e.kind == LingException.Kind.Http && e.status >= 500
- /// (kind, what to say) for a stretch that couldn't be heard. Ling keeps its own words; another
- /// service is named. A hear model that refuses audio (400 / 404) is a key-like problem: 设置 fixes it.
fun problem(e: LingException, service: String): Pair<String?, String?> {
val ling = service == "Ling"
if (e.kind == LingException.Kind.Http && (e.status == 400 || e.status == 404) && !ling)
return "key" to Strings.L("这个模型听不了声音,换一个支持音频输入的")
- // It answered, with an error: like busy, it passes by itself (AICheck's serverError words).
if (serverError(e)) return "busy" to Strings.LF("%@ 暂时出错(HTTP %lld),稍后再试。", Strings.L(service), e.status)
val kind = when (e.kind) {
LingException.Kind.NoKey, LingException.Kind.InvalidKey -> "key"
@@ -491,22 +410,18 @@ class ListenEngine(
LingException.Kind.NoKey -> if (ling) Strings.L("需要 Ling key 才能听") else Strings.LF("需要 %@ 的 key 才能听", name)
LingException.Kind.InvalidKey -> if (ling) Strings.L("Ling key 无效") else Strings.LF("%@ 的 key 无效", name)
LingException.Kind.RateLimited -> if (ling) Strings.L("Ling 太忙,稍后再试") else Strings.LF("%@ 太忙,稍后再试", name)
- // Hearing goes through the service: the subtitles wait with the notes, then go on by themselves.
LingException.Kind.Network, LingException.Kind.Timeout -> Strings.LF("字幕和纪要等 %@ 恢复 · 连上后自动继续", name)
else -> null
}
return kind to text
}
- /// What may be spoken into the room for a line: my words' translation, never my own words.
fun speakable(line: TranscriptLine): String? {
val dst = line.dst?.trim() ?: return null
if (line.speaker != "me" || dst.isEmpty() || Languages.same(line.srcLang, line.dstLang) || dst == line.src.trim()) return null
return dst
}
- /// A segment continues the last line when the cut came mid-sentence: no sentence end on the
- /// last line, a short gap, the same language, and the joined line not too long to read.
fun continues(last: TranscriptLine, gap: Double, next: Heard): Boolean {
if (gap > 0.8 || last.srcLang != next.lang) return false
val text = last.src.trimEnd()
@@ -523,10 +438,6 @@ class ListenEngine(
}
}
-/** Whether anyone spoke during a hold (PressSpeech in the Mac's SpeakEngine.swift, same numbers):
- * 0.3 s of 30 ms frames over three times the hold's own quiet (its quietest tenth), between
- * -44 and -36 dBFS. A silent hold came back from Ming as "嗯。" and went out as "Hmm."; a result
- * that is only fillers isn't said either. */
object PressSpeech {
private const val FRAME = 480
private const val NEEDED = 0.3
@@ -547,9 +458,7 @@ object PressSpeech {
return levels.count { it >= line } * FRAME / 16000.0 >= NEEDED
}
- /** Nothing but fillers (嗯, 啊, um, hmm…), whatever the punctuation. */
fun filler(text: String): Boolean {
- // A heading with nothing after it ("翻译结果:", "Translation:"): the model's answer to noise, not a sentence.
val trimmed = text.trim()
if (trimmed.length in 1..12 && trimmed.last() in "::") return true
val words = text.lowercase().split(Regex("[^\\p{L}]+")).filter { it.isNotEmpty() }
diff --git a/android/core/src/main/kotlin/cicada/LiveFixes.kt b/android/core/src/main/kotlin/cicada/LiveFixes.kt
index c6a8994..510df6f 100644
--- a/android/core/src/main/kotlin/cicada/LiveFixes.kt
+++ b/android/core/src/main/kotlin/cicada/LiveFixes.kt
@@ -1,22 +1,12 @@
package cicada
-/// 改正听错的词 (the Mac's LiveFixes.swift), between the translation and the records: which fixes a
-/// line takes, which wait for the user (待确认), and what the user's answers and edits teach the
-/// word list. Who wins: the user's own decisions, then the word list, then a later pass, then the
-/// first guess. UI-free and thread-safe: proposals arrive on listening's threads, taps on the main
-/// one. The screens show `pending`, `asking` and `toast` and pass taps back.
class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val settings: AppSettings) {
- /// The last thing the user did, said back with 撤销 for a few seconds (`TOAST_MS`).
class Toast(val text: String, val at: Long = System.currentTimeMillis())
@Volatile var toast: Toast? = null; private set
- /// Fixes said no to in this meeting ("from→to"), and how often each heard form was turned down
- /// overall this run: twice and it leaves the word list.
private val refused = HashSet<String>()
private val refusals = HashMap<String, Int>()
- /// 稍后再看 on the card: still waiting, but asked again only after the meeting.
private val deferred = HashSet<String>()
- /// What 撤销 puts back: the lines' fixes and the word list as they were.
private class Step(val session: String, val lines: Map<String, List<LineFix>>, val words: List<Vocabulary.Term>,
val refused: Set<String>, val deferred: Set<String>)
private val undoStack = ArrayDeque<Step>()
@@ -32,7 +22,6 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
// MARK: The service's proposals
- /// What a finished sentence's request carries (the Mac's FixContext); null while fixing is off.
class Context(val topic: String?, val words: List<String>, val recent: List<String>,
val following: List<String> = emptyList(), val summary: String? = null)
@@ -52,8 +41,6 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
)
}
- /// The service's proposals for a line heard as `text` (none at all is an answer too: a second
- /// pass takes back what isn't proposed again).
@Synchronized fun received(text: String, edits: List<Correction.Edit>) {
if (!settings.fixMisheard) return
val (id, line) = store.lineHeard(text) ?: return
@@ -64,7 +51,6 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
when {
verdict == Correction.Verdict.Apply -> {
fresh.add(LineFix(e.from, e.to))
- // A listed word counts as used whichever way the fix was found (a sound-alike too).
vocabulary.used(Correction.core(e.from, e.to).second)
}
verdict == Correction.Verdict.Ask && settings.askNames -> fresh.add(LineFix(e.from, e.to, ask = true))
@@ -77,8 +63,6 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
set(fixes, line.id, id)
}
- /// The word list's confirmed heard forms, fixed without asking anyone: also with no AI service.
- /// Two characters at least, so a single 压 never turns into 押 everywhere.
@Synchronized fun applyKnown(lineId: String, id: String) {
if (!settings.fixMisheard) return
val l = store.line(id, lineId) ?: return
@@ -89,8 +73,6 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
val out = fixes.toMutableList()
for (t in vocabulary.terms) {
for (h in t.heard) {
- // A heard form two words claim (两个都留) is never fixed silently. A translation a yes taught
- // before that was refused (平台 → platform) isn't either; one the user typed is.
if (t.source != "user" && Correction.translation(h, t.word)) continue
if (h.length < 2 || Correction.word(h, src) == null || pair(h, t.word) in refused || vocabulary.owners(h, t.word).isNotEmpty()) continue
if (out.any { it.from == h || (it.applied && it.from.contains(h)) || (it.off == true && it.from == h) }) continue
@@ -111,7 +93,6 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
class Waiting(val line: TranscriptLine, val fix: LineFix)
- /// 待确认 in a meeting: each (from → to) once, oldest first.
fun pending(id: String): List<Waiting> {
val seen = HashSet<String>()
val out = mutableListOf<Waiting>()
@@ -119,8 +100,6 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
return out
}
- /// What the live card asks now: not what was put off (稍后再看), and only the first few, so a
- /// burst of names doesn't keep the card up all meeting. `of`: how many in this run.
class Asking(val line: TranscriptLine, val fix: LineFix, val of: Int)
@Synchronized fun asking(id: String): Asking? {
@@ -129,15 +108,12 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
return Asking(first.line, first.fix, minOf(open.size, ASK_AT_ONCE))
}
- /// × on the card: 稍后再看, asked again after the meeting (the record's banner).
@Synchronized fun later(fix: LineFix, id: String) {
remember(id, emptyList())
deferred.add(key(fix))
say(Strings.L("已收进人名和术语,稍后再看"))
}
- /// 对 / 不对 on a waiting fix: every line in the meeting waiting on the same change follows,
- /// and a yes goes into the word list so the next meeting fixes it without asking.
@Synchronized fun answer(fix: LineFix, yes: Boolean, id: String) {
val c = Correction.core(fix.from, fix.to)
val lines = store.lines(id)
@@ -152,7 +128,6 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
}
if (yes) {
vocabulary.confirm(c.first, c.second)
- // The rest of the meeting heard the same way follows now, not with the next line.
for (l in others) applyKnown(l.id, id)
} else {
refused.add(pair(c.first, c.second))
@@ -161,11 +136,9 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
say(if (yes) Strings.LF("已改 %@ → %@,记进词表", c.first, c.second) else Strings.LF("这场不再问 %@", c.first))
}
- /// 改回: this line goes back to what was heard, and the meeting stops making this change.
@Synchronized fun revert(fix: LineFix, lineId: String, id: String) {
val l = store.line(id, lineId) ?: return
val fixes = l.fixes ?: return
- // The one still on: an earlier, already undone copy of the same change may sit before it.
val k = fixes.indexOfFirst { it.from == fix.from && it.to == fix.to && it.applied }
.takeIf { it >= 0 } ?: fixes.indexOfFirst { it.from == fix.from && it.to == fix.to }
if (k < 0) return
@@ -184,8 +157,6 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
class Same(val heard: String, val count: Int, val swap: Boolean)
- /// How many lines of the meeting the same edit would change ("整场听成 木娜 的 2 处都改").
- /// An edit that only adds or drops words stays on its line (count 1, nothing to learn).
fun sameHeard(lineId: String, id: String, edited: String): Same? {
val lines = store.lines(id)
val l = lines.firstOrNull { it.id == lineId } ?: return null
@@ -194,8 +165,6 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
return Same(e.heard, maxOf(1, n), e.swap)
}
- /// The user rewrote a line (改这句…): what changed becomes their own fix, on this line or on
- /// every line showing the same words, and with `keep` the heard form joins the word list.
@Synchronized fun edit(lineId: String, id: String, edited: String, everywhere: Boolean, keep: Boolean): Int {
val lines = store.lines(id)
val l = lines.firstOrNull { it.id == lineId } ?: return 0
@@ -205,21 +174,15 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
val targets = if (everywhere) lines.filter { it.shown.contains(fix.from) } else listOf(l)
remember(id, targets.map { it.id })
for (t in targets) {
- // A guess still waiting on the same words is answered by the edit: not that.
- // The same change made again replaces any earlier copy (say, one undone with 改回).
val fixes = (t.fixes ?: emptyList()).filter { !(it.from == fix.from && it.to == fix.to) }.map { f ->
if (f.ask == true && (f.from.contains(heard) || heard.contains(f.from))) f.copy(ask = null, off = true) else f
}
set(fixes + fix, t.id, id)
}
val word = Correction.core(fix.from, fix.to).second.trim()
- // Only a change made everywhere teaches the word list (a one-off must not), and only a
- // word for a word (`Vocabulary.learnable`).
val learned = keep && everywhere && Vocabulary.learnable(heard, word) != null
if (learned) vocabulary.confirm(heard, word, "user")
Log.d("fix edited lines=${targets.size} learned=$learned")
- // A swap reads as the words swapped; an added or dropped word as the span it changed
- // ("in → in now", not "in → now").
val (a, b) = if (e.swap) heard to word else fix.from to fix.to
say(if (learned) Strings.LF("已改 %lld 处:%@ → %@,记进词表", targets.size, a, b) else Strings.LF("已改 %lld 处:%@ → %@", targets.size, a, b))
return targets.size
@@ -247,7 +210,6 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
changed()
}
- /// The toast while it is up.
fun toastNow(now: Long = System.currentTimeMillis()): Toast? = toast?.takeIf { now - it.at < TOAST_MS }
private fun say(text: String) {
@@ -256,7 +218,6 @@ class LiveFixes(val store: SessionStore, val vocabulary: Vocabulary, private val
}
companion object {
- /// The card asks about at most this many names in a row; the rest wait for after the meeting.
const val ASK_AT_ONCE = 3
const val TOAST_MS = 6000L
}
diff --git a/android/core/src/main/kotlin/cicada/MeetingEnd.kt b/android/core/src/main/kotlin/cicada/MeetingEnd.kt
index 03cc8fe..65dd8fb 100644
--- a/android/core/src/main/kotlin/cicada/MeetingEnd.kt
+++ b/android/core/src/main/kotlin/cicada/MeetingEnd.kt
@@ -1,14 +1,5 @@
package cicada
-/// Decides when a meeting is over, so one nobody ended doesn't run on for hours and pull the next
-/// video into its notes. A port of the Mac's MeetingEndWatch (MeetingEnd.swift), same rules and
-/// tests; times are seconds.
-///
-/// Two signals on the Mac. The main one, a meeting app letting go of the microphone (hanging up),
-/// Android can't see: no app may know what another one records, and calls can't be captured
-/// anyway. So the app passes no calls and `followApps` off, which leaves the fallback: nothing was
-/// recognised for a while. "Nothing recognised" counts words, not sound, so background music
-/// doesn't keep a meeting alive. Pure; the app ticks it every 2 s.
class MeetingEndWatch(var config: Config, start: Double) {
enum class Silence(val key: String) {
Prompt("prompt"), End("end"), Off("off");
@@ -19,46 +10,33 @@ class MeetingEndWatch(var config: Config, start: Double) {
val followApps: Boolean = true,
val silence: Silence = Silence.Prompt,
val silenceAfter: Double = 600.0,
- /// How long the "没人说话" prompt waits before ending.
val countdown: Double = 60.0,
- /// How long after a hang-up before ending: a device switch drops the mic for a moment.
val appGrace: Double = 30.0,
)
sealed class Reason {
- /// The meeting app (by name) hung up.
data class AppLeft(val name: String) : Reason()
object Silence : Reason() { override fun toString() = "silence" }
- /// Nobody spoke at all: there is nothing to keep, so it just stops, without a countdown.
object NobodySpoke : Reason() { override fun toString() = "nobodySpoke" }
}
data class Pending(val reason: Reason, val deadline: Double)
- /// The meeting ends at `deadline` unless someone keeps it going.
var pending: Pending? = null; private set
var lastSpeech: Double = start; private set
- /// Meeting apps seen in a call during this meeting (id → name).
var inCall: Map<String, String> = emptyMap(); private set
- /// Words were recognised (theirs or mine): a silence countdown stops. A hang-up doesn't: the
- /// next video would talk over it.
fun heard(now: Double) {
lastSpeech = now
if (pending?.reason == Reason.Silence) pending = null
}
- /// "继续记录": forget the hang-up and start counting silence again.
fun keepGoing(now: Double) {
pending = null
lastSpeech = now
inCall = emptyMap()
}
- /// `calls`: meeting apps reading a microphone now. `said`: the meeting has lines. One without
- /// keeps listening for the silence time (the subtitles stay ready), then stops quietly: a
- /// forgotten switch shouldn't listen to an empty room for hours. A call that ended before anyone
- /// spoke doesn't count. Returns why the meeting ends now, if it does.
fun tick(now: Double, calls: Map<String, String>, said: Boolean): Reason? {
if (!said) {
inCall = if (config.followApps) calls else emptyMap()
@@ -70,7 +48,7 @@ class MeetingEndWatch(var config: Config, start: Double) {
if (config.followApps) {
inCall = inCall + calls
val hungUp = inCall.isNotEmpty() && inCall.keys.all { calls[it] == null }
- if (pending?.reason is Reason.AppLeft && !hungUp) pending = null // rejoined
+ if (pending?.reason is Reason.AppLeft && !hungUp) pending = null
if (hungUp && (pending == null || pending?.reason == Reason.Silence)) {
val name = inCall.toSortedMap().values.firstOrNull() ?: ""
pending = Pending(Reason.AppLeft(name), now + config.appGrace)
diff --git a/android/core/src/main/kotlin/cicada/Models.kt b/android/core/src/main/kotlin/cicada/Models.kt
index df06e46..4c88ff0 100644
--- a/android/core/src/main/kotlin/cicada/Models.kt
+++ b/android/core/src/main/kotlin/cicada/Models.kt
@@ -4,11 +4,6 @@ import java.time.Instant
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
-// The meeting record, field for field the Mac app's `session.json` (SessionStore.swift, Notes.swift),
-// so a record moves between the platforms unchanged. Each type maps to and from a JSON object;
-// Json.write sorts the keys and leaves out nulls, as the Mac's encoder does.
-
-/// Whole seconds, UTC, "Z": what Swift's `.iso8601` writes (and expects back).
object Iso8601 {
private val format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(java.time.ZoneOffset.UTC)
fun write(at: Instant): String = format.format(at.truncatedTo(ChronoUnit.SECONDS))
@@ -16,28 +11,19 @@ object Iso8601 {
}
class TranscriptLine(
- /// "h<n>-<segment>" for heard lines, "m<n>" for the user's own.
var id: String = "",
- /// Seconds from the start of the session.
var t: Double = 0.0,
- /// "them" (what was heard) or "me" (the user's microphone, on the Mac).
var speaker: String = "them",
var src: String = "",
var dst: String? = null,
var srcLang: String = "",
var dstLang: String = "",
- /// The other side's voice, as SpeakerTagger grouped it (null: not told apart).
var voice: Int? = null,
- /// "room": heard by the Mac's room microphone in a 电脑和会议室 meeting; kept so a Mac record
- /// opened here keeps its 现场 / 线上.
var via: String? = null,
- /// Words the AI service or the user fixed (Correction.kt); `src` stays what was heard. Absent
- /// when none, as the Mac writes it.
var fixes: MutableList<LineFix>? = null,
) {
fun copy() = TranscriptLine(id, t, speaker, src, dst, srcLang, dstLang, voice, via, fixes?.map { it.copy() }?.toMutableList())
- /// What the line says once its fixes are in: shown, searched, exported and read by the notes.
val shown: String get() = fixes?.let { Correction.apply(it, src).text } ?: src
fun toJson(): Map<String, Any?> = mapOf(
@@ -74,15 +60,10 @@ class Session(
var renamed: Boolean? = null,
var voiceNames: Map<String, String>? = null,
var voiceGuesses: Map<String, VoiceGuess>? = null,
- /// An imported recording or video on the Mac (its file name, where it was, true until
- /// transcribed); Android imports too (ImportActivity) and writes these as the Mac does.
var sourceFile: String? = null,
var sourcePath: String? = null,
var importing: Boolean? = null,
- /// Heard through the microphone in the room (会议室) for some or all of it.
var room: Boolean? = null,
- /// Keys this version doesn't know (the Mac's voiceProfiles / voiceSuggestions, newer
- /// fields), written back untouched so saving here never drops another platform's data.
var extra: Map<String, Any?> = emptyMap(),
) {
val durationSeconds: Double get() = ((endedAt ?: Instant.now()).toEpochMilli() - startedAt.toEpochMilli()) / 1000.0
@@ -115,7 +96,6 @@ class Session(
}
}
-/// Written by Ling while the meeting runs, rewritten over the whole transcript when it ends.
class MeetingNotes(
var title: String? = null,
var summary: String = "",
@@ -123,7 +103,6 @@ class MeetingNotes(
var conclusions: MutableList<NoteItem> = mutableListOf(),
var todos: MutableList<NoteItem> = mutableListOf(),
var terms: MutableList<NoteTerm> = mutableListOf(),
- /// How many transcript lines these notes cover.
var covered: Int = 0,
var final: Boolean = false,
var updatedAt: Instant? = null,
@@ -154,13 +133,11 @@ class NoteTopic(
var title: String = "",
var summary: String = "",
var points: MutableList<String> = mutableListOf(),
- /// When each point was said (its first evidence line), parallel to points.
var pointTimes: MutableList<Double?>? = null,
var fishbone: Fishbone? = null,
) {
fun pointTime(i: Int): Double? = pointTimes?.getOrNull(i)
- // pointTimes keeps its nulls: Swift writes [12.4, null].
fun toJson(): Map<String, Any?> = mapOf(
"start" to start, "title" to title, "summary" to summary, "points" to points,
"pointTimes" to pointTimes, "fishbone" to fishbone?.toJson(),
@@ -187,7 +164,6 @@ class FishboneBranch(
var label: String = "",
var detail: String = "",
var t: Double? = null,
- /// How many transcript lines back this branch; 0 is shown as weak.
var support: Int = 0,
) {
fun toJson(): Map<String, Any?> = mapOf("label" to label, "detail" to detail, "t" to t, "support" to support)
@@ -200,12 +176,10 @@ class NoteItem(
var text: String = "",
var owner: String? = null,
var support: Int = 0,
- /// When it was said (first evidence line).
var t: Double? = null,
) {
fun toJson(): Map<String, Any?> = mapOf("text" to text, "owner" to owner, "support" to support, "t" to t)
- /// The owner as stored ("你", "对方", "说话人2" or a name) in the UI language.
val ownerShown: String? get() {
val o = owner ?: return null
when (o) { "你", "对方", "未识别" -> return Strings.L(o) }
@@ -213,7 +187,6 @@ class NoteItem(
return o
}
- /// The to-do with its owner after it: "(对方)" in Chinese, " (Them)" in English.
val withOwner: String get() = text + (ownerShown?.let { Strings.LF("待办的负责人 %@", it) } ?: "")
companion object {
@@ -221,18 +194,14 @@ class NoteItem(
}
}
-/// A name or term as the notes settled on it, and how speech recognition heard it.
class NoteTerm(var name: String = "", var note: String = "", var heard: MutableList<String> = mutableListOf()) {
fun toJson(): Map<String, Any?> = mapOf("name" to name, "note" to note, "heard" to heard)
companion object {
fun from(o: Map<String, Any?>) = NoteTerm(o["name"].str() ?: "", o["note"].str() ?: "", o["heard"].arr().mapNotNull { it.str() }.toMutableList())
- /// Corrected spellings first: what a reader can't work out alone.
fun ordered(terms: List<NoteTerm>) = terms.filter { it.heard.isNotEmpty() } + terms.filter { it.heard.isEmpty() }
- /// The reply's terms in the order they were shown before, new ones after: the model often
- /// returns the same names reshuffled, which would make the chips jump on every update.
fun keepingOrder(old: List<NoteTerm>, new: List<NoteTerm>): List<NoteTerm> {
val rank = HashMap<String, Int>()
old.forEachIndexed { i, t -> rank.putIfAbsent(t.name, i) }
diff --git a/android/core/src/main/kotlin/cicada/Notes.kt b/android/core/src/main/kotlin/cicada/Notes.kt
index 7f6fbc6..c73494e 100644
--- a/android/core/src/main/kotlin/cicada/Notes.kt
+++ b/android/core/src/main/kotlin/cicada/Notes.kt
@@ -6,11 +6,6 @@ import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
-/// Keeps the live meeting's notes up to date: every ~45 s with new speech, one Ling call sends the
-/// current notes plus the new lines and gets the last topics back as JSON; a final pass rewrites
-/// them over the whole transcript (a long one in parts) when the meeting ends. A failed or odd
-/// reply never replaces good notes. The prompt and parsing are the Mac's (Notes.swift, via the
-/// Windows port), so all write the same notes.
class NotesEngine(private val ling: LingClient, private val store: SessionStore) {
enum class State { Idle, Updating, NoKey, InvalidKey, RateLimited, Failed }
@@ -21,30 +16,22 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
private var sessionId: String? = null
private var inFlight = false
private var pendingFinal: String? = null
- /// The meeting whose final pass is running.
private var finalId: String? = null
private var lastAttempt = 0L
private val listeners = mutableListOf<() -> Unit>()
@Volatile var notes = MeetingNotes(); private set
@Volatile var status = State.Idle; private set
- /// The session the notes belong to (stays set after the meeting ends).
@Volatile var shownId: String? = null; private set
- /// A final pass is over, whether it wrote notes or not (存到文件夹 waits for it). On the
- /// notes' worker thread.
@Volatile var finalDone: ((String) -> Unit)? = null
- /// The final pass for this meeting is running, waiting its turn, or still to start: the
- /// meeting has ended but finish() hasn't run yet (it starts on listening's pool).
fun settling(id: String): Boolean = synchronized(gate) { sessionId == id || finalId == id || pendingFinal == id } || generating == id
- /// The language notes are written in (English name), from 纪要语言.
@Volatile var language: () -> String = { "Simplified Chinese" }
fun onChange(listener: () -> Unit) { synchronized(listeners) { listeners.add(listener) } }
private fun changed() { synchronized(listeners) { listeners.toList() }.forEach { it() } }
- /// Names for the translation glossary: "江充 (note; misheard as 江松, 江冲)".
fun glossary(): List<String> = notes.terms.take(30).map {
if (it.heard.isEmpty()) "${it.name} (${it.note})" else "${it.name} (${it.note}; misheard as ${it.heard.joinToString(", ")})"
}
@@ -61,7 +48,6 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
changed()
}
- /// The meeting ended: one last pass over the whole transcript. Blocks until it's written.
fun finish() {
val id = synchronized(gate) {
tick?.cancel(false); tick = null
@@ -75,10 +61,8 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
changed()
}
- /// The finished meeting whose notes are being written on request (the UI shows it working).
@Volatile var generating: String? = null; private set
- /// Notes for a finished meeting that has none (runs in the background; repeat taps are one).
fun generate(id: String) {
if (generating == id) return
generating = id
@@ -90,15 +74,12 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
private fun tick() {
val id = synchronized(gate) {
- // A key added or replaced since: clear the old complaint (an invalid key stays invalid
- // until it's changed, which resets the client's keyState).
if ((status == State.NoKey || status == State.InvalidKey) && ling.usable) { status = State.Idle; changed() }
val id = sessionId ?: return
if (inFlight) return
val s = store.get(id) ?: return
if (s.lines.size <= notes.covered) return
val since = (System.currentTimeMillis() - lastAttempt) / 1000.0
- // First notes as soon as there is something to say, then every 45 s.
val due = if (notes.isEmpty) s.lines.size >= 3 || since > 20 else since >= INTERVAL
if (!due) return
id
@@ -128,11 +109,7 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
val lines = store.lines(id)
val from = if (final) 0 else minOf(base.covered, lines.size)
val lang = language()
- // A live update returns only the last topics: when it rewrote them all, its reply grew with
- // the meeting until, about an hour in, it was cut off at max_tokens or fell into a loop and
- // the notes stopped updating. The final pass still rewrites everything once.
val frozen = if (final) 0 else maxOf(0, base.topics.size - EDITABLE_TOPICS)
- // Voices told apart go as 说话人N, or the name they've been given (notes then say "George").
val numbers = SpeakerLabels.numbers(lines)
val names = SpeakerLabels.names(session)
val prompt = prompt(base, lines, from, lang, final, frozen = frozen, numbers = numbers, names = names)
@@ -181,16 +158,12 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
}
}
- /// A long meeting's final pass: each part noted on its own, all at once, then merged into one.
- /// null when a step fails: the caller then makes one pass over the whole transcript, as before.
private fun longFinal(lines: List<TranscriptLine>, numbers: Map<String, Int>, names: Map<Int, String>,
lang: String, startedAt: Double): MeetingNotes? {
val parts = parts(lines)
if (parts.size <= 1) return null
val started = System.currentTimeMillis()
val times = lines.map { it.t }
- // The engine's own executor is single-threaded: the parts get a pool of their own, for this
- // pass only. Each call still goes through LingClient's gate.
val pool = Executors.newFixedThreadPool(parts.size) { r -> Thread(r, "NotesPart").apply { isDaemon = true } }
val replies = try {
pool.invokeAll(parts.mapIndexed { i, range ->
@@ -213,7 +186,6 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
Log.d("notes: final part ${i + 1}/${parts.size} failed, one pass instead")
return null
}
- // Without its topics: given them, the merge wrote them all back out and was cut off.
notes.add(Json.write(part - "topics", pretty = false))
topics += thinned(parsed!!.topics, partTopics(parts.size), lines[parts[i].last].t)
}
@@ -236,22 +208,11 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
companion object {
const val INTERVAL = 45.0
- /// The most topics the final notes have (the prompt says so too; the model doesn't always listen).
const val MAX_TOPICS = 8
- /// Live notes once stopped at 8 topics and poured the rest of the meeting into the last one,
- /// whose summary grew into a wall of "最新…又…补充…"; past this, the two shortest neighbouring
- /// settled topics are joined instead, so the newest can start.
const val LIVE_MAX_TOPICS = 12
- /// A topic summary longer than this is a log the model kept appending to, not one sentence.
const val TOPIC_SUMMARY_LIMIT = 160
- /// How many of the last topics a live update may rewrite; earlier ones stay as they are.
const val EDITABLE_TOPICS = 2
- /// A live reply's topics after the `frozen` ones it was told to leave alone: with some frozen,
- /// at most the editable ones plus one new, from the end (the model sometimes echoes the whole
- /// list), never a copy of a frozen one, each summary kept to one sentence; and no more than
- /// LIVE_MAX_TOPICS in all (past that, settled neighbours are joined). A reply with no topics of
- /// its own keeps the ones it had.
fun merge(old: List<NoteTopic>, frozen: Int, returned: List<NoteTopic>): List<NoteTopic> {
val kept = old.take(frozen).toMutableList()
val fixed = kept.map { it.title }.toSet()
@@ -261,7 +222,6 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
tail.forEach { it.summary = shortened(it.summary) }
tail = capped(tail, LIVE_MAX_TOPICS - minOf(kept.size, 1))
while (kept.size + tail.size > LIVE_MAX_TOPICS && kept.size >= 2) {
- // The pair spanning the least time, its end being the next topic's start.
val ends = kept.drop(1).map { it.start } + tail[0].start
val i = (0 until kept.size - 1).minBy { ends[it + 1] - kept[it].start }
kept[i] = joined(kept[i], kept[i + 1])
@@ -270,8 +230,6 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
return capped(kept + tail, LIVE_MAX_TOPICS)
}
- /// Two neighbouring topics as one: both titles and summaries, and up to the 4 points the
- /// prompt allows, taken evenly from each.
fun joined(a: NoteTopic, b: NoteTopic): NoteTopic {
val fromA = minOf(a.points.size, maxOf(2, 4 - b.points.size))
val fromB = minOf(b.points.size, 4 - fromA)
@@ -282,8 +240,6 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
pointTimes = if (times.any { it != null }) times.toMutableList() else null, fishbone = a.fishbone ?: b.fishbone)
}
- /// At most `count` topics (at least one): the points of any after that go into the last kept.
- /// Copies the topic it adds to: the earlier ones may be the notes on screen.
fun capped(topics: List<NoteTopic>, count: Int): List<NoteTopic> {
val out = topics.toMutableList()
while (out.size > maxOf(1, count)) {
@@ -296,14 +252,10 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
return out
}
- /// Terms keep only the heard forms the recognizer really wrote (`src`). The notes read lines
- /// with fixes in, so a wrong fix came back as a heard form ("X平台 heard as platform"), went to
- /// the translator and the next fix's request as a known mishearing, and was proposed again.
fun heardAsSaid(terms: List<NoteTerm>, lines: List<TranscriptLine>): List<NoteTerm> = terms.map { t ->
NoteTerm(t.name, t.note, t.heard.filter { h -> lines.any { it.src.contains(h, ignoreCase = true) } }.toMutableList())
}
- /// A runaway topic summary cut back to its first sentence (or to the limit, with "…").
fun shortened(summary: String): String {
if (summary.length <= TOPIC_SUMMARY_LIMIT) return summary
val head = summary.take(TOPIC_SUMMARY_LIMIT)
@@ -311,15 +263,12 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
return if (end >= 0) head.take(end + 1) else head.trimEnd() + "…"
}
- /// The model echoes points it already had without evidence: keep the times they had, and a
- /// point keeps the time it was first heard.
fun carryTimes(old: MeetingNotes, next: MeetingNotes) {
val known = HashMap<String, Double>()
for (t in old.topics) for (i in t.points.indices) t.pointTime(i)?.let { known.putIfAbsent(t.points[i], it) }
for (t in next.topics) {
val times = t.points.mapIndexed { i, p -> min(t.pointTime(i), known[p]) }.toMutableList()
t.pointTimes = if (times.any { it != null }) times else null
- // A topic starts no later than its first point (the reply dates it from the lines it cites now).
times.filterNotNull().minOrNull()?.let { if (it < t.start) t.start = it }
}
val items = HashMap<String, Double>()
@@ -334,9 +283,6 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
// MARK: Prompt (Notes.swift › prompt, word for word)
- /// `frozen`: how many first topics a live update leaves alone (sent as a list, not returned).
- /// `part`: in a long meeting's final pass, which part `from until lines.size` is (1-based, of).
- /// `numbers` / `names`: voices told apart (line id → 说话人N) and the names given to them.
fun prompt(notes: MeetingNotes, lines: List<TranscriptLine>, from: Int, language: String, final: Boolean,
frozen: Int = 0, part: Pair<Int, Int>? = null,
numbers: Map<String, Int> = emptyMap(), names: Map<Int, String> = emptyMap()): String { fun line(i: Int): String {
@@ -374,7 +320,6 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
return p + "\n\n" + format(language, final, frozen)
}
- /// The reply's JSON shape and the rules for its contents.
private fun format(language: String, final: Boolean, frozen: Int): String =
"Return the full notes as one JSON object with exactly these keys:\n" +
"{\"title\": \"the meeting's name: what it is about, a few words\",\n" +
@@ -400,8 +345,6 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
// MARK: Long meetings
- /// How a long meeting's final pass is split: over SPLIT_MINUTES, into equal parts by time of at
- /// most PART_MINUTES. One pass covered a 91-minute meeting but only the first hour of a 4-hour one.
const val SPLIT_MINUTES = 100.0
const val PART_MINUTES = 60.0
fun parts(lines: List<TranscriptLine>): List<IntRange> {
@@ -421,21 +364,14 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
return bounds.zipWithNext { a, b -> a until b }
}
- /// Each part's share of the topics: the merge keeps them as they are, so every part has some.
fun partTopics(parts: Int) = maxOf(2, MAX_TOPICS / maxOf(1, parts))
- /// At most `count` of a part's `topics`, neighbours joined: a part's reply often has more
- /// topics than asked. Keeping the first ones lost the end of the part, and keeping some spread
- /// from first to last kept a topic's "(续)" stub at the part's end and dropped the topic
- /// itself. The same subject twice is joined first, under the first one's title; then the pair
- /// spanning the least time (to the next topic's start, or `end` for the last), as live notes do.
fun thinned(topics: List<NoteTopic>, count: Int, end: Double): List<NoteTopic> {
val list = topics.toMutableList()
while (list.size > maxOf(1, count)) {
fun span(i: Int) = (if (i + 2 < list.size) list[i + 2].start else end) - list[i].start
val pairs = 0 until list.size - 1
val same = pairs.firstOrNull { subject(list[it].title) == subject(list[it + 1].title) }
- // minBy keeps the first of equal spans, as the Mac does.
val at = same ?: pairs.minBy { span(it) }
val one = joined(list[at], list[at + 1])
if (same != null) { one.title = list[at].title; one.summary = list[at].summary }
@@ -445,7 +381,6 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
return list
}
- /// A topic title without a trailing bracket ("预算评审(续)", "Budget (cont.)"): what it is about.
fun subject(title: String): String {
val t = title.trim()
if (t.isEmpty() || t.last() !in "))") return t
@@ -453,9 +388,6 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
return if (open > 0) t.substring(0, open).trim() else t
}
- /// The whole meeting's title, summary, conclusions, to-dos and terms from its parts' notes (the
- /// replies as they came, with their evidence line ids). Asked to merge topics too, the model
- /// kept the first parts' and dropped the rest, so topics are joined in code.
fun mergePrompt(parts: List<String>, lines: List<TranscriptLine>, language: String): String {
var p = "You keep notes for a meeting that has just ended. It was long, so each part was noted on its own; below are those notes, in time order (JSON; evidence ids are transcript lines, L1 the first). Merge them into the notes for the whole meeting.\n" +
"Write the notes in $language. Return JSON only.\n\n"
@@ -466,8 +398,6 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
return p + format(language, final = true, frozen = 0)
}
- /// The current notes as sent back to the model (no bookkeeping fields). `from`: the first topic
- /// sent (earlier ones go as a list of titles).
private fun compactJson(n: MeetingNotes, from: Int = 0): String {
val o = linkedMapOf<String, Any?>()
if (n.title != null) o["title"] = n.title
@@ -483,7 +413,6 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
// MARK: Parse
- /// Lenient: missing keys become empty, evidence ids are checked against the transcript.
fun parse(raw: String, times: List<Double>, startedAt: Double): MeetingNotes? {
val a = raw.indexOf('{'); val b = raw.lastIndexOf('}')
if (a < 0 || b <= a) return null
@@ -519,8 +448,6 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
points.add(text)
pointTimes.add(po?.let { time(it["evidence"]) })
}
- // When it was first said, from its lines: the model's own `start` drifts by tens of
- // minutes in a long meeting (a topic said at 51-85 min came back as starting at 23).
val said = (listOf(time(t["evidence"])) + pointTimes).filterNotNull().minOrNull()
n.topics.add(NoteTopic(start = said ?: t["start"].num() ?: startedAt, title = topicTitle, summary = s(t["summary"]), points = points,
pointTimes = if (pointTimes.any { it != null }) pointTimes else null, fishbone = fish))
@@ -534,7 +461,6 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
val name = s(t["name"])
NoteTerm(name = name, note = s(t["note"]), heard = t["heard"].arr().map { s(it) }.filter { it.isNotEmpty() && it != name }.toMutableList())
}.filter { it.name.isNotEmpty() }.toMutableList()
- // The model keeps every term it ever had: bound the glossary, keeping the misheard ones.
if (n.terms.size > 20) n.terms = NoteTerm.ordered(n.terms).take(20).toMutableList()
return if (n.isEmpty) null else n
}
diff --git a/android/core/src/main/kotlin/cicada/Providers.kt b/android/core/src/main/kotlin/cicada/Providers.kt
index b767099..22c5a88 100644
--- a/android/core/src/main/kotlin/cicada/Providers.kt
+++ b/android/core/src/main/kotlin/cicada/Providers.kt
@@ -3,35 +3,20 @@ package cicada
import java.net.URI
import java.util.Base64
-/// The AI services the port can use (AIProviders.swift, plus what hears audio; the Linux port's
-/// providers.py is the same table). Ling is the reference: Ming hears each stretch of audio and
-/// answers language, original and translation in one call, and only Ling clones the user's voice.
-/// The others are OpenAI-compatible and hear through an audio-input chat model with the same
-/// prompt (tools/audio-probe, 2026-11: about as accurate, 0.5–2 s slower). OpenAI itself is left
-/// out: a port needs a model that hears, and its audio models are untested.
-///
-/// Recommended models come first in every menu and are the defaults. For hearing, the first is the
-/// one that wrote nothing for a clip without speech: a made-up line ends up in the notes and, in
-/// 面对面, read aloud to the other side.
-data class Model(val id: String, /** Why it is recommended: a Chinese UI key, localized where shown. */ val note: String = "")
-
-data class CloudVoice(val id: String, /** "女" / "男", a Chinese UI key. */ val gender: String)
+data class Model(val id: String, val note: String = "")
+
+data class CloudVoice(val id: String, val gender: String)
class Provider(
val id: String,
val name: String,
- /** Null for "custom": the user's address. */
val base: String?,
- /** Where to create a key. */
val site: String?,
val textModels: List<Model> = emptyList(),
val hearModels: List<Model> = emptyList(),
- /** Empty: this service can't speak to the other side here. */
val voiceModels: List<Model> = emptyList(),
- /** Of `voiceModels` (Gemini TTS: the same names in every language). */
val voices: List<CloudVoice> = emptyList(),
val clones: Boolean = false,
- /** Ling allows ~2 request starts a second; the aggregators far more. */
val spacing: Double = 0.1,
) {
val hasVoices get() = voiceModels.isNotEmpty()
@@ -58,24 +43,16 @@ object Providers {
voiceModels = listOf(Model("google/gemini-3.8-flash-tts", "效果和价格最均衡"), Model("google/gemini-3.8-flash-lite-tts", "更省")),
voices = GEMINI_VOICES)
- /// Any OpenAI-compatible address (a company gateway, Ollama…). Its hear model must take audio
- /// in; voices only when the user names a speech model.
val CUSTOM = Provider("custom", "其他(兼容 OpenAI)", null, null)
val ALL = listOf(LING, OPENROUTER, ZENMUX, CUSTOM)
fun named(raw: String?): Provider = ALL.firstOrNull { it.id == raw } ?: LING
- /// The custom service's notes model in `aiModels` (the Mac's key): empty is the translation model.
const val NOTES_MODEL = "custom.notes"
- /// This phone itself: a model running in Termux, say.
fun isLocal(hostOrUrl: String): Boolean = host(hostOrUrl) in listOf("localhost", "127.0.0.1", "::1")
- /// This phone or the local network (AIProvider.isNearby on the Mac): plain http is allowed and
- /// a key isn't needed. Private IPv4 (10/8, 172.16/12, 192.168/16), link-local, Tailscale's
- /// 100.64/10, IPv6 unique and link-local addresses, and `.local` names. On a phone "localhost"
- /// is the phone, so a GPU box at home or work is the usual case.
fun isNearby(hostOrUrl: String): Boolean {
val h = host(hostOrUrl).lowercase()
if (isLocal(h) || h.endsWith(".local")) return true
@@ -96,8 +73,6 @@ object Providers {
return host.trim('[', ']')
}
- /// The address as typed, normalized: https, or http only on this phone or the local network;
- /// ends in "/".
fun customBase(raw: String?): String? {
var s = raw?.trim() ?: return null
if (s.isEmpty()) return null
@@ -112,7 +87,6 @@ object Providers {
}
}
- /// The service, its address and models from the app's settings (Settings.swift › aiConfig).
fun configFrom(s: AppSettings): AIConfig {
val p = named(s.aiProvider)
if (p.id == "ling") {
@@ -124,10 +98,7 @@ object Providers {
val voice = s.aiVoiceModels["custom"]?.trim().orEmpty()
val voiceBase = if (s.aiCustomVoiceBase.isNotBlank()) customBase(s.aiCustomVoiceBase) else base
val name = s.aiCustomVoice.trim()
- // The hear model may run on its own server (an omni model beside a text one): empty is the same address.
val hearBase = if (s.aiCustomHearBase.isNotBlank()) customBase(s.aiCustomHearBase) else base
- // Notes (实时纪要, 说话人) may use another model, and with 另一个服务 another server: empty
- // is translation's. 同一个服务 keeps the typed address but doesn't use it.
val textModel = s.aiModels["custom"]?.trim().orEmpty()
val notesModel = s.aiModels[NOTES_MODEL]?.trim().orEmpty()
val notesAddress = if (s.aiCustomNotesOwn) s.aiCustomNotesBase.trim() else ""
@@ -145,9 +116,6 @@ object Providers {
private val NOT_CHAT = Regex("(embed|whisper|tts|transcribe|dall-e|image|moderation|realtime|sora|search|video|seedance|wan\\d)")
- /// Model ids from a `/models` reply, recommended ones first: those that answer in text, and for
- /// `hears` only those that take audio in. ZenMux lists modalities at the top level, OpenRouter
- /// under `architecture`; a service that says nothing keeps everything but obvious non-chat names.
fun catalog(body: String, recommended: List<String>, hears: Boolean): List<String> {
val root = Json.parseObject(body) ?: return recommended
val ids = mutableListOf<String>()
@@ -159,7 +127,7 @@ object Providers {
val ins = (m["input_modalities"] ?: a?.get("input_modalities")).arr().mapNotNull { it.str() }
val outs = (m["output_modalities"] ?: a?.get("output_modalities")).arr().mapNotNull { it.str() }
if (outs.isNotEmpty() && "text" !in outs) continue
- if (ins == listOf("audio")) continue // speech-to-text only: no prompt, no translation
+ if (ins == listOf("audio")) continue
if (hears && "audio" !in ins) continue
if (outs.isEmpty() && NOT_CHAT.containsMatchIn(id)) continue
ids.add(id)
@@ -168,32 +136,22 @@ object Providers {
}
}
-/// What one call needs to know about the service in use, resolved from settings each time.
class AIConfig(
val provider: Provider,
- /** Null: a custom service without a valid address yet. */
val base: String?,
val textModel: String,
val hearModel: String,
- /** Null: no voices with this service. */
val voiceModel: String? = null,
val voiceBase: String? = null,
val customVoice: String? = null,
- /** Where the hear model is asked (a custom service may name its own; null: not a valid address). */
val hearBase: String? = base,
- /** A custom service's notes (实时纪要, 说话人): another model, and with 另一个服务 another server
- * with its own key. Null: the same as translation. */
val notesModel: String? = null,
val notesBase: String? = null,
- /** 另一个服务 is picked: notes use their own key file when there is one. */
val notesOwnService: Boolean = false,
- /** 另一个服务 with an address that can't be used (http to the internet): notes fail the check. */
val notesBadAddress: Boolean = false,
) {
- /// Notes go somewhere translation doesn't: they get their own check, result and start gate.
val notesApart get() = provider.id == "custom" && (notesModel != null || notesBase != null || notesOwnService)
- /// What a notes call is sent with: notes' model at notes' address, the rest as translation.
val forNotes: AIConfig get() = if (!notesApart) this else
AIConfig(provider, notesBase ?: base, notesModel ?: textModel, hearModel, voiceModel, voiceBase, customVoice, hearBase,
notesModel, notesBase, notesOwnService, notesBadAddress)
@@ -201,19 +159,14 @@ class AIConfig(
val isLing get() = provider.id == "ling"
val hasVoices get() = voiceModel != null && voiceBase != null
- /// The voices the other side can be read to in with this service (Ling's are Ming's own).
val voices: List<CloudVoice> get() = when {
!hasVoices || isLing -> emptyList()
provider.id == "custom" -> customVoice?.let { listOf(CloudVoice(it, "")) } ?: emptyList()
else -> provider.voices
}
- /// The hear model is on another server than the text model.
val hearsElsewhere get() = hearBase != base
- /// Each service turns thinking off its own way (AIConfig.shape on the Mac). A custom service
- /// gets `chat_template_kwargs` (vLLM, SGLang and llama.cpp pass it to the chat template, which
- /// is how Qwen3 turns thinking off); `templateKwargs` false leaves it out for a server that refused it.
fun shape(body: MutableMap<String, Any?>, maxTokens: Int, templateKwargs: Boolean = true) {
body["max_tokens"] = maxTokens
body["temperature"] = 0.2
@@ -223,9 +176,6 @@ class AIConfig(
}
companion object {
- /// The model thought before answering, which makes every translation slow: a
- /// `reasoning_content` (or `reasoning`) field, reasoning tokens in the usage, or a `<think>`
- /// block in the answer.
fun thought(root: Map<String, Any?>): Boolean {
val message = root["choices"].arr().firstOrNull().obj()?.get("message").obj()
for (k in listOf("reasoning_content", "reasoning")) if (!message?.get(k).str().isNullOrBlank()) return true
@@ -235,9 +185,6 @@ class AIConfig(
}
}
- /// One clip in a user message: Ming takes a data URL (of any type: the app sends AAC); the
- /// others the standard `input_audio` WAV, except that Qwen's omni models want the data URL
- /// inside it (DashScope's form).
fun audioPart(audio: ByteArray, model: String, type: String = "audio/wav"): Map<String, Any?> {
val b64 = Base64.getEncoder().encodeToString(audio)
if (isLing) return mapOf("type" to "audio_url", "audio_url" to mapOf("url" to "data:$type;base64,$b64"))
diff --git a/android/core/src/main/kotlin/cicada/Segmenter.kt b/android/core/src/main/kotlin/cicada/Segmenter.kt
index 9d04e65..319168c 100644
--- a/android/core/src/main/kotlin/cicada/Segmenter.kt
+++ b/android/core/src/main/kotlin/cicada/Segmenter.kt
@@ -1,61 +1,50 @@
package cicada
-/// A stretch of speech to send to Ming: where it starts (seconds since listening began) and its
-/// 16 kHz mono samples.
class Segment(val index: Int, val start: Double, val samples: ShortArray) {
val seconds get() = samples.size / Segmenter.RATE.toDouble()
}
-/// Cuts the audio into stretches of speech by loudness alone: a pause of 0.6 s ends one, and one
-/// that runs to 8 s is cut at its quietest moment in the last 2 s, so a word is split as rarely as
-/// possible (Ming has no word timings to put it back together). Not thread-safe: fed from the
-/// listening worker only. Same numbers as the Windows Segmenter. 面对面 gives it a VoiceGate: a
-/// phone's mic hears a voice across the table well under -40 dBFS. (A meeting's first stretch was once
-/// cut at 4 s to show a line sooner: Ming then finished the cut sentence by itself, and the rest
-/// came back as a second, duplicate line.)
class Segmenter(private val gate: VoiceGate? = null) {
companion object {
const val RATE = 16000
- private const val FRAME = 480 // 30 ms
- private const val STEP = 160 // 10 ms: a key click is judged in these, as the Mac's VoiceActivity does
- private const val ONSET = 3 // steps of sound before it counts as speech
- @Volatile var threshold = 0.01 // the Mac AudioRouter's gate (about -40 dBFS)
+ private const val FRAME = 480
+ private const val STEP = 160
+ private const val ONSET = 3
+ @Volatile var threshold = 0.01
@Volatile var pause = 0.6
@Volatile var maxLength = 8.0
@Volatile var minSpeech = 0.25
- @Volatile var minWord = 0.2 // a word on its own (isWord): this much over gate / 4
- @Volatile var steady = 2.0 // frames' 90th / 10th percentile below this: not speech…
- @Volatile var dips = 2.5 // …unless the median is this far over the 10th, quiet ones held at gate / 8
- @Volatile var short = 2.0 // a sound up to this long, with real quiet (gate / 4) on both sides…
- @Volatile var swell = Math.pow(10.0, 10 / 20.0) // …that swells and fades by 10 dB is a word: see isWord
- @Volatile var fade = Math.pow(10.0, 30 / 20.0) // its rise and fade reach this far under its loudest step (or gate / 4 if lower)
- @Volatile var voiced = 0.15 // a word's full frames crossing zero under this often (per sample) have voice in them: see isVoiced
+ @Volatile var minWord = 0.2
+ @Volatile var steady = 2.0
+ @Volatile var dips = 2.5
+ @Volatile var short = 2.0
+ @Volatile var swell = Math.pow(10.0, 10 / 20.0)
+ @Volatile var fade = Math.pow(10.0, 30 / 20.0)
+ @Volatile var voiced = 0.15
private const val PRE_ROLL = 0.15
private const val TAIL = 0.15
private const val CUT_WINDOW = 2.0
- @Volatile var above = 0.25 // under this share of its loud frames' energy over 100 Hz: rumble, not speech
- // A first-order high-pass at 100 Hz, for how much of a sound is above it (isRumble).
+ @Volatile var above = 0.25
private val HIGH_PASS = 1.0 / (1.0 + 2.0 * Math.PI * 100.0 / RATE)
}
- private val pending = ShortList() // samples not yet a whole frame
- private val current = ShortList() // the open segment
- private val levels = ArrayList<Double>() // per frame of `current`
- private val highs = ArrayList<Double>() // per frame of `current`: its level over 100 Hz
- private val speech = ArrayList<Boolean>() // per frame of `current`: whether it held speech (isSpeech)
- private var sounding = 0 // 10 ms steps of sound in a row so far
- private var carried = false // the sound that made the last frame speech began in the frame before
- private var hx = 0.0 // the high-pass's last input and output, carried from frame to frame
+ private val pending = ShortList()
+ private val current = ShortList()
+ private val levels = ArrayList<Double>()
+ private val highs = ArrayList<Double>()
+ private val speech = ArrayList<Boolean>()
+ private var sounding = 0
+ private var carried = false
+ private var hx = 0.0
private var hy = 0.0
- private val before = ArrayDeque<Triple<ShortArray, Double, Double>>() // recent quiet frames and their levels, for the pre-roll
- private val idle = ArrayDeque<Double>() // levels of the last 0.6 s of quiet frames
- private var lead: Double? = null // the quietest of those when the open segment began
- private var consumed = 0L // samples seen, for timestamps
+ private val before = ArrayDeque<Triple<ShortArray, Double, Double>>()
+ private val idle = ArrayDeque<Double>()
+ private var lead: Double? = null
+ private var consumed = 0L
private var currentStart = 0.0
private var quietFrames = 0
private var loudFrames = 0
private var index = 0
- /// The level that counts as speech for this frame: the gate's when there is one.
private var line = threshold
var onSegment: ((Segment) -> Unit)? = null
@@ -68,16 +57,10 @@ class Segmenter(private val gate: VoiceGate? = null) {
pending.removeFirst(whole)
}
- /// Ends the open segment (listening stopped).
fun flush() {
if (current.size > 0) close(current.size - quietFrames * FRAME + (TAIL * RATE).toInt())
}
- /// Whether the frame holds speech: sound that has lasted 30 ms, judged in 10 ms steps against the
- /// line, so a lone key click (a few ms) neither opens a segment nor breaks the pause that ends one
- /// (VoiceActivity.swift's onset); the pre-roll then reaches back to where that sound began. A
- /// room's gate learns its noise per frame and takes whole ones, as the Mac's does per block: a
- /// voiced 30 ms frame has lasted the onset already.
private fun isSpeech(frame: ShortArray, level: Double): Boolean {
gate?.let { g ->
val on = g.voiced(level, FRAME / RATE.toDouble())
@@ -116,7 +99,6 @@ class Segmenter(private val gate: VoiceGate? = null) {
while (before.size > PRE_ROLL * RATE / FRAME + 1) before.removeFirst()
return
}
- // One frame more when the sound began in the last quiet one.
while (before.size > PRE_ROLL * RATE / FRAME + (if (carried) 1 else 0)) before.removeFirst()
currentStart = now - before.size * FRAME / RATE.toDouble()
lead = idle.minOrNull()
@@ -135,7 +117,6 @@ class Segmenter(private val gate: VoiceGate? = null) {
if (quietFrames * FRAME >= pause * RATE) {
close(current.size - quietFrames * FRAME + (TAIL * RATE).toInt())
} else if (current.size >= maxLength * RATE) {
- // The quietest frame in the last 2 s; the rest starts the next segment.
val from = maxOf(1, levels.size - (CUT_WINDOW * RATE / FRAME).toInt())
var cut = from
for (i in from until levels.size) if (levels[i] < levels[cut]) cut = i
@@ -143,19 +124,6 @@ class Segmenter(private val gate: VoiceGate? = null) {
}
}
- /// Steady sound just over the gate (a fan, hum, hiss) isn't speech: its frames barely vary
- /// (90th / 10th percentile about 1.1; speech, even over such a floor, 3 and up). Given one, Ming
- /// writes a stock sentence in the hint's language ("I'm going to show you a couple of things").
- /// Speech buried under steady noise goes too; system audio rarely carries it. Every frame from
- /// the first loud one to the last counts, the quiet ones held at the gate: counting only the
- /// loud ones dropped quiet speech (under about -30 dBFS), whose dips fall below the gate.
- /// A voice so quiet that its loudest frames barely clear the gate (about -38 dBFS: 6 of 6 lines
- /// lost in testing) still pauses between syllables, its quietest tenth of frames far under its
- /// median (8 dB and more); noise near the gate stays within about 6 dB of its median. So a flat
- /// top is steady only when it has no such dips, measured with quiet frames held at gate / 8.
- /// Very low rumble (brown noise with almost nothing over 20 Hz) can look like that and gets
- /// through more often than before (about 1 in 3 segments, was 1 in 5); what Ming makes of it
- /// still meets the hear filter (Translator.isNoise).
internal fun isSteady(frameLevels: List<Double>): Boolean {
val first = frameLevels.indexOfFirst { it >= line }
val last = frameLevels.indexOfLast { it >= line }
@@ -167,22 +135,6 @@ class Segmenter(private val gate: VoiceGate? = null) {
return low[(0.5 * (low.size - 1)).toInt()] < dips * low[(0.1 * (low.size - 1)).toInt()]
}
- /// A short word on its own: a sound up to `short` that rises out of real quiet and falls back
- /// into it (under gate / 4, about -52 dBFS, in the 0.6 s before it and in the pause after),
- /// and that swells and fades by 10 dB or more: at least 5% of its 10 ms steps (and 3 of them),
- /// from where it rises to where it fades, are that far under its 90th percentile. Such a word
- /// ("Thanks.", "Good morning everyone,") is one smooth syllable or a run of voiced ones, so the
- /// steady test, which looks for dips inside, dropped it even at -26 dBFS; and a quiet one
- /// ("Thanks." at -36 dBFS) has under 0.25 s over the gate, so it needs `minWord` over gate / 4
- /// instead (a knock with a 150 ms tail has 0.15 s). A fan, hum or hiss is there on both sides;
- /// a short burst of one in silence has at most one low step at each edge (its 5th percentile
- /// stays within 2 dB, 9 dB with 50 ms fades), and Ming makes up a sentence for a hum or fan
- /// burst. Not for a forced cut, whose end isn't a pause.
- /// Where it rises and fades: over gate / 4, or 30 dB under its loudest step if that's lower;
- /// over gate / 4 alone, a quiet word lost its rise and fade (an "s" or breath at -55 dBFS) and
- /// only its flat top was left. 30 ms frames and their 10th percentile put Samantha's "Good
- /// morning everyone." at 7.5 to 11.4 dB depending on where the frames fell, so it came and
- /// went with a few ms of lead-in; 10 ms steps and their 5th percentile give it 14.6 to 16.5.
internal fun isWord(frameLevels: List<Double>): Boolean {
val first = frameLevels.indexOfFirst { it >= line }
val last = frameLevels.indexOfLast { it >= line }
@@ -207,11 +159,6 @@ class Segmenter(private val gate: VoiceGate? = null) {
return low < body.size && body[(0.9 * (body.size - 1)).toInt()] >= swell * body[low] && isVoiced(frameLevels, samples)
}
- /// Whether a word has voice in it: 2 or more of its full frames (within 3 dB of its 90th
- /// percentile) cross zero under `voiced` times a sample. Voiced speech crosses slowly (every
- /// voice tested had full frames at 0.01 to 0.06); a hiss crosses about every other sample (0.46
- /// and up) and, faded in and out over 0.3 s, swells like a word. Edge frames half silence
- /// cross slowly whatever they hold, hence full frames only and more than one.
private fun isVoiced(frameLevels: List<Double>, samples: ShortArray): Boolean {
val full = frameLevels.sorted()[(0.9 * (frameLevels.size - 1)).toInt()] / Math.sqrt(2.0)
var slow = 0
@@ -226,7 +173,6 @@ class Segmenter(private val gate: VoiceGate? = null) {
return slow >= 2
}
- /// The frame's level over 100 Hz (RMS after the high-pass), the filter running on across frames.
private fun high(frame: ShortArray): Double {
val a = HIGH_PASS
var x0 = hx; var y = hy; var total = 0.0
@@ -240,12 +186,6 @@ class Segmenter(private val gate: VoiceGate? = null) {
return if (frame.isEmpty()) 0.0 else Math.sqrt(total / frame.size) / 32768
}
- /// Rumble, not speech: under a quarter of the loud frames' energy is over 100 Hz. Speech keeps
- /// nearly all of it there (-0.3 to -1 dB in testing, the low male voices included); brown noise
- /// with almost nothing over 20 Hz keeps -20 to -28 dB, and Ming made a sentence of 15 of 17 such
- /// segments ("I'm going to go ahead and start the meeting."), which the loudness rules can't
- /// tell from a voice. Brown noise up to about 12 Hz keeps -10 dB and goes too; a 50 Hz hum or a
- /// fan keeps about -5 dB and is left to the steady test.
internal fun isRumble(frameLevels: List<Double>, frameHighs: List<Double>): Boolean {
var full = 0.0; var above = 0.0
for (i in 0 until minOf(frameLevels.size, frameHighs.size)) {
@@ -256,7 +196,6 @@ class Segmenter(private val gate: VoiceGate? = null) {
return above < Segmenter.above * full
}
- /// Emits `current[0 until end]` and keeps what follows as the start of the next segment.
private fun close(endAt: Int) {
val end = endAt.coerceIn(0, current.size)
val samples = current.slice(0, end)
@@ -273,7 +212,6 @@ class Segmenter(private val gate: VoiceGate? = null) {
quietFrames = 0; loudFrames = 0
if (heard) onSegment?.invoke(Segment(++index, Math.round(start * 1000) / 1000.0, samples))
- // A forced cut carries on with the remainder; after a pause the remainder is silence.
if (restSpeech.any { it }) {
currentStart = start + end / RATE.toDouble()
lead = null
@@ -289,11 +227,6 @@ class Segmenter(private val gate: VoiceGate? = null) {
}
}
-/// 面对面: where speech starts follows the room. The Mac's VoiceGate (RoomMic.swift) and Windows':
-/// twice the room's noise, between -56 and -40 dBFS, the noise being the quietest moment of each
-/// second (the gaps between words, even while people talk on and on), taken low over the last half
-/// minute. A phone's VOICE_RECOGNITION input has no gain control, so a voice a metre away comes in
-/// around -50 dBFS and a fixed -40 dBFS line never opened once (#30).
class VoiceGate {
companion object {
const val FIXED = 0.01
@@ -309,7 +242,6 @@ class VoiceGate {
return minOf(FIXED, maxOf(LOWEST, floor * 2))
}
- /// Takes one frame's level and length; true when it is over the line.
fun voiced(rms: Double, seconds: Double): Boolean {
val on = rms >= threshold
second = minOf(second, rms)
@@ -324,7 +256,6 @@ class VoiceGate {
}
}
-/// A growable ShortArray (no boxing on the audio path).
internal class ShortList {
private var a = ShortArray(RATE_HINT)
var size = 0; private set
diff --git a/android/core/src/main/kotlin/cicada/SessionStore.kt b/android/core/src/main/kotlin/cicada/SessionStore.kt
index b6a0b8d..3d318dc 100644
--- a/android/core/src/main/kotlin/cicada/SessionStore.kt
+++ b/android/core/src/main/kotlin/cicada/SessionStore.kt
@@ -9,9 +9,6 @@ import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
-/// The meeting records: one folder per meeting under Sessions/<yyyyMMdd-HHmmss>/ with
-/// session.json, as on the Mac. Saves are debounced by 1.5 s; a meeting with no lines is removed
-/// when it ends. Thread-safe; `changed` fires on whichever thread made the change.
class SessionStore(loadNow: Boolean = true) {
private val gate = Any()
private val sessions = HashMap<String, Session>()
@@ -20,10 +17,8 @@ class SessionStore(loadNow: Boolean = true) {
private var pendingSave: ScheduledFuture<*>? = null
private val listeners = mutableListOf<(String) -> Unit>()
- /// The meeting being listened to (begin to end): it can't be deleted, as on the Mac.
@Volatile var liveId: String? = null; private set
- /// Whether the records on disk have been read (the app reads them off the main thread).
@Volatile var loaded = false; private set
init { if (loadNow) load() }
@@ -34,8 +29,6 @@ class SessionStore(loadNow: Boolean = true) {
private fun folder(id: String) = File(Paths.sessions, id)
private fun fileOf(id: String) = File(folder(id), "session.json")
- /// Reads every record on disk; the app calls this on a background thread at launch (hundreds of
- /// records take seconds), so a meeting begun meanwhile is kept, not overwritten.
fun load() {
val dirs = Paths.sessions.listFiles() ?: run { loaded = true; fire(""); return }
for (dir in dirs) {
@@ -43,8 +36,6 @@ class SessionStore(loadNow: Boolean = true) {
if (!file.isFile) continue
try {
val s = Session.read(file.readText()) ?: continue
- // A meeting the app was killed in (a phone does that) never ended: it ends at its
- // last line, so its length doesn't keep growing with the clock.
if (s.endedAt == null) {
s.endedAt = s.startedAt.plusMillis((((s.lines.lastOrNull()?.t ?: 0.0) + 5) * 1000).toLong())
synchronized(gate) { dirty.add(s.id) }
@@ -58,12 +49,10 @@ class SessionStore(loadNow: Boolean = true) {
fire("")
}
- /// Newest first.
fun all(): List<Session> = synchronized(gate) { sessions.values.sortedByDescending { it.startedAt } }
fun get(id: String): Session? = synchronized(gate) { sessions[id] }
- /// A copy of a record's lines, safe to read while listening adds to them.
fun lines(id: String): List<TranscriptLine> = synchronized(gate) { sessions[id]?.lines?.map { it.copy() } ?: emptyList() }
fun begin(at: Instant = Instant.now()): Session {
@@ -76,14 +65,11 @@ class SessionStore(loadNow: Boolean = true) {
fun append(id: String, line: TranscriptLine) = mutate(id) { it.lines.add(line) }
- /// Listening's newer text or translation for a line. Its fixes stay the store's own (LiveFixes
- /// sets them with setFixes): a fix whose words are no longer in the line is simply not shown.
fun replace(id: String, line: TranscriptLine) = mutate(id) { s ->
val i = s.lines.indexOfFirst { it.id == line.id }
if (i >= 0) { line.fixes = s.lines[i].fixes; s.lines[i] = line }
}
- /// A line's fixes (Correction): what the AI service proposed and the user decided; none is null.
fun setFixes(id: String, lineId: String, fixes: List<LineFix>) {
val changed = synchronized(gate) {
val l = sessions[id]?.lines?.firstOrNull { it.id == lineId } ?: return
@@ -94,21 +80,16 @@ class SessionStore(loadNow: Boolean = true) {
if (changed) { markDirty(id); fire(id) }
}
- /// The line a reply was for, by its text as heard: the newest such line in the live meeting,
- /// else in a file being imported. Older meetings never: "好的。" is in all of them.
fun lineHeard(text: String): Pair<String, TranscriptLine>? {
val ids = listOfNotNull(liveId) + synchronized(gate) { sessions.values.filter { it.importing == true }.map { it.id } }
for (id in ids) synchronized(gate) { sessions[id]?.lines?.lastOrNull { it.src == text }?.copy() }?.let { return id to it }
return null
}
- /// A copy of one line, or null.
fun line(id: String, lineId: String): TranscriptLine? = synchronized(gate) { sessions[id]?.lines?.firstOrNull { it.id == lineId }?.copy() }
fun setNotes(id: String, notes: MeetingNotes) = mutate(id) { it.notes = notes }
- /// The Mac's rename: the title already shown changes nothing (so saving the dialog untouched
- /// doesn't freeze the automatic title), and an empty one goes back to the automatic title.
fun rename(id: String, title: String) = mutate(id) { s ->
val t = title.trim()
if (t == displayTitle(s)) return@mutate
@@ -116,16 +97,12 @@ class SessionStore(loadNow: Boolean = true) {
else { s.title = t; s.renamed = true }
}
- /// The user names a voice (the Mac's setVoiceName): null drops their name (Ling's guess shows
- /// again); "" keeps 说话人 N.
fun setVoiceName(id: String, voice: Int, name: String?) = mutate(id) { s ->
val names = (s.voiceNames ?: emptyMap()).toMutableMap()
if (name == null) names.remove(voice.toString()) else names[voice.toString()] = name.trim()
s.voiceNames = names
}
- /// Ling's latest guesses (SpeakerNamer); earlier ones stay for voices it no longer mentions,
- /// unless it now named them without evidence (refuted, voice → name): then that earlier name goes too.
fun setVoiceGuesses(id: String, guesses: Map<Int, VoiceGuess>, refuted: Map<Int, String> = emptyMap()) {
if (guesses.isEmpty() && refuted.isEmpty()) return
mutate(id) { s ->
@@ -136,14 +113,10 @@ class SessionStore(loadNow: Boolean = true) {
}
}
- /// Fields set once around a meeting (its recording, an imported file's name and progress).
fun update(id: String, change: (Session) -> Unit) = mutate(id, change)
- /// Where a meeting's recording is (the Mac's system.m4a: what was heard).
fun audioFile(id: String) = File(folder(id), "system.m4a")
- /// The meeting ended (`at`: when it really did, for one that ended by itself): kept if
- /// anything was said, removed otherwise.
fun end(id: String, at: Instant? = null) {
val empty = synchronized(gate) {
if (liveId == id) liveId = null
@@ -154,7 +127,6 @@ class SessionStore(loadNow: Boolean = true) {
if (empty) deleteNow(id) else { markDirty(id); flush() }
}
- /// Not the meeting being listened to: its next lines would vanish with it.
fun delete(id: String) {
if (id == liveId) { Log.d("store: kept $id, it is live"); return }
deleteNow(id)
@@ -166,7 +138,6 @@ class SessionStore(loadNow: Boolean = true) {
fire(id)
}
- /// A record from elsewhere (a Mac's session.json): added as it is, saved now.
fun import(session: Session) {
synchronized(gate) { sessions[session.id] = session }
markDirty(session.id); flush(); fire(session.id)
@@ -186,7 +157,6 @@ class SessionStore(loadNow: Boolean = true) {
}
}
- /// Writes every changed record now (also when the app goes to the background).
fun flush() {
val writes = synchronized(gate) {
val list = dirty.mapNotNull { id -> sessions[id]?.let { id to Json.write(it.toJson()) } }
@@ -204,20 +174,15 @@ class SessionStore(loadNow: Boolean = true) {
}
companion object {
- /// The stored default title is always Chinese ("会议 11月1日 14:30"), as on the Mac; the UI
- /// shows displayTitle instead.
fun defaultTitle(at: Instant): String =
"会议 " + DateTimeFormatter.ofPattern("M月d日 HH:mm", Locale.ROOT).withZone(ZoneId.systemDefault()).format(at)
private fun localDate(at: Instant, pattern: String): String =
DateTimeFormatter.ofPattern(pattern, Strings.locale).withZone(ZoneId.systemDefault()).format(at)
- /// The user's own title, else the date and the name the notes gave the meeting, else the
- /// default title in the UI language (Session.displayTitle).
fun displayTitle(s: Session): String {
if (s.renamed ?: !s.title.startsWith("会议 ")) return s.title
val name = s.notes?.title
- // An imported file (from the Mac) is known by its name until the notes give it one.
if (name.isNullOrEmpty() && s.sourceFile != null) return s.sourceFile!!.substringBeforeLast('.')
if (name.isNullOrEmpty()) return Strings.L("会议") + " " + localDate(s.startedAt, Strings.L("M月d日 HH:mm"))
val thisYear = s.startedAt.atZone(ZoneId.systemDefault()).year == Instant.now().atZone(ZoneId.systemDefault()).year
@@ -226,7 +191,6 @@ class SessionStore(loadNow: Boolean = true) {
fun stamp(at: Instant): String = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneId.systemDefault()).format(at)
- /// The record as Markdown, as the Mac writes it (TranscriptExport.markdown).
fun markdown(s: Session): String = TranscriptExport.markdown(s)
}
}
diff --git a/android/core/src/main/kotlin/cicada/Settings.kt b/android/core/src/main/kotlin/cicada/Settings.kt
index 87bedc5..a64e1e2 100644
--- a/android/core/src/main/kotlin/cicada/Settings.kt
+++ b/android/core/src/main/kotlin/cicada/Settings.kt
@@ -2,16 +2,10 @@ package cicada
import java.util.Locale
-/// The app's settings, in settings.json beside the records (never the Ling key: that has its own file).
class AppSettings(
- /// What subtitles translate into; "system" follows the phone's language.
var target: String = "system",
- /// 纪要语言: the notes' language code; "system" is the same as the subtitles'.
var notesLanguage: String = "system",
- /// Ling's text model (the other services' are in aiModels).
var model: String = LingClient.DEFAULT_MODEL,
- /// AI 服务 (Settings.swift's keys): the service, and per service the models chosen over its
- /// recommended ones. aiHearModels is the ports' own: what hears the audio (Ming on Ling).
var aiProvider: String = "ling",
var aiModels: MutableMap<String, String> = mutableMapOf(),
var aiHearModels: MutableMap<String, String> = mutableMapOf(),
@@ -19,69 +13,38 @@ class AppSettings(
var aiCustomBase: String = "",
var aiCustomVoiceBase: String = "",
var aiCustomVoice: String = "",
- /// The custom service's hear model's own address (the Mac's aiCustomHearBase); empty: the text model's.
var aiCustomHearBase: String = "",
- /// 语音和文字只发给你的服务: with the custom service, Google Translate is never asked. Kept when
- /// another service is picked, but only acts on the custom one (`customOnly`).
var aiCustomOnly: Boolean = false,
- /// The custom service's notes: 另一个服务 (its own address, empty: the same one, and its own key
- /// in the `custom-notes` key file). Off keeps the address, so switching back and forth loses
- /// nothing. The notes model is `aiModels["custom.notes"]` (empty: the translation model).
var aiCustomNotesOwn: Boolean = false,
var aiCustomNotesBase: String = "",
- /// "notes" (live notes, default) or "subtitles" (the subtitle bar), for the floating window.
var view: String = "notes",
- /// 共享屏幕时让对方看到: let the floating window show up in screenshots and screen recording.
var showInCapture: Boolean = false,
var onboarded: Boolean = false,
- /// The UI language: "system", "zh-Hans", "en", "ja" or "ko".
var uiLanguage: String = "system",
- /// Where listening hears from: "playback" (what the phone plays) or "mic" (面对面).
var source: String = "playback",
- /// Whether the floating window shows while listening (it needs 显示在其他应用上层).
var overlay: Boolean = true,
- /// 没人说话时: "prompt" (count down, then end), "end" (end at once) or "off" (keep recording).
var silenceEnd: String = "prompt",
- /// 多久算没人说话, in minutes: 5, 10, 15 or 30.
var silenceMinutes: Double = 10.0,
- /// 说话人识别: tell the other side's voices apart and number them (the Mac's speakerVoices).
var speakerVoices: Boolean = true,
- /// 保存会议录音: keep what was heard as system.m4a beside the record (the Mac's recordAudio).
var recordAudio: Boolean = true,
- /// 把我说的翻译给对方: 按住说话 in 面对面 (the Mac's 同声传译 switch).
var speakBack: Boolean = true,
- /// 读出来的声音 per language key ("en", "zh"), as the Mac's speakVoices: "ming:US_Emma",
- /// "cloud:Kore", "phone". A language not in it uses VoiceCatalog.defaultId.
var speakVoices: MutableMap<String, String> = mutableMapOf(),
- /// 会中改正听错的词: finished sentences carry the word list to the AI service, which points out
- /// misheard words (Correction). On by default; does nothing without an AI service.
var fixMisheard: Boolean = true,
- /// 没见过的名字和专称先问我: a new name is asked about once instead of left as heard.
var askNames: Boolean = true,
- /// 存到文件夹: settled meetings are also written as Markdown into `exportFolder`, a SAF tree URI
- /// (empty until one is chosen), whose short name "parent › folder" is `exportName`. Not secrets.
var exportOn: Boolean = false,
var exportFolder: String = "",
var exportName: String = "",
- /// When GitHub Releases last answered an update check (epoch ms; UpdateChecker).
var updateLastChecked: Long? = null,
- /// The newest version a notification was posted for, so each one is announced once.
var updateNotified: String? = null,
) {
- /// My language: the translate-to choice, or under "follow system" the Mac's myLanguage
- /// (Chinese when the system list has it, else the first). 我说, notes and the UI start from it.
val targetCode: String get() = if (target == "system") Languages.myLanguage(systemLanguages()) else target
val notesCode: String get() = if (notesLanguage == "system") targetCode else notesLanguage
- /// What subtitles translate `source` into: under "follow system", my language unless that is
- /// what they speak, then the next system language (the Mac's followSystemTarget).
fun targetFor(source: String?): String =
if (target == "system") Languages.followSystemTarget(source, systemLanguages()) else target
- /// The AI service in use, its address and models (what LingClient calls with).
fun aiConfig(): AIConfig = Providers.configFrom(this)
- /// 语音和文字只发给你的服务 in effect: on, and the custom service in use.
val customOnly: Boolean get() = aiCustomOnly && aiProvider == "custom"
fun toJson(): Map<String, Any?> = mapOf(
@@ -107,8 +70,6 @@ class AppSettings(
}
companion object {
- /// The phone's languages, most preferred first (the app reads the system's list; the
- /// JVM's default locale stands in for tests and the CLI).
@Volatile var systemLanguages: () -> List<String> = { listOf(Locale.getDefault().toLanguageTag()) }
fun load(): AppSettings {
diff --git a/android/core/src/main/kotlin/cicada/Share.kt b/android/core/src/main/kotlin/cicada/Share.kt
index d902ce5..56050b8 100644
--- a/android/core/src/main/kotlin/cicada/Share.kt
+++ b/android/core/src/main/kotlin/cicada/Share.kt
@@ -9,16 +9,9 @@ import java.util.Base64
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
-// A meeting shared as a link on cicada.indaloop.app (ShareProjection.swift, ShareClient.swift).
-
enum class ShareScope(val id: String) { Notes("notes"), Full("full") }
-/// The share document (v1): what goes to the share page, made from a meeting record. Only these
-/// fields leave the phone: never the record's file paths, Ling's guesses at names with the lines
-/// they came from, or the record's own bookkeeping. Speakers are 说话人 N unless the user chose to
-/// show names. The same bytes as the Mac (Tests/fixtures/share); server/src/doc.js reads them.
object ShareProjection {
- /// `removed`: indices into the record's lines the user took out; `dropNotes` leaves the notes out.
fun doc(s: Session, scope: ShareScope, names: Boolean, removed: Set<Int> = emptySet(), dropNotes: Boolean = false): Map<String, Any?> {
val numbers = SpeakerLabels.numbers(s.lines)
val nameMap = if (names) SpeakerLabels.names(s) else emptyMap()
@@ -52,34 +45,27 @@ object ShareProjection {
)
}
- /// The meeting's usual direction ("en" → "zh"), by the most lines; ties go to the earliest.
fun languages(lines: List<TranscriptLine>): List<String> {
val count = LinkedHashMap<String, Int>()
for (l in lines) if (l.dst != null) {
val key = base(l.srcLang) + ">" + base(l.dstLang)
count[key] = (count[key] ?: 0) + 1
}
- // LinkedHashMap keeps first-seen order, so the first of the most is the earliest.
val top = count.entries.fold(null as Map.Entry<String, Int>?) { best, e -> if (best == null || e.value > best.value) e else best } ?: return emptyList()
- return top.key.split(">").filter { it.isNotEmpty() } // Swift's split drops empty parts
+ return top.key.split(">").filter { it.isNotEmpty() }
}
private fun base(code: String) = (code.split("-").firstOrNull { it.isNotEmpty() } ?: code).lowercase()
- /// One decimal, halves away from zero as Swift's rounded(): the page shows seconds, and short
- /// numbers keep the bytes the same on every platform.
fun round(t: Double): Double = Math.signum(t) * Math.floor(Math.abs(t) * 10 + 0.5) / 10
- /// Compact, sorted keys, "/" unescaped: JSONEncoder's [.sortedKeys, .withoutEscapingSlashes].
fun encode(doc: Map<String, Any?>): String = Json.write(doc, pretty = false, slashes = false)
}
-/// Where the review found a problem: the notes, or lines `from`…`to` of what was sent.
data class ShareHit(val part: String, val from: Int?, val to: Int?, val questions: List<String>) {
companion object {
fun from(o: Map<String, Any?>) = ShareHit(o["part"].str() ?: "", o["from"].int(), o["to"].int(), o["questions"].arr().mapNotNull { it.str() })
- /// The record's line indices behind the hits, given which record lines were sent (`kept`).
fun recordLines(hits: List<ShareHit>, kept: List<Int>): Set<Int> {
val out = HashSet<Int>()
for (h in hits) if (h.part == "lines") {
@@ -95,14 +81,9 @@ data class ShareHit(val part: String, val from: Int?, val to: Int?, val question
object SharePassword {
const val ITERATIONS = 210_000
- /// PBKDF2-SHA256, 32 bytes: what the browser derives from the password (site/share.js). The
- /// server keeps only its hash, so the password never leaves either side. Written out over the
- /// platform's HMAC-SHA256 (one block is all 32 bytes need) rather than SecretKeyFactory, whose
- /// providers turn the password into bytes differently on Android and the JDK.
fun verifier(password: String, salt: ByteArray, iterations: Int = ITERATIONS): ByteArray {
val mac = Mac.getInstance("HmacSHA256")
mac.init(SecretKeySpec(password.toByteArray(Charsets.UTF_8).let { if (it.isEmpty()) ByteArray(1) else it }, "HmacSHA256"))
- // An empty password can't be a SecretKeySpec; HMAC pads keys with zeros, so one zero byte is the same key.
var u = mac.doFinal(salt + byteArrayOf(0, 0, 0, 1))
val out = u.copyOf()
for (i in 1 until iterations) {
@@ -112,7 +93,6 @@ object SharePassword {
return out
}
- /// "ruby-41-lake": easy to read out and type; the server limits how many can be tried.
fun make(random: java.util.Random = SecureRandom()): String {
val w = WORDS.split(" ")
return "${w[random.nextInt(w.size)]}-${10 + random.nextInt(90)}-${w[random.nextInt(w.size)]}"
@@ -121,9 +101,6 @@ object SharePassword {
private const val WORDS = "amber apple arrow aspen basil beach birch bloom brook cedar cherry cloud coral comet dawn delta dune ember fern field flint frost grove harbor hazel honey iris island jade lake lark lemon lily linen maple meadow mint moss olive orbit pearl pine plum pond quartz rain reed river ruby sage sand shell silk sky slate snow spruce stone storm sun tide tulip velvet willow wind"
}
-/// What the phone keeps about a shared meeting. The manage token (needed to turn the link off)
-/// lives only here, in the app's private files (Shares/<record id>.json), never in the record,
-/// exports or logs; so does the password, so it can be copied again.
data class ShareRecord(
val id: String, val url: String, val token: String, val expiresAt: Instant,
val scope: String, val password: String?, val createdAt: Instant,
@@ -133,14 +110,9 @@ data class ShareRecord(
"scope" to scope, "password" to password, "createdAt" to Iso8601.write(createdAt),
)
- /// Whole days the link stays open, rounded up. Ten minutes of slack: the server's clock, not
- /// the phone's, set the expiry.
fun daysLeft(now: Instant = Instant.now()): Long =
maxOf(1L, Math.ceil((expiresAt.epochSecond - now.epochSecond - 600) / 86400.0).toLong())
- /// What 生成并复制 and 复制 put on the clipboard (and 分享 sends), in the UI's language: the
- /// title, the link on a line of its own (chat apps then make it a link), the password and how
- /// long it stays open (ShareSheet.clipboardText on the Mac).
fun message(title: String, now: Instant = Instant.now()): String {
val left = daysLeft(now)
val valid = if (left >= 365) Strings.L("1 年内有效") else Strings.LF("%lld 天内有效", left)
@@ -158,8 +130,6 @@ data class ShareRecord(
}
}
-/// Shares/<record id>.json and the device key, in the app's private folder (Paths.root), readable
-/// by this app only and left out of backups and device transfers (data_extraction_rules.xml).
object ShareStore {
val folder get() = File(Paths.root, "Shares")
val deviceFile get() = File(Paths.root, "share-device.json")
@@ -189,20 +159,12 @@ object ShareStore {
}
}
-/// Talks to the share service on cicada.indaloop.app (server/). There are no accounts: this phone
-/// is an Ed25519 key made on first use (share-device.json), registered once with a small proof of
-/// work, and every write is signed (method, path, time, nonce, body hash), as server/src/auth.js
-/// checks. Not an AI call, so not LingClient: the review runs on the server. Calls block: run
-/// them off the main thread.
class ShareClient(
private val platform: String,
private val version: String,
private val transport: Transport = UrlTransport,
- /// The dev build can point at a local Worker.
var base: String = "https://cicada.indaloop.app",
) {
- /// Where this phone's key and registration live; the dev build gives a local Worker its own
- /// file so switching back never re-registers with cicada.indaloop.app.
var deviceFile: File? = null
private val keyFile get() = deviceFile ?: ShareStore.deviceFile
@@ -240,7 +202,6 @@ class ShareClient(
ShareStore.writePrivate(keyFile, Json.write(mapOf("key" to Base64.getEncoder().encodeToString(seed), "device" to id, "server" to server)))
}
- /// The device, registering this phone with the server first if needed (one at a time).
private fun device(force: Boolean = false): Device = synchronized(gate) {
val d = loadDevice()
if (!force && d.id != null && d.server == base) return d
@@ -275,7 +236,6 @@ class ShareClient(
return try { transport.send(base + path, method, body, h, 90_000) } catch (e: IOException) { throw Failure("network") }
}
- /// A signed call; registers again once if the server no longer knows this phone.
private fun signed(method: String, path: String, body: String? = null, headers: Map<String, String> = emptyMap()): Transport.Response {
var r = send(method, path, body, headers, device())
if (r.status == 401 && code(r.body) == "unknown_device") r = send(method, path, body, headers, device(force = true))
@@ -297,8 +257,6 @@ class ShareClient(
"hash" to b64url(sha256(SharePassword.verifier(pw, salt))))
}
return try {
- // The same meeting, content and settings sent again (the answer was lost) gets the same
- // link back; any other setting makes a new share.
val settings = "${o.scope.id}|${o.days}|${o.names}|${o.password ?: ""}|${o.summaryInPreview}"
val idem = s.id + "-" + hex(sha256(encoded.toByteArray(Charsets.UTF_8) + settings.toByteArray(Charsets.UTF_8)).copyOf(8))
val r = signed("POST", "/api/v1/shares", Json.write(body, pretty = false, slashes = false), mapOf("Idempotency-Key" to idem))
@@ -333,11 +291,9 @@ class ShareClient(
}
}
- /// Turns the link off on the server and forgets it here. `sessionId` null: the record is being replaced.
fun revoke(r: ShareRecord, sessionId: String?): Boolean {
val ok = try {
val res = signed("DELETE", "/api/v1/shares/${r.id}", headers = mapOf("Authorization" to "Bearer ${r.token}"))
- // 404: already gone (or never ours); either way nothing to keep.
(res.status == 204 || res.status == 404).also { if (!it) Log.d("share: revoke ${r.id} failed ${res.status} ${code(res.body) ?: "?"}") }
} catch (e: Exception) {
Log.d("share: revoke ${r.id} failed ${e.message}")
@@ -360,7 +316,6 @@ class ShareClient(
}
companion object {
- /// 20 leading zero bits of sha256(public key ‖ 8-byte big-endian nonce): about a million hashes.
fun proofOfWork(pub: ByteArray): ByteArray {
val md = MessageDigest.getInstance("SHA-256")
val nonce = ByteArray(8)
diff --git a/android/core/src/main/kotlin/cicada/Speakers.kt b/android/core/src/main/kotlin/cicada/Speakers.kt
index 70218ab..32bbcf3 100644
--- a/android/core/src/main/kotlin/cicada/Speakers.kt
+++ b/android/core/src/main/kotlin/cicada/Speakers.kt
@@ -2,31 +2,19 @@ package cicada
import kotlin.math.sqrt
-/// 说话人识别: telling the other side's voices apart (SpeakerID.swift; linux/cicada/core/speakers.py).
/// Each heard line's audio becomes a voiceprint (WeSpeaker ResNet34-LM, VoxCeleb, CC BY 4.0),
-/// voiceprints are grouped as they arrive, and a voice is only shown once it has a few lines
-/// (SpeakerLabels). The thresholds are the Mac's, tuned on AMI meetings.
-///
-/// The model runs in linux/native/voiceprint.c, built into the app with the NDK: the app gives a
-/// `Voiceprinter`; this plain-JVM side only groups. Without one the feature is unavailable and
-/// listening carries on as before.
interface Voiceprinter {
- /// A unit-length voiceprint of 16 kHz mono samples, or null (too short, or it failed).
fun embed(samples: ShortArray): FloatArray?
}
-/// Groups voiceprints as lines arrive, never revising a line already labelled. A line joins the
-/// closest voice when similar enough; a long line unlike every voice starts a new one; anything
-/// else stays unlabelled (对方). (VoiceClusterer, SpeakerID.swift.)
class VoiceClusterer {
private val sums = ArrayList<FloatArray>()
- /// The user said two voices are one: later lines like either go to `into`.
fun merge(from: Int, into: Int) {
if (from !in sums.indices || into !in sums.indices || from == into) return
val a = sums[into]; val b = sums[from]
for (i in a.indices) a[i] += b[i]
- b.fill(0f) // never the closest again
+ b.fill(0f)
}
fun label(v: FloatArray, seconds: Double): Int? {
@@ -56,15 +44,12 @@ class VoiceClusterer {
}
}
-/// Voiceprints for listening: `embed` runs on the engine's voice thread while Ming hears the same
-/// segment; `label` is called in segment order.
open class SpeakerTagger(private val voiceprints: Voiceprinter?) {
private val gate = Any()
private var clusterer = VoiceClusterer()
val available: Boolean get() = voiceprints != null
- /// A new meeting: forget the voices of the last one.
fun reset() = synchronized(gate) { clusterer = VoiceClusterer() }
fun merge(from: Int, into: Int) = synchronized(gate) { clusterer.merge(from, into) }
@@ -82,9 +67,6 @@ open class SpeakerTagger(private val voiceprints: Voiceprinter?) {
companion object { const val MIN_SECONDS = 0.5 }
}
-/// Names from the conversation (SpeakerNameGuess, SpeakerNamer): asks Ling on its own once two
-/// voices are on show, again every 20 lines, and once more when the meeting ends. Guesses go
-/// straight into the meeting (voiceGuesses); the user corrects them.
class SpeakerNamer(private val ling: LingClient, private val store: SessionStore) {
private val gate = Any()
private val busy = HashSet<String>()
@@ -100,7 +82,7 @@ class SpeakerNamer(private val ling: LingClient, private val store: SessionStore
if (id in busy || !(force || lines.size >= (asked[id] ?: -1000) + 20)) return
text = content(lines) ?: return
val numbers = SpeakerLabels.voiceNumbers(lines)
- if (numbers.keys.all { s.voiceNames?.get(it.toString()) != null }) return // everyone already has the user's name
+ if (numbers.keys.all { s.voiceNames?.get(it.toString()) != null }) return
busy.add(id)
asked[id] = lines.size
}
@@ -125,7 +107,6 @@ class SpeakerNamer(private val ling: LingClient, private val store: SessionStore
}
companion object {
- /// Ling's prompt, word for word the Mac's.
const val INSTRUCTION = "Who are the people labelled 说话人N? Name one only when the transcript makes it clear: they " +
"introduce themselves on a line labelled with their own 说话人N; someone addresses them by name just " +
"before or after they speak (\"Thanks, George\" right after 说话人1's answer: 说话人1 is George); " +
@@ -137,10 +118,8 @@ class SpeakerNamer(private val ling: LingClient, private val store: SessionStore
"you are unsure of. Reply as JSON: {\"speakers\": [{\"speaker\": 2, \"name\": \"George\", \"evidence\": \"L12\"}]}, " +
"the evidence being the line with the name; an empty list if none. Check each name's spelling before replying."
- /// "Okay, Amos, thank you" comes right after Amos's last words.
const val EVIDENCE_REACH = 2
- /// The transcript as Ling sees it, newest 400 lines, with speaker labels; null when no voices are shown.
fun content(lines: List<TranscriptLine>): String? {
val numbers = SpeakerLabels.voiceNumbers(lines)
if (numbers.isEmpty()) return null
@@ -154,11 +133,8 @@ class SpeakerNamer(private val ling: LingClient, private val store: SessionStore
return sb.toString()
}
- /// (found: voice → guess, refuted: voice → name). A name given on a line the voice neither
- /// said nor spoke next to is refuted; a name Ling gives two voices goes to the one with more lines.
fun read(reply: String, all: List<TranscriptLine>): Pair<MutableMap<Int, VoiceGuess>, MutableMap<Int, String>> {
val found = LinkedHashMap<Int, VoiceGuess>(); val refuted = LinkedHashMap<Int, String>()
- // Without JSON mode (a host that refuses it) the object may come in a fence or a sentence.
val a = reply.indexOf('{'); val z = reply.lastIndexOf('}')
val list = (if (a in 0 until z) Json.parseObject(reply.substring(a, z + 1)) else null)?.get("speakers").arr() ?: return found to refuted
val voiceOf = SpeakerLabels.voiceNumbers(all).entries.associate { (v, n) -> n to v }
@@ -186,7 +162,6 @@ class SpeakerNamer(private val ling: LingClient, private val store: SessionStore
return found to refuted
}
- /// Whether a stored guess still stands: its evidence line is found again and the voice speaks there.
fun holds(g: VoiceGuess, v: Int, lines: List<TranscriptLine>): Boolean {
if (!g.evidence.contains("“")) return true
val at = g.evidence.substringBefore("“").trim()
diff --git a/android/core/src/main/kotlin/cicada/Strings.kt b/android/core/src/main/kotlin/cicada/Strings.kt
index b5bcc02..c39b72f 100644
--- a/android/core/src/main/kotlin/cicada/Strings.kt
+++ b/android/core/src/main/kotlin/cicada/Strings.kt
@@ -2,17 +2,10 @@ package cicada
import java.util.Locale
-/// UI text. The Chinese text is the key, as on the Mac, and the translations are the Mac's own
-/// `Resources/{en,ja,ko}.lproj/Localizable.strings` (copied into the APK's assets at build time),
-/// plus `Android.strings` for text only the Android app has, and the Mac's
-/// `Localizable.stringsdict` for plurals ("1 line", "2 lines"). Placeholders are the Mac's `%@`,
-/// filled in order. Never for prompts, logs or stored values.
object Strings {
@Volatile private var table: Map<String, String> = emptyMap()
@Volatile private var plurals: Map<String, Plural> = emptyMap()
- /// A stringsdict entry: the format with `%#@n@` placeholders, and each variable's forms by
- /// plural category ("one", "other").
class Plural(val format: String, val forms: Map<String, Map<String, String>>)
@Volatile var language = "zh-Hans"; private set
@@ -20,13 +13,10 @@ object Strings {
"en" -> Locale.ENGLISH; "ja" -> Locale.JAPANESE; "ko" -> Locale.KOREAN; else -> Locale.SIMPLIFIED_CHINESE
}
- /// Loads the table for `ui` ("en", "ja", "ko"; anything else is Chinese). `read` returns the
- /// text of "<lang>.lproj/<name>" or null.
fun load(ui: String, read: (String) -> String?) {
val head = ui.split('-', '_')[0]
language = if (head == "en" || head == "ja" || head == "ko") head else "zh-Hans"
val t = HashMap<String, String>()
- // The Mac's table, then the Android-only strings over it (same format).
for (name in listOf("Localizable.strings", "Android.strings")) {
read("$language.lproj/$name")?.let { t.putAll(parse(it)) }
}
@@ -34,15 +24,11 @@ object Strings {
plurals = read("$language.lproj/Localizable.stringsdict")?.let { parsePlurals(it) } ?: emptyMap()
}
- /// Only English has more than one form among the app's languages: "one" for exactly 1.
private fun category(n: Any?): String =
if (language == "en" && (n as? Number)?.toDouble() == 1.0) "one" else "other"
@JvmStatic fun L(key: String): String = table[key]?.takeIf { it.isNotEmpty() } ?: key
- /// L() with the Mac's placeholders filled in order: `%@` (or `%1$@` by position), and the
- /// numbers `%lld` / `%ld` / `%d`. A key in the stringsdict takes its plural form for the
- /// number: `%#@n@` (or `%2$#@n@`) becomes variable n's "one" or "other" text.
@JvmStatic fun LF(key: String, vararg args: Any): String {
val plural = plurals[key]
val text = plural?.format ?: L(key)
@@ -51,7 +37,6 @@ object Strings {
var i = 0
while (i < text.length) {
if (text[i] != '%' || i + 1 >= text.length) { b.append(text[i]); i++; continue }
- // An optional position: %2$…
var j = i + 1
var position: Int? = null
if (text[j].isDigit() && j + 1 < text.length && text[j + 1] == '$') { position = text[j] - '1'; j += 2 }
@@ -73,8 +58,6 @@ object Strings {
return b.toString()
}
- /// The Mac's Localizable.stringsdict (an XML plist of dicts and strings) as key → Plural. A
- /// small reader of its own: the XML parsers want to fetch the plist DTD from apple.com.
fun parsePlurals(xml: String): Map<String, Plural> {
var i = 0
fun tag(): String? {
@@ -114,7 +97,6 @@ object Strings {
return result
}
- /// `"key" = "value";` lines, with /* */ and // comments and \" \\ \n escapes.
fun parse(text: String): Map<String, String> {
val result = HashMap<String, String>()
var i = 0
diff --git a/android/core/src/main/kotlin/cicada/Support.kt b/android/core/src/main/kotlin/cicada/Support.kt
index c05ad4d..afe7e36 100644
--- a/android/core/src/main/kotlin/cicada/Support.kt
+++ b/android/core/src/main/kotlin/cicada/Support.kt
@@ -5,26 +5,19 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
-/// Where the app keeps its files. On Android the app sets `root` to its private filesDir (the dev
-/// build has its own app id, so its own folder) and `log` into its cache; tests and the CLI point
-/// it at a temp folder, or CICADA_HOME.
object Paths {
@Volatile var root: File = File(System.getenv("CICADA_HOME") ?: (System.getProperty("java.io.tmpdir") + "/cicada-cli"))
@Volatile var log: File = File(System.getProperty("java.io.tmpdir"), "cicada-debug.log")
val sessions get() = File(root, "Sessions")
val settings get() = File(root, "settings.json")
- /// 词表, beside the records as on the Mac (not a secret).
val vocabulary get() = File(root, "vocabulary.json")
val keyFile get() = keyFile("ling")
- /// One key file per AI service, named as on the Mac.
fun keyFile(service: String) = File(root, if (service == "ling") "ling-api-key" else "ai-key-$service")
}
-/// The debug log: timings and states, never meeting text or the key.
object Log {
private val gate = Any()
@Volatile var echo = false
- /// Also handed to the platform log (logcat) when set.
@Volatile var sink: ((String) -> Unit)? = null
private val clock = object : ThreadLocal<SimpleDateFormat>() {
override fun initialValue() = SimpleDateFormat("HH:mm:ss.SSS", Locale.US)
@@ -42,7 +35,6 @@ object Log {
data class Lang(val name: String, val code: String)
-/// The languages the Mac app offers (Languages.swift), as translation codes.
object Languages {
val sources = listOf(
Lang("English", "en"), Lang("日本語", "ja"), Lang("中文", "zh-CN"), Lang("한국어", "ko"),
@@ -54,36 +46,28 @@ object Languages {
Lang("한국어", "ko"), Lang("Español", "es"), Lang("Français", "fr"), Lang("Deutsch", "de"), Lang("Português", "pt"),
)
- /// "Simplified Chinese", "Japanese": the names prompts use.
fun englishName(code: String): String = when (code) {
"zh-CN" -> "Simplified Chinese"
"zh-TW" -> "Traditional Chinese"
else -> Locale.forLanguageTag(code).getDisplayLanguage(Locale.ENGLISH).ifEmpty { code }
}
- /// A system UI language ("zh-Hans-CN", "zh-TW", "en-US") as a translation code.
fun fromSystem(tag: String): String {
val parts = tag.split('-', '_')
if (parts[0] != "zh") return parts[0]
- // As the Mac's translationCode: the script decides; a region only when there's none.
if ("Hant" in parts) return "zh-TW"
if ("Hans" in parts) return "zh-CN"
return if (parts.any { it in setOf("TW", "HK", "MO") }) "zh-TW" else "zh-CN"
}
- /// The Mac's myLanguage: Chinese when the system list has it (the app speaks Chinese),
- /// otherwise the first system language.
fun myLanguage(prefs: List<String>): String = fromSystem(prefs.firstOrNull { it.startsWith("zh") } ?: prefs.firstOrNull() ?: "zh-Hans")
- /// The Mac's followSystemTarget: my language, unless that is what they speak; then the next
- /// system language, or between Chinese and English when the system has only one.
fun followSystemTarget(source: String?, prefs: List<String>): String {
val mine = myLanguage(prefs)
if (source == null || source != mine) return mine
return prefs.map(::fromSystem).firstOrNull { it != mine } ?: if (mine.startsWith("zh")) "en" else "zh-CN"
}
- /// Normalizes what Ming says the language is ("zh", "zh-Hans", "cmn") to a source code.
fun normalize(reported: String?, fallback: String): String {
if (reported.isNullOrBlank()) return fallback
val r = reported.trim().trim('.', '`', '"')
@@ -103,8 +87,6 @@ object Languages {
return letters to cjk
}
- /// Whether text is in the target's script: Chinese, Japanese and Korean targets need some CJK,
- /// others must not be mostly CJK (TranslationService.cleanTranslation's check).
fun inScript(text: String, target: String): Boolean {
val (letters, cjk) = count(text)
if (letters == 0) return true
@@ -112,7 +94,6 @@ object Languages {
return if (wantsCjk) cjk > 0 else cjk * 2 <= letters
}
- /// Notes' check: CJK languages need a fair share (names and numbers stay Latin).
fun writtenIn(text: String, englishLanguage: String): Boolean {
val (letters, cjk) = count(text)
if (letters == 0) return true
@@ -125,7 +106,6 @@ object Languages {
return if (s >= 3600) "%d:%02d:%02d".format(s / 3600, s / 60 % 60, s % 60) else "%02d:%02d".format(s / 60, s % 60)
}
- /// The same language for speaking purposes: "zh" and "zh-CN" are, "zh-CN" and "zh-TW" aren't.
fun same(a: String, b: String): Boolean {
if (a.equals(b, ignoreCase = true)) return true
val (x, y) = a.substringBefore('-') to b.substringBefore('-')
diff --git a/android/core/src/main/kotlin/cicada/TranscriptSearch.kt b/android/core/src/main/kotlin/cicada/TranscriptSearch.kt
index 3e2376c..69333c4 100644
--- a/android/core/src/main/kotlin/cicada/TranscriptSearch.kt
+++ b/android/core/src/main/kotlin/cicada/TranscriptSearch.kt
@@ -1,9 +1,6 @@
package cicada
-/// Searching a meeting's lines (the Mac's TranscriptSearch), shared by 会议记录's list and the
-/// record it opens, so both find the same lines (misheard names included) and mark them the same.
object TranscriptSearch {
- /// The query, plus every way the notes say that name was heard (江充 also finds 江松).
fun terms(query: String, notes: List<NoteTerm>): List<String> {
val q = query.trim()
if (q.isEmpty()) return emptyList()
@@ -19,13 +16,9 @@ object TranscriptSearch {
fun matches(l: TranscriptLine, terms: List<String>): Boolean =
terms.any { l.shown.contains(it, ignoreCase = true) || (l.dst ?: "").contains(it, ignoreCase = true) }
- /// The ids of the lines a search finds, in order.
fun matches(lines: List<TranscriptLine>, terms: List<String>): List<String> =
if (terms.isEmpty()) emptyList() else lines.filter { matches(it, terms) }.map { it.id }
- /// Where every term is in `text` (start until end), in order and never overlapping, for marking
- /// in place. Compared char by char, so the ranges index the text itself (lowercasing can change
- /// a string's length).
fun ranges(text: String, terms: List<String>): List<IntRange> {
val found = mutableListOf<IntRange>()
for (term in terms) {
diff --git a/android/core/src/main/kotlin/cicada/Translator.kt b/android/core/src/main/kotlin/cicada/Translator.kt
index d46b685..d4122f7 100644
--- a/android/core/src/main/kotlin/cicada/Translator.kt
+++ b/android/core/src/main/kotlin/cicada/Translator.kt
@@ -2,19 +2,11 @@ package cicada
import java.net.URLEncoder
-/// What the hear model (Ming on Ling) heard in one stretch of audio.
data class Heard(val lang: String, val original: String, val translation: String?)
-/// Translation and recognition through the cloud (the Windows design): listening sends each
-/// stretch of audio to the AI service's hear model (Ming on Ling), which returns the language, the
-/// original and the translation in one call. Text translation is the AI service first, then
-/// Google. Calls block.
class Translator(private val ling: LingClient, private val transport: Transport = UrlTransport) {
@Volatile private var googleBackoffUntil = 0L
- /// 语音和文字只发给你的服务 (the Mac's googleOff; set by the app for the custom service only):
- /// Google is never asked, so the text stays with the user's service. Flipping it forgets a
- /// Google backoff and what the last sentence did.
@Volatile var googleOff = false
set(value) {
if (value == field) return
@@ -23,19 +15,12 @@ class Translator(private val ling: LingClient, private val transport: Transport
sentencesUntranslated = false
}
- /// The last finished sentence sent here came back untranslated (the Mac's
- /// TranslationHealth.sentencesUntranslated): with googleOff, the user's service can't be reached.
@Volatile var sentencesUntranslated = false
- /// Names and terms the notes have settled on, e.g. "江充 (…; misheard as 江松)".
@Volatile var glossary: () -> List<String> = { emptyList() }
// MARK: Hearing
- /// One stretch of speech (16 kHz mono, WAV or compressed) heard and interpreted. `hint` is the language the
- /// meeting has been in, which keeps Ming from flipping on a short or accented stretch. Null
- /// when there was no speech or the reply wasn't in the three-line form; never a guess.
- /// `seconds` is the clip's length (0: unknown): it caps the reply and catches a runaway one.
fun hear(clip: Clip, target: String, hint: String?, seconds: Double = 0.0): Heard? {
val reply = ling.chat(hearPrompt(target, hint, glossary()), hearInstruction(target), Priority.Translate,
maxTokens = hearTokens(seconds), timeout = hearTimeout(ling), model = ling.config().hearModel,
@@ -45,14 +30,10 @@ class Translator(private val ling: LingClient, private val transport: Transport
// MARK: Text
- /// Speak: my words for 我说 (the Mac's .speak), which don't count as the meeting's subtitles.
enum class Kind { Draft, Sentence, Speak }
@Volatile private var lastUnreachableTry = 0L
- /// A service that answers nothing costs a line its timeout before Google gets it (a hear model
- /// on its own server still hearing, 我说's fallback). While the check says unreachable, one line
- /// in 15 s still goes to it, so a service that is back is noticed without waiting for a check.
@Synchronized private fun lingWorthTrying(): Boolean {
if (ling.aiCheck.failure?.reason != AICheck.Reason.Unreachable) return true
val now = System.currentTimeMillis()
@@ -61,26 +42,17 @@ class Translator(private val ling: LingClient, private val transport: Transport
return true
}
- /// The AI service (finished sentences only) → Google (never with googleOff). Null when both fail.
fun translate(text: String, source: String, target: String, kind: Kind): String? {
if (source == target) return text
- // Partial text only ever goes to Google: left out, it shows the original until the sentence ends.
if (kind == Kind.Draft && googleOff) return null
val out = chain(text, source, target, kind)
if (kind == Kind.Sentence) sentencesUntranslated = out == null
return out
}
- /// What a finished sentence's request carries so the service can also point out misheard words
- /// (改正听错的词, LiveFixes.context). Null: fixing is off, and the request is the plain translation.
@Volatile var fixContext: ((text: String) -> LiveFixes.Context?)? = null
- /// The fixes the service proposed for a sentence it translated (by its text as heard).
@Volatile var onFixes: ((text: String, edits: List<Correction.Edit>) -> Unit)? = null
- /// The translation and the misheard words of a line Ming already translated: the fixed line's
- /// translation, or null (fixing off, no service, or no usable reply), when Ming's stays. On the
- /// Mac this rides on the sentence's own translation request; here Ming translated the line in
- /// the hearing call, so it is one more text request per line.
fun fixLine(text: String, source: String, target: String): String? {
if (source == target || !ling.usable || !lingWorthTrying()) return null
val ctx = fixContext?.invoke(text) ?: return null
@@ -88,11 +60,6 @@ class Translator(private val ling: LingClient, private val transport: Transport
return try { viaLingFixing(text, from, target, ctx) } catch (e: LingException) { Log.d("translate ling failed: ${e.message}"); null }
}
- /// The translation and the misheard words in one request (the Mac's viaLingFixing, its prompt
- /// word for word). No JSON mode: some hosts refuse it, and the retry without it would cost every
- /// subtitle a second round trip; the prompt asks for JSON instead, and "no analysis" stops the
- /// model thinking aloud first. Proposals only: Correction.decide picks which to take. A reply
- /// that isn't the JSON asked for is dropped like a failed one (null).
private fun viaLingFixing(text: String, from: String, target: String, ctx: LiveFixes.Context): String? {
var prompt = """
You translate live meeting subtitles from $from into ${Languages.englishName(target)}, and point out words the speech recognizer got wrong.
@@ -111,11 +78,9 @@ class Translator(private val ling: LingClient, private val transport: Transport
prompt += "\nSubtitle: $text"
val out = ling.chat(prompt, "JSON only.", Priority.Translate, maxTokens = 600, timeout = 6.0)
if (out.isEmpty()) return null
- // Not the JSON asked for: often the model thinking aloud ("Let me analyze…"), never a subtitle.
val (translation, edits) = Correction.parse(out, text) ?: run { Log.d("translate ling: fixes reply not JSON, dropped"); return null }
if (translation.isEmpty()) return null
val clean = cleanTranslation(translation, target) ?: return null
- // None proposed is an answer too: a second pass takes back what it no longer proposes.
onFixes?.invoke(text, edits)
return clean
}
@@ -124,7 +89,6 @@ class Translator(private val ling: LingClient, private val transport: Transport
if (kind != Kind.Draft && ling.usable && lingWorthTrying()) {
val from = if (source == "auto") "the spoken language" else Languages.englishName(source)
val ctx = if (kind == Kind.Sentence) fixContext?.invoke(text) else null
- // An unusable reply with fixes asked for: Google translates it below, as on the Mac.
if (ctx != null) try {
viaLingFixing(text, from, target, ctx)?.let { return it }
} catch (e: LingException) { Log.d("translate ling failed: ${e.message}") }
@@ -157,13 +121,8 @@ class Translator(private val ling: LingClient, private val transport: Transport
private fun enc(s: String) = URLEncoder.encode(s, "UTF-8")
companion object {
- /// Ming answers in ~2 s; the other services' hear models in 3–4 s, but now and then over
- /// 12 s (Qwen on ZenMux, 2026-11), and a stretch given up on is words lost.
fun hearTimeout(ling: LingClient) = if (ling.config().isLing) 12.0 else 20.0
- /// The notes' names for a request. Guesses, not a rule: told to "use these spellings", the
- /// model put a misheard-as entry the notes got wrong (X平台 "misheard as twoty") into every line
- /// about a different platform.
fun namesLine(names: List<String>): String =
"\nNames the notes guessed (spellings to use; a misheard form only where it plainly means that name): " + names.joinToString("; ")
@@ -175,17 +134,12 @@ class Translator(private val ling: LingClient, private val transport: Transport
return p
}
- /// Tested wording (Windows M0): adding "NONE if there is no speech" or "the same text if
- /// already in it" gets the gateway's canned "作为一个人工智能语言模型…" refusal instead.
fun hearInstruction(target: String) =
"Reply in exactly three lines:\n" +
"LANG: <BCP-47 code of the spoken language, e.g. en, zh-CN, ja>\n" +
"ORIGINAL: <exactly what was said, in the spoken language>\n" +
"TRANSLATION: <its translation into ${Languages.englishName(target)}>"
- /// `LANG: … / ORIGINAL: … / TRANSLATION: …`. Drops replies without an original, "NONE" (music,
- /// silence), and translations not in the target's script; a dropped translation leaves the
- /// original for the text translator to try.
fun parseHeard(reply: String, target: String, hint: String?, seconds: Double = 0.0): Heard? {
var lang: String? = null; var original: String? = null; var translation: String? = null
for (raw in reply.split('\n')) {
@@ -207,19 +161,11 @@ class Translator(private val ling: LingClient, private val transport: Transport
return Heard(code, o, t)
}
- /// Room for a reply to `seconds` of audio: a fast talker's original and translation fit; a
- /// reply that runs on repeating itself ("滴答" ×800 from typing) stops early. 0: unknown.
fun hearTokens(seconds: Double) = if (seconds <= 0) 800 else minOf(800, (60 + 40 * seconds).toInt())
- /// Ming writes something for every stretch it is sent, speech or not (it can't be asked for
- /// NONE, see hearInstruction): hold music, a ringback tone, a fan or typing came back as "嗯。",
- /// "嗯,嗯,嗯…" or "滴答" ×800. That is noise: fillers only, one short sound six or more times
- /// over, or more than anyone says in `seconds` (0: unknown). A short real answer ("对",
- /// "好的", "喂,能听到吗") stays. Same rules and lists as the Windows and Linux ports.
fun isNoise(original: String, seconds: Double = 0.0): Boolean {
val text = original.lowercase().replace(ANNOTATION, " ")
if (NO_SPEECH.any { text.contains(it) }) return true
- // A clock instead of words ("00:00"): what some of the other services' models write for a beep.
if (CLOCK.matches(text.trim())) return true
val words = mutableListOf<String>()
val word = StringBuilder()
@@ -229,15 +175,12 @@ class Translator(private val ling: LingClient, private val transport: Transport
if (word.isNotEmpty()) words.add(word.toString())
if (words.isEmpty()) return true
if (words.all(::isFillerWord)) return true
- // Each CJK character is a unit, as a word is elsewhere.
val units = words.flatMap { w -> if (w.any(::isCjk)) w.map { it.toString() } else listOf(w) }
val n = units.size
for (p in 1..4) if (n >= 6 * p && (p until n).all { units[it] == units[it - p] }) return true
return seconds > 0 && n > maxOf(12.0, 12 * seconds)
}
- /// Ming describing the audio instead of transcribing it: "(无语音内容)", "[Music]", "这段音频是一段
- /// 旋律,没有说话声。". A bracketed note beside real words ("(笑)好的") keeps the words.
private val CLOCK = Regex("^\\d{1,2}(:\\d{2}){1,2}[.。]?$")
private val ANNOTATION = Regex("[((\\[【][^))\\]】]*[))\\]】]|♪")
private val NO_SPEECH = listOf(
@@ -253,7 +196,6 @@ class Translator(private val ling: LingClient, private val transport: Transport
"음", "어", "아", "응", "흠", "으",
)
- /// Made of fillers only, a held sound shortened first: "嗯嗯嗯", "hmmmm", "えーと" is not.
private fun isFillerWord(raw: String): Boolean {
val w = StringBuilder()
for (c in raw) if (w.length < 2 || w[w.length - 1] != c || w[w.length - 2] != c) w.append(c)
@@ -268,15 +210,11 @@ class Translator(private val ling: LingClient, private val transport: Transport
private fun take(line: String, label: String) =
if (line.startsWith(label, ignoreCase = true)) line.substring(label.length).trim() else null
- /// "Translate." in each target language, letters only and lowercased. Port of instructionEchoes.
private val instructionEchoes = setOf(
"翻译", "翻譯", "translate", "翻訳", "翻訳して", "翻訳する", "翻訳してください", "번역", "번역해", "번역하세요", "번역해주세요",
"traducir", "traduce", "traduzca", "traduire", "traduisez", "traduis", "übersetzen", "übersetze", "traduzir", "traduza",
)
- /// Ling sometimes comments on a garbled subtitle instead of translating it ("The subtitle
- /// appears to be…"). Remark lines go, a "Translation:" label is stripped, and what is left must
- /// be in the target's script; null lets the next provider try. Port of cleanTranslation.
fun cleanTranslation(reply: String, target: String): String? {
val opener = listOf("here is", "here's", "the subtitle", "this subtitle", "the text", "this text", "the original",
"the user", "note", "(note", "i'm sorry", "i am sorry", "sorry", "it seems", "it appears", "this appears")
@@ -304,8 +242,6 @@ class Translator(private val ling: LingClient, private val transport: Transport
}
output = output.trim()
if (output.isEmpty()) return null
- // Ling translated the fixed "Translate." instruction instead of the subtitle ("翻译。" for an empty
- // subtitle, or for "Translate this into Chinese please."); the next provider translates it.
if (output.lowercase().filter { it.isLetter() } in instructionEchoes) return null
return if (Languages.inScript(output, target)) output else null
}
diff --git a/android/core/src/main/kotlin/cicada/Updates.kt b/android/core/src/main/kotlin/cicada/Updates.kt
index e213a99..5e0921d 100644
--- a/android/core/src/main/kotlin/cicada/Updates.kt
+++ b/android/core/src/main/kotlin/cicada/Updates.kt
@@ -3,27 +3,15 @@ package cicada
import java.io.File
import java.net.URI
-/// Checks GitHub Releases for an Android build newer than the running one, as the Windows
-/// UpdateChecker: the app checks at launch, when 首页 comes back once the answer is an hour old,
-/// and from a daily job. Failures (offline, rate-limited, 404) are silent. This only finds the
-/// update: the browser downloads the APK and the system installer replaces the app (it refuses
-/// one signed with another key), so no install permission is needed.
-/// `check` blocks: run it off the main thread.
class UpdateChecker(
- /// The running version, three parts ("1.4.0"), from VERSION via versionName.
val current: String,
- /// When the feed last answered (epoch ms), kept in settings across launches.
@Volatile var lastChecked: Long? = null,
private val transport: Transport = UrlTransport,
) {
class Update(val version: String, val page: String, val apk: String?, val size: Long)
- /// The list, not `releases/latest`: a release that ships only the Mac or Windows has no APK,
- /// so the newest Android release may be further down. The `updatefeed` debug command points
- /// it at another release JSON (a list or one release); a file path or file:// URL works too.
@Volatile var feed = FEED
- /// The newer release, or null (none, or not checked yet).
@Volatile var available: Update? = null; private set
private val listeners = mutableListOf<() -> Unit>()
@@ -31,8 +19,6 @@ class UpdateChecker(
fun checkIfDue(age: Long, now: Long = System.currentTimeMillis()): Boolean = if (due(lastChecked, now, age)) check() else true
- /// False when the feed couldn't be reached or answered with something unexpected. One at a
- /// time: a second caller (检查更新 during the launch check) waits, then asks for itself.
@Synchronized fun check(): Boolean {
try {
val releases = decode(read(feed)) ?: run { Log.d("update: feed unreadable"); return false }
@@ -51,7 +37,6 @@ class UpdateChecker(
private fun read(feed: String): String {
if (feed.startsWith("file:")) return File(URI(feed)).readText()
if (!feed.contains("://")) return File(feed).readText()
- // GitHub's API refuses requests without a User-Agent.
val r = transport.send(feed, "GET", null, mapOf("User-Agent" to "Cicada-Android", "Accept" to "application/vnd.github+json"), 20_000)
if (r.status !in 200..299) throw java.io.IOException("HTTP ${r.status}")
return r.body
@@ -59,14 +44,11 @@ class UpdateChecker(
companion object {
const val FEED = "https://api.github.com/repos/wquguru/cicada/releases?per_page=20"
- /// 首页 coming back checks once the last answer is this old; the daily job does the rest.
const val STALE = 3600_000L
fun due(last: Long?, now: Long, age: Long): Boolean =
- // A clock set back leaves `last` in the future: check rather than wait for it.
last == null || now - last >= age || last > now
- /// A list of releases, or one release (a feed pointed at `releases/latest`).
fun decode(text: String): List<Map<String, Any?>>? {
val v = try { Json.parse(text) } catch (_: Json.ParseException) { return null }
return when (v) {
@@ -76,7 +58,6 @@ class UpdateChecker(
}
}
- /// The newest published release with an Android APK; one without only carries other platforms.
fun newestAndroid(releases: List<Map<String, Any?>>): Update? {
var best: Update? = null
for (r in releases) {
@@ -92,7 +73,6 @@ class UpdateChecker(
return best
}
- /// Dotted numeric versions: "2.10.0" is newer than "2.9.1"; a suffix ("1.4.0-dev") is ignored.
fun isNewer(a: String, b: String): Boolean {
fun parts(v: String) = v.substringBefore('-').split('.').map { it.toIntOrNull() ?: 0 }
val x = parts(a); val y = parts(b)
diff --git a/android/core/src/main/kotlin/cicada/Vocabulary.kt b/android/core/src/main/kotlin/cicada/Vocabulary.kt
index 9a1eb6f..0f36258 100644
--- a/android/core/src/main/kotlin/cicada/Vocabulary.kt
+++ b/android/core/src/main/kotlin/cicada/Vocabulary.kt
@@ -4,16 +4,10 @@ import java.io.File
import java.text.Normalizer
import java.time.Instant
-/// 词表 (the Mac's Vocabulary.swift): the spellings the user stands behind, and how speech
-/// recognition has misheard each. Only these let a new name be fixed without asking: names the
-/// notes guess are often wrong, so they stay suggestions until the user confirms one. One JSON
-/// file beside the records (`file` null: in memory only). Thread-safe.
class Vocabulary(private val file: File? = Paths.vocabulary) {
data class Term(
val word: String,
- /// Wrong forms the recognizer produced, as confirmed or typed by the user.
val heard: List<String> = emptyList(),
- /// "user" (added or imported), "live" (confirmed during a meeting).
val source: String,
val fixes: Int = 0,
val used: Instant? = null,
@@ -26,7 +20,6 @@ class Vocabulary(private val file: File? = Paths.vocabulary) {
}
}
- /// What 粘贴导入 did, or would do: added, updated, and the line numbers skipped.
data class ImportResult(var added: Int = 0, var updated: Int = 0, val skipped: MutableList<Int> = mutableListOf())
private val gate = Any()
@@ -58,9 +51,6 @@ class Vocabulary(private val file: File? = Paths.vocabulary) {
return terms.any { key(it.word) == w && it.heard.any { x -> key(x) == h } }
}
- /// The user said yes to a fix (or added it): the word, and the form it was heard as. A pair
- /// that isn't a word for a word (`learnable`) adds nothing. A yes in a meeting never teaches a
- /// translation (平台 → platform): it would rewrite that word everywhere after.
fun confirm(heard: String, word: String, source: String = "live") {
if (heard.isEmpty()) return add("", word, source)
val l = learnable(heard, word) ?: return
@@ -75,35 +65,29 @@ class Vocabulary(private val file: File? = Paths.vocabulary) {
} else t.add(Term(word, if (heard.isEmpty()) emptyList() else listOf(heard), source))
}
- /// A heard form the user turned down twice stops being one.
fun forget(heard: String, word: String) = change { t ->
val i = t.indexOfFirst { key(it.word) == key(word) }
if (i >= 0) t[i] = t[i].copy(heard = t[i].heard.filter { key(it) != key(heard) })
}
- /// 词表 › tap a word: its spelling changes; what it was heard as stays with it.
fun rename(word: String, new: String) = change { t ->
val n = new.trim()
val i = t.indexOfFirst { key(it.word) == key(word) }
if (n.isEmpty() || n.length > 40 || i < 0) return@change
val j = t.indexOfFirst { key(it.word) == key(n) }
if (j >= 0 && j != i) {
- // Renamed onto a word already there: the two become one.
t[j] = t[j].copy(heard = t[j].heard + t[i].heard.filter { h -> t[j].heard.none { key(it) == key(h) } })
t.removeAt(i)
} else t[i] = t[i].copy(word = n)
}
- /// The other words a heard form already belongs to ("莫拉" is Morpho's).
fun owners(heard: String, except: String? = null): List<String> =
terms.filter { t -> t.heard.any { key(it) == key(heard) } && key(t.word) != key(except ?: "") }.map { it.word }
- /// Back where it was, after 撤销 on a delete.
fun insert(term: Term, at: Int) = change { t ->
if (t.none { key(it.word) == key(term.word) }) t.add(minOf(at, t.size), term)
}
- /// 撤销: the list as it was.
fun restore(saved: List<Term>) = change { t -> t.clear(); t.addAll(saved) }
fun remove(word: String) = change { t -> t.removeAll { key(it.word) == key(word) } }
@@ -113,13 +97,11 @@ class Vocabulary(private val file: File? = Paths.vocabulary) {
if (i >= 0) t[i] = t[i].copy(fixes = t[i].fixes + 1, used = at)
}
- /// For the request: the most recently useful first, "Morpho (heard as 莫拉, 莫法)".
fun promptLines(): List<String> =
terms.sortedByDescending { it.used ?: Instant.EPOCH }.take(LIMIT).map {
if (it.heard.isEmpty()) it.word else "${it.word} (heard as ${it.heard.joinToString(", ")})"
}
- /// What 粘贴导入 would do, before it does it (the dialog's counts and its button).
fun preview(text: String): ImportResult {
val r = ImportResult()
val seen = HashSet<String>()
@@ -164,12 +146,8 @@ class Vocabulary(private val file: File? = Paths.vocabulary) {
class Entry(val line: Int, val word: String, val heard: List<String>)
companion object {
- /// More would make every sentence's request long, and more terms means more wrong swaps.
const val LIMIT = 300
- /// What a fix can teach the list, or null: both sides trimmed of spaces and punctuation, no
- /// punctuation inside, short, and a real swap. An edit that only adds or drops words around
- /// the heard ones ("我来" → "OK我来") or ends on a full stop ("持。" → "讲。") teaches nothing.
fun learnable(heard: String, word: String): Pair<String, String>? {
val h = trimEdges(heard); val w = trimEdges(word)
if (h.isEmpty() || w.isEmpty() || h.codePointCount(0, h.length) > 20 || w.codePointCount(0, w.length) > 40 || key(h) == key(w)) return null
@@ -185,7 +163,6 @@ class Vocabulary(private val file: File? = Paths.vocabulary) {
else -> false
}
- /// Spaces, punctuation and symbols: what a learned pair is trimmed of at both ends.
private fun edge(c: Int): Boolean = Character.isWhitespace(c) || Character.isSpaceChar(c) || punctuation(c) ||
when (Character.getType(c).toByte()) {
Character.MATH_SYMBOL, Character.CURRENCY_SYMBOL, Character.MODIFIER_SYMBOL, Character.OTHER_SYMBOL -> true
@@ -199,11 +176,8 @@ class Vocabulary(private val file: File? = Paths.vocabulary) {
return s.substring(a, b)
}
- /// Same word whatever its width, case or spacing ("AAVE" is "aave").
fun key(s: String): String = Normalizer.normalize(s, Normalizer.Form.NFKC).lowercase().split(Regex("\\s+")).filter { it.isNotEmpty() }.joinToString(" ")
- /// 粘贴导入: one per line, heard forms after "=" ("Morpho = 莫拉、莫法"). A line too long (or
- /// with control characters) comes back with an empty word, reported by its number.
fun parse(text: String): List<Entry> = text.split(Regex("\r\n|\r|\n")).mapIndexedNotNull { i, raw ->
val line = raw.trim()
if (line.isEmpty()) return@mapIndexedNotNull null
diff --git a/android/core/src/main/kotlin/cicada/VoiceReference.kt b/android/core/src/main/kotlin/cicada/VoiceReference.kt
index c23bf63..1464257 100644
--- a/android/core/src/main/kotlin/cicada/VoiceReference.kt
+++ b/android/core/src/main/kotlin/cicada/VoiceReference.kt
@@ -4,13 +4,7 @@ import java.io.File
import java.util.Base64
import kotlin.math.sqrt
-/// The recording Ming clones the user's voice from (VoiceReference in Voices.swift): `voice/reference.wav`
-/// (16 kHz mono) and `voice/reference.txt` (what it says, as Ming heard it) in the app's private
-/// folder, kept out of backups and device transfer. Never leaves the phone except inside a speech
-/// request to Ling; never in records, exports or the log.
object VoiceReference {
- /// The phones' limits (#32): every sentence sends the clip again, so a long one makes the voice
- /// late. The Mac allows 8–30 s.
const val MIN_SECONDS = 10.0
const val MAX_SECONDS = 15.0
@@ -23,7 +17,6 @@ object VoiceReference {
val duration: Double get() = try { (audio.length() - 44).coerceAtLeast(0) / 2.0 / Segmenter.RATE } catch (_: Exception) { 0.0 }
- /// What Ming needs: the clip as a data URI and its transcript.
fun reference(): Pair<String, String>? {
val t = text ?: return null
val bytes = try { audio.readBytes() } catch (_: Exception) { return null }
@@ -46,13 +39,9 @@ object VoiceReference {
// MARK: Pace (the Mac's)
- /// Ming copies the recording's pace into every sentence. Below these (characters for Chinese,
- /// Japanese and Korean, words otherwise, per second of speech) the clone is too slow for a
- /// meeting; reading the passage at an ordinary pace gives 3.5–5 and 2.3–3.
const val SLOW_CHARACTERS = 2.5
const val SLOW_WORDS = 1.6
- /// SpeakScore.tokens: each CJK character, and each run of letters, digits and apostrophes.
fun tokens(text: String): List<String> {
val out = mutableListOf<String>()
val word = StringBuilder()
@@ -73,26 +62,19 @@ object VoiceReference {
fun isCJK(cp: Int) = cp in 0x3040..0x30FF || cp in 0x3400..0x4DBF || cp in 0x4E00..0x9FFF || cp in 0xAC00..0xD7AF || cp in 0xF900..0xFAFF
- /// Seconds from the first to the last 20 ms window within 35 dB of the loudest one.
fun speechSpan(samples: ShortArray, rate: Int = Segmenter.RATE): Double? {
val (first, last, size) = speechWindows(samples, rate) ?: return null
return (last - first + 1) * size.toDouble() / rate
}
- /// Quiet kept before and after the reading by `trim`.
const val TRIM_PAD = 0.2
- /// The recording without the quiet before and after the reading, 0.2 s kept each side (the
- /// Linux port's trim). Ming copies the clip's ending: a second of silence after the last word
- /// (the pause before 读完了) cut every cloned sentence short (measured 2026-11 against Ling:
- /// 1.9 s of speech instead of 3.6 s for the same line).
fun trim(samples: ShortArray, rate: Int = Segmenter.RATE): ShortArray {
val (first, last, size) = speechWindows(samples, rate) ?: return samples
val pad = (TRIM_PAD * rate).toInt()
return samples.copyOfRange(maxOf(0, first * size - pad), minOf(samples.size, (last + 1) * size + pad))
}
- /// The first and last 20 ms window within 35 dB of the loudest one, and the window's length.
private fun speechWindows(samples: ShortArray, rate: Int): Triple<Int, Int, Int>? {
val size = maxOf(1, (rate * 0.02).toInt())
val levels = ArrayList<Double>()
@@ -113,7 +95,6 @@ object VoiceReference {
return Triple(first, last, size)
}
- /// Characters or words a second, silence at both ends left out; null when there is no speech.
fun pace(text: String, samples: ShortArray, rate: Int = Segmenter.RATE): Double? {
val units = tokens(text).size
val span = speechSpan(samples, rate) ?: return null
@@ -129,7 +110,6 @@ object VoiceReference {
@Volatile private var cachedSlow: Pair<Long, Boolean>? = null
- /// The saved recording is read too slowly (worked out once per recording).
val savedIsSlow: Boolean get() {
val t = text ?: return false
val stamp = audio.lastModified()
@@ -139,17 +119,12 @@ object VoiceReference {
return slow
}
- /// The passage to read, in the user's own language.
fun passage(language: String): String = when (VoiceCatalog.key(language)) {
"zh" -> "大家好,我是这次会议的主持人。今天我们主要讨论新产品的上线计划,包括时间安排、测试范围和市场推广。请大家先看一下屏幕上的议程。"
"ja" -> "皆さん、こんにちは。今日の会議では、新製品の発売計画について話し合います。スケジュール、テストの範囲、そしてマーケティングについて順番に確認しましょう。"
else -> "Hello everyone, thanks for joining. Today we'll walk through the launch plan for the new product: the schedule, what we still need to test, and how we'll tell people about it. Let's start with the agenda on the screen."
}
- /// What the recording says, as the service hears it (the Mac transcribes on the device; the
- /// phone has Ming), then checked as the Mac checks it. Returns the text and the trimmed clip
- /// to keep, or the reason to record again (a Chinese UI key). The 10 s are the reading's,
- /// silence at the ends left out.
sealed class Check {
class Ok(val text: String, val pcm: ShortArray) : Check() {
override fun equals(other: Any?) = other is Ok && other.text == text && other.pcm.contentEquals(pcm)
diff --git a/android/core/src/main/kotlin/cicada/Voices.kt b/android/core/src/main/kotlin/cicada/Voices.kt
index 26b916a..7dff2de 100644
--- a/android/core/src/main/kotlin/cicada/Voices.kt
+++ b/android/core/src/main/kotlin/cicada/Voices.kt
@@ -1,21 +1,13 @@
package cicada
-/// A voice 我说 can read with (Voices.swift's VoiceOption): one of Ming's (through the Ling key), one
-/// of another service's speech model, the phone's text-to-speech, or the user's own voice cloned
-/// from a recording (VoiceReference). `id` is what settings keep: "ming:US_Emma", "cloud:Kore",
-/// "phone", "clone".
-data class VoiceOption(val id: String, val name: String, /** Chinese UI keys, localized where shown. */ val tags: List<String>)
+data class VoiceOption(val id: String, val name: String, val tags: List<String>)
-/// Which voices to offer for each language the other side may hear (VoiceCatalog in Voices.swift).
-/// Ming's are hand-picked natural ones; for languages it has no native voice for, Emma and George
-/// speak it with `language_id`. The phone's own voice follows, so there is always one without a key.
object VoiceCatalog {
const val PHONE = "phone"
const val CLONE = "clone"
const val MING = "ming:"
const val CLOUD = "cloud:"
- /// The picker's languages (key, title), as on the Mac. The key is the code without region.
val languages = listOf("en" to "English", "zh" to "中文", "ja" to "日本語", "ko" to "한국어",
"es" to "Español", "fr" to "Français", "de" to "Deutsch", "pt" to "Português")
@@ -23,7 +15,6 @@ object VoiceCatalog {
fun title(code: String): String = languages.firstOrNull { it.first == key(code) }?.second ?: code
- /// Ming's `language_id` for languages that need it (zh and en work without).
fun mingLanguage(code: String): String? = key(code).takeIf { it in listOf("ja", "ko", "de", "fr", "es") }
fun ming(language: String): List<VoiceOption> {
@@ -38,8 +29,6 @@ object VoiceCatalog {
}
}
- /// The service's own voices for a language: Ming's on Ling, a speech model's (the same in every
- /// language) elsewhere, none when it has no speech model.
fun remote(language: String, config: AIConfig): List<VoiceOption> = when {
!config.hasVoices -> emptyList()
config.isLing -> ming(language)
@@ -51,15 +40,9 @@ object VoiceCatalog {
fun options(language: String, config: AIConfig): List<VoiceOption> = remote(language, config) + phone
- /// What a language uses until the user picks: the service's first voice once it can speak,
- /// else the phone's (the Mac's defaultID).
fun defaultId(language: String, config: AIConfig, speaks: Boolean): String =
(if (speaks) remote(language, config).firstOrNull()?.id else null) ?: PHONE
- /// The chosen voice for a language, or its default (AppModel.voiceID): a choice the service in
- /// use can't speak (Ming after switching to OpenRouter, any after the key is gone, the user's
- /// own voice without Ling or without a recording: `canClone`) falls back to the default, and
- /// comes back with that service.
fun chosen(voices: Map<String, String>, language: String, config: AIConfig, speaks: Boolean, canClone: Boolean = false): String {
val fallback = defaultId(language, config, speaks)
val id = voices[key(language)] ?: return fallback
@@ -74,7 +57,6 @@ object VoiceCatalog {
fun option(id: String, language: String, config: AIConfig): VoiceOption? =
if (id == CLONE) clone else options(language, config).firstOrNull { it.id == id }
- /// A short line to try a voice with, in the language it will speak.
fun sample(language: String): String = when (key(language)) {
"zh" -> "谢谢大家。我们来看一下上线时间表,并确定谁负责麦克风测试。"
"ja" -> "皆さん、ありがとうございます。発売スケジュールを確認しましょう。"
diff --git a/android/scripts/build.sh b/android/scripts/build.sh
index 6306080..33736cf 100755
--- a/android/scripts/build.sh
+++ b/android/scripts/build.sh
@@ -1,12 +1,7 @@
#!/bin/bash
-# Builds the Android app on the Mac: build/Cicada-dev.apk (com.wquguru.cicada.dev, with the debug
-# receiver), or with RELEASE=1 build/Cicada-<version>-Android.apk signed with the release key
-# (scripts/keystore.sh; build/Cicada-unsigned.apk when there is none). Also regenerates the
-# onboarding sample from the Mac app's. The launcher icon is vector (res/drawable/ic_launcher_*.xml).
set -euo pipefail
cd "$(dirname "$0")/.."
root=..
-# The sample meeting as 16 kHz WAV: the file source and MediaPlayer both read it.
afconvert -f WAVE -d LEI16@16000 -c 1 "$root/Resources/sample/sample.m4a" app/src/main/assets/sample.wav
mkdir -p build
if [ "${RELEASE:-}" = 1 ]; then
diff --git a/android/scripts/check-release.sh b/android/scripts/check-release.sh
index 6a8ca45..aed4a2c 100755
--- a/android/scripts/check-release.sh
+++ b/android/scripts/check-release.sh
@@ -1,10 +1,7 @@
#!/bin/bash
-# Checks a release APK before it ships: it verifies, and it is not signed with a debug key.
-# scripts/check-release.sh build/Cicada-1.1.0-Android.apk
set -euo pipefail
apk=${1:?usage: scripts/check-release.sh <apk>}
sdk="${ANDROID_HOME:-$HOME/.cicada-android/sdk}"
-# apksigner is Java: the toolchain from install-sdk.sh on the Mac, setup-java in CI.
[ -n "${JAVA_HOME:-}" ] || export JAVA_HOME="$HOME/.cicada-android/jdk/Contents/Home"
apksigner=$(ls "$sdk"/build-tools/*/apksigner | tail -1)
certs=$("$apksigner" verify --print-certs "$apk")
diff --git a/android/scripts/cicadactl.sh b/android/scripts/cicadactl.sh
index 1461451..5e3ae99 100755
--- a/android/scripts/cicadactl.sh
+++ b/android/scripts/cicadactl.sh
@@ -1,9 +1,4 @@
#!/bin/bash
-# Drives the dev build in the emulator or a phone (adb): scripts/cicadactl.sh state | start mic |
-# feed en.wav | sample | view subtitles | capture on | stop | … (see DebugReceiver.kt). Prints the
-# app's one-line JSON reply. `push <file>` copies a file into the app's files/ for feed and import;
-# `key` copies the Mac app's Ling key in (never printed), `aikey <file>` another service's; `log`
-# prints the debug log.
set -euo pipefail
adb="$HOME/.cicada-android/sdk/platform-tools/adb"
pkg=com.wquguru.cicada.dev
@@ -18,8 +13,6 @@ case "${1:-state}" in
"$adb" shell "run-as $pkg sh -c 'mkdir -p files && cat > files/ling-api-key && chmod 600 files/ling-api-key'" < "$f"
set -- key reload ;;
aikey)
- # Another service's key from the Mac app (`aikey ai-key-zenmux`, after `provider zenmux`): the
- # app seals it as the current service's key and deletes the plain copy. Never printed.
f="${CICADA_KEY_FILE:-$HOME/Library/Application Support/LiveSubs Dev/$2}"
"$adb" shell "run-as $pkg sh -c 'cat > files/key-import'" < "$f"
set -- key import key-import ;;
diff --git a/android/scripts/cli.sh b/android/scripts/cli.sh
index dd81bf9..5a444ac 100755
--- a/android/scripts/cli.sh
+++ b/android/scripts/cli.sh
@@ -1,6 +1,4 @@
#!/bin/bash
-# Runs cicada-cli (the engines on the Mac): scripts/cli.sh test | listen <wav> | hear | segments | roundtrip.
-# Builds it first; a proxy in the environment is passed to Java, which ignores http(s)_proxy.
set -euo pipefail
cd "$(dirname "$0")/.."
scripts/gradle.sh :cli:installDist >/dev/null
diff --git a/android/scripts/consent.sh b/android/scripts/consent.sh
index 8956c72..50693d7 100755
--- a/android/scripts/consent.sh
+++ b/android/scripts/consent.sh
@@ -1,10 +1,7 @@
#!/bin/bash
-# Taps through Android's screen-capture consent dialog, as a person does once per listening
-# session in 手机里的声音 mode ("Next" first where Android asks one app or the whole screen).
set -euo pipefail
cd "$(dirname "$0")"
TAP_EXACT=1 ./tap.sh "Start now" "Share screen" "Start" "立即开始" "共享屏幕" "开始" "Next" "下一步"
sleep 1
-# A second step on some versions.
TAP_EXACT=1 ./tap.sh "Start now" "Share screen" "立即开始" "共享屏幕" 2>/dev/null || true
echo consented
diff --git a/android/scripts/emulator.sh b/android/scripts/emulator.sh
index 435ef7e..3779d24 100755
--- a/android/scripts/emulator.sh
+++ b/android/scripts/emulator.sh
@@ -1,6 +1,4 @@
#!/bin/bash
-# Boots the `cicada` emulator (AVD=cicada29 for Android 10; made by install-sdk.sh) and waits until Android is up. Network goes
-# through the Mac's proxy when one is set, so Google translation works too. --wipe starts clean.
set -euo pipefail
D="$HOME/.cicada-android"; S="$D/sdk"; adb="$S/platform-tools/adb"
AVD="${AVD:-cicada}"
diff --git a/android/scripts/gradle.sh b/android/scripts/gradle.sh
index b3c6247..5edadf1 100755
--- a/android/scripts/gradle.sh
+++ b/android/scripts/gradle.sh
@@ -1,6 +1,4 @@
#!/bin/bash
-# Gradle with the toolchain from install-sdk.sh (~/.cicada-android), run from android/. Java ignores
-# http(s)_proxy, so a proxy in the environment is handed to Gradle as system properties.
set -euo pipefail
D="$HOME/.cicada-android"
export JAVA_HOME="$D/jdk/Contents/Home" ANDROID_HOME="$D/sdk"
diff --git a/android/scripts/install-sdk.sh b/android/scripts/install-sdk.sh
index 1b47809..23169ad 100755
--- a/android/scripts/install-sdk.sh
+++ b/android/scripts/install-sdk.sh
@@ -1,9 +1,4 @@
#!/bin/bash
-# One-time toolchain for the Android app, all under ~/.cicada-android (no sudo, nothing system-wide):
-# a JDK 21, Gradle, the Android SDK (platform, build tools, the NDK for the voiceprint library,
-# emulator) and an arm64 system image for the test emulator. Versions are pinned and every download
-# is checked against its published checksum before it is unpacked. Re-running skips what is already
-# there. --old also makes `cicada29`, an Android 10 emulator (the oldest Android the app supports).
set -euo pipefail
D="$HOME/.cicada-android"; mkdir -p "$D"; cd "$D"
JDK=21.0.13_9; JDK_TAG="jdk-21.0.13%2B9"
@@ -12,10 +7,8 @@ JDK_SHA_X64=9aa1d1c17ae5467a022679e7e0af5c00797d94ac462ed1a46f4db07a8a34a6dd
GRADLE=9.8.2; GRADLE_SHA=21bd5da2de49b642904077f38c0efdc7778e92b3ed0889392dca61b97e389607
CLT=15641748; CLT_SHA1=b62a5d8cf63ded173b47be867be4ee058ceda6df
API=36; BUILD_TOOLS=36.0.0
-# The NDK builds 说话人识别's voiceprint library (linux/native/voiceprint.c); app/build.gradle.kts pins the same.
NDK=29.0.14206865
-# fetch <url> <file> <sha256|sha1:…>: download, then refuse anything that doesn't match.
fetch() {
curl -fsSL "$1" -o "$2.part"
local want="$3" got
@@ -40,7 +33,6 @@ if [ ! -x sdk/cmdline-tools/latest/bin/sdkmanager ]; then
fetch "https://dl.google.com/android/repository/commandlinetools-mac-${CLT}_latest.zip" clt.zip "sha1:$CLT_SHA1"
mkdir -p sdk/cmdline-tools && unzip -q clt.zip -d sdk/cmdline-tools && mv sdk/cmdline-tools/cmdline-tools sdk/cmdline-tools/latest && rm clt.zip
fi
-# sdkmanager checks its own packages' checksums.
sm=sdk/cmdline-tools/latest/bin/sdkmanager; avd=sdk/cmdline-tools/latest/bin/avdmanager
yes | "$sm" --licenses >/dev/null || true
images=("system-images;android-$API;google_apis;arm64-v8a")
diff --git a/android/scripts/install.sh b/android/scripts/install.sh
index 9996df0..b81fc0a 100755
--- a/android/scripts/install.sh
+++ b/android/scripts/install.sh
@@ -1,12 +1,9 @@
#!/bin/bash
-# Installs build/Cicada-dev.apk on the running emulator or phone, grants what a person would
-# (microphone, notifications, 显示在其他应用上层) and opens it.
set -euo pipefail
cd "$(dirname "$0")/.."
adb="$HOME/.cicada-android/sdk/platform-tools/adb"; pkg=com.wquguru.cicada.dev
"$adb" install -r build/Cicada-dev.apk >/dev/null
"$adb" shell pm grant $pkg android.permission.RECORD_AUDIO
-# Android 13+ only; older systems show notifications without asking.
[ "$("$adb" shell getprop ro.build.version.sdk | tr -d "\r")" -ge 33 ] && "$adb" shell pm grant $pkg android.permission.POST_NOTIFICATIONS
"$adb" shell appops set $pkg SYSTEM_ALERT_WINDOW allow
"$adb" shell am start -n $pkg/com.wquguru.cicada.MainActivity >/dev/null
diff --git a/android/scripts/keystore.sh b/android/scripts/keystore.sh
index 1b3ceda..220bbbd 100755
--- a/android/scripts/keystore.sh
+++ b/android/scripts/keystore.sh
@@ -1,8 +1,4 @@
#!/bin/bash
-# Makes the release signing key, once ever: ~/.cicada-android/release.jks (PKCS12, RSA 4096, 30
-# years), its random password in the login Keychain (cicada-android-release). Every release must be
-# signed with this same key, or phones can't update to it: back up the file and the password.
-# --github also puts both in the repo's Actions secrets, for the release workflow.
set -euo pipefail
ks="${CICADA_KEYSTORE:-$HOME/.cicada-android/release.jks}"
keytool="$HOME/.cicada-android/jdk/Contents/Home/bin/keytool"
diff --git a/android/scripts/shot.sh b/android/scripts/shot.sh
index 514298c..7790013 100755
--- a/android/scripts/shot.sh
+++ b/android/scripts/shot.sh
@@ -1,5 +1,4 @@
#!/bin/bash
-# Screenshot of the emulator or phone to $1 (default build/shot.png), scaled to SHOT_SIZE (900) px high.
set -euo pipefail
out="${1:-$(dirname "$0")/../build/shot.png}"
"$HOME/.cicada-android/sdk/platform-tools/adb" exec-out screencap -p > "$out"
diff --git a/android/scripts/strings.py b/android/scripts/strings.py
index 4cb146a..4770dcb 100755
--- a/android/scripts/strings.py
+++ b/android/scripts/strings.py
@@ -1,10 +1,5 @@
#!/usr/bin/env python3
-"""Lists Android UI text with no translation: every L("…") / LF("…") key in android/app and
-android/core that is in neither the Mac's Resources/<lang>.lproj/Localizable.strings nor
-android/app/src/main/strings/<lang>.lproj/Android.strings. --write appends the missing keys to
-Android.strings as TODO lines (value = the Chinese)."""
import re, sys, pathlib
-# The Windows console is cp1252: Chinese keys would crash the report itself.
sys.stdout.reconfigure(encoding="utf-8")
here = pathlib.Path(__file__).resolve().parent.parent
root = here.parent
diff --git a/android/scripts/tap.sh b/android/scripts/tap.sh
index dc4eec0..c125908 100755
--- a/android/scripts/tap.sh
+++ b/android/scripts/tap.sh
@@ -1,7 +1,4 @@
#!/bin/bash
-# Taps the first on-screen element whose text (or description) is one of the given labels,
-# waiting up to 10 s for it: scripts/tap.sh "开始听" "Start listening". For driving the real UI in
-# tests (system dialogs too). Exits 1 if none shows up. TAP_EXACT=0 matches substrings.
set -euo pipefail
adb="$HOME/.cicada-android/sdk/platform-tools/adb"
xml=$(mktemp); trap 'rm -f "$xml"' EXIT
diff --git a/android/scripts/test.sh b/android/scripts/test.sh
index 6829327..90cc4d1 100755
--- a/android/scripts/test.sh
+++ b/android/scripts/test.sh
@@ -1,4 +1,3 @@
#!/bin/bash
-# Unit tests for the Android engines; runs on the Mac (no network, no emulator).
set -euo pipefail
exec "$(dirname "$0")/cli.sh" test
diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts
index fe03caa..9cf9983 100644
--- a/android/settings.gradle.kts
+++ b/android/settings.gradle.kts
@@ -1,4 +1,3 @@
-// Cicada for Android: core (pure-JVM engines), cli (tests + real runs on the Mac), app (the APK).
pluginManagement {
repositories { google(); mavenCentral(); gradlePluginPortal() }
}
diff --git a/android/tools/player/build.gradle.kts b/android/tools/player/build.gradle.kts
index 46a939a..3b4dc61 100644
--- a/android/tools/player/build.gradle.kts
+++ b/android/tools/player/build.gradle.kts
@@ -1,5 +1,3 @@
-// A test helper, not shipped: plays a WAV as another app would (USAGE_MEDIA), so the emulator has
-// something Cicada can capture. `adb shell am start -n com.wquguru.cicada.player/.Play -d file:///sdcard/Music/en.wav`
plugins { id("com.android.application") }
android {
namespace = "com.wquguru.cicada.player"
diff --git a/android/tools/player/src/main/kotlin/Play.kt b/android/tools/player/src/main/kotlin/Play.kt
index 43d1c54..f0dc0ea 100644
--- a/android/tools/player/src/main/kotlin/Play.kt
+++ b/android/tools/player/src/main/kotlin/Play.kt
@@ -6,7 +6,6 @@ import android.media.MediaPlayer
import android.os.Bundle
import android.widget.TextView
-/// Plays the intent's file or URL once as media, the way a video or podcast app does.
class Play : Activity() {
private var player: MediaPlayer? = null