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.

feat(android): redesign the app on the iPhone design, with saved meeting audio, export, import, speaker names and a full-screen face-to-face view

wqugurub556497e57d3
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index ac5d23c..7a48716 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -6,6 +6,8 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
+ <!-- 导入录音或视频: transcribing a file goes on with another app in front. -->
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- The floating notes window / subtitle bar. -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
@@ -31,6 +33,18 @@
<activity android:name=".RecordActivity" android:exported="false" android:parentActivityName=".MainActivity" />
<activity android:name=".SettingsActivity" android:exported="false" android:parentActivityName=".MainActivity" />
<activity android:name=".OnboardingActivity" android:exported="false" />
+ <!-- 导入录音或视频: from 首页, or another app's share sheet (分享到知了). -->
+ <activity android:name=".ImportActivity" android:exported="true" android:parentActivityName=".MainActivity"
+ android:label="@string/app_name">
+ <intent-filter>
+ <action android:name="android.intent.action.SEND" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <data android:mimeType="audio/*" />
+ <data android:mimeType="video/*" />
+ </intent-filter>
+ </activity>
+ <!-- 面对面: the phone between two people, half of it turned to the other side. -->
+ <activity android:name=".FaceActivity" android:exported="false" android:parentActivityName=".ListeningActivity" />
<activity android:name=".OverlayGuideActivity" android:exported="false" />
<activity android:name=".ProjectionActivity" android:exported="false"
android:theme="@style/Cicada.Translucent" android:excludeFromRecents="true" />
@@ -40,6 +54,6 @@
<meta-data android:name="android.service.quicksettings.TOGGLEABLE_TILE" android:value="true" />
</service>
<service android:name=".ListenService" android:exported="false"
- android:foregroundServiceType="mediaProjection|microphone" />
+ android:foregroundServiceType="mediaProjection|microphone|dataSync" />
</application>
</manifest>
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 70b0b33..f92e4b6 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
@@ -14,10 +14,12 @@ import cicada.AudioSource
import cicada.LingClient
import cicada.ListenEngine
import cicada.Log
+import cicada.MeetingEndWatch
import cicada.NotesEngine
import cicada.Paths
import cicada.PcmAudioSource
import cicada.SessionStore
+import cicada.SpeakerLabels
import cicada.Strings
import cicada.Translator
import cicada.Wav
@@ -54,6 +56,10 @@ class CicadaApp : Application() {
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() {
super.onCreate()
@@ -62,6 +68,13 @@ class CicadaApp : Application() {
Paths.log = File(cacheDir, if (BuildConfig.DEBUG) "cicada-dev-debug.log" else "cicada-debug.log")
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()
key = AIKey(KeystoreProtector)
ling = LingClient(key).apply { model = settings.model }
@@ -77,6 +90,7 @@ class CicadaApp : Application() {
overlay = Overlay(this)
voice = Voice(this)
listen.onSaid = ::speakAloud
+ listen.onWords = { main.post { endWatch?.heard(now()); setEnding(endWatch?.pending) } }
listen.onChange(::changed)
notes.onChange(::changed)
store.onChange { changed() }
@@ -167,6 +181,8 @@ class CicadaApp : Application() {
overlayThisMeeting = false
overlay.collapsed = false
listen.start(source, kind)
+ startRecording()
+ watchEnd()
if (kind == "mic") background.execute { voice.warm() }
openLive()
}
@@ -197,15 +213,103 @@ 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
+
+ private val endConfig: MeetingEndWatch.Config get() = MeetingEndWatch.Config(
+ followApps = false,
+ silence = MeetingEndWatch.Silence.of(settings.silenceEnd),
+ silenceAfter = endTimesOverride?.first ?: (settings.silenceMinutes * 60),
+ countdown = endTimesOverride?.second ?: 60.0,
+ )
+
+ private val endTick = object : Runnable {
+ override fun run() {
+ val w = endWatch ?: return
+ if (!listen.listening) return
+ w.config = endConfig
+ val said = listen.sessionId?.let { store.lines(it).isNotEmpty() } ?: false
+ 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)
+ }
+ }
+
+ private fun watchEnd() {
+ autoEnded = false
+ endWatch = MeetingEndWatch(endConfig, now())
+ main.removeCallbacks(endTick)
+ main.postDelayed(endTick, 2000)
+ }
+
+ private fun setEnding(p: MeetingEndWatch.Pending?) {
+ if (p == ending) { if (p != null) changed(); return }
+ if (p != null) Log.d("meeting end: pending ${p.reason}, ends in ${(p.deadline - now()).toInt()} s")
+ else if (ending != null) Log.d("meeting end: pending cleared")
+ ending = p
+ changed()
+ }
+
+ fun endingTitle(p: MeetingEndWatch.Pending): String = when (val r = p.reason) {
+ is MeetingEndWatch.Reason.AppLeft -> Strings.LF("%@ 已挂断", r.name)
+ else -> Strings.LF("已经 %lld 分钟没人说话", maxOf(1, Math.round(endConfig.silenceAfter / 60).toInt()))
+ }
+
+ fun endingLeft(p: MeetingEndWatch.Pending) = maxOf(0, Math.round(p.deadline - now()).toInt())
+
+ 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
+ }
+ val at = java.time.Instant.ofEpochMilli(((w.lastSpeech + 5) * 1000).toLong())
+ Log.d("meeting end: ended by itself ($reason), end time ${(now() - w.lastSpeech - 5).toInt()} s ago")
+ 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))
}
- fun stopListening(then: (() -> Unit)? = null) {
+ fun stopListening(endedAt: java.time.Instant? = null, then: (() -> Unit)? = null) {
voice.stop()
+ autoEnded = false
+ endWatch = null
+ setEnding(null)
+ val rec = recorder; recorder = null; listen.tap = null
+ val recId = listen.sessionId
+ val imported = importing; importing = null
background.execute {
- listen.stop()
+ listen.stop(endedAt)
+ if (imported != null && recId != null) store.update(recId) { it.importing = null }
+ rec?.finish { ok -> if (ok && recId != null && store.get(recId) != null) store.update(recId) { it.hasAudio = true } }
main.post {
starting = 0
micSilenced = false
@@ -230,6 +334,8 @@ class CicadaApp : Application() {
overlayThisMeeting = false
overlay.collapsed = false
listen.start(source, "file")
+ startRecording()
+ watchEnd()
if (showLive) openLive()
if (play) {
try {
@@ -256,7 +362,58 @@ class CicadaApp : Application() {
changed()
}
- fun saveSettings() { settings.save(); ling.model = settings.model; changed() }
+ fun saveSettings() { settings.save(); ling.model = settings.model; SpeakerLabels.voices = settings.speakerVoices; changed() }
+
+ /// 保存会议录音: 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
+ val rec = Recorder(store.audioFile(id))
+ recorder = rec
+ listen.tap = { rec.write(it) }
+ }
+
+ // 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 }
+ startProblem = null
+ try { context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } catch (_: Exception) {}
+ val intent = Intent(context, ListenService::class.java).putExtra("kind", "import").setData(uri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ 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
+ stopListening(endedAt = start?.plusMillis((source.done * 1000).toLong()))
+ }, if (reason == null) 3000 else 0)
+ }
+ overlayClosed = true
+ importing = source
+ listen.start(source, "file")
+ listen.sessionId?.let { id -> store.update(id) { it.sourceFile = name; it.importing = true } }
+ 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.
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 78d3b05..835e556 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
@@ -18,7 +18,7 @@ import java.util.concurrent.TimeUnit
/// state | start [playback|mic] | stop | feed <wav in files/> | sample | view notes|subtitles
/// capture on|off | overlay show|hide | show main|live|records|settings|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/> | onboarded on|off | target <code> | ui <lang> | clip <text>
+/// import <session.json in files/> | importfile <audio or video in files/> | face | onboarded on|off | target <code> | ui <lang> | clip <text>
class DebugReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (!BuildConfig.DEBUG) return
@@ -56,12 +56,19 @@ 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()
"tts" -> {
val (lang, text) = arg.split(Regex("\\s+"), 2).let { it[0] to it.getOrElse(1) { "Hello." } }
app.background.execute { Log.d("debug: tts $lang -> ${app.voice.speak(text, lang, {}, {})}") }
@@ -101,6 +108,8 @@ class DebugReceiver : BroadcastReceiver() {
"lines" to (id?.let { app.store.lines(it).size } ?: 0),
"translated" to (id?.let { app.store.lines(it).count { l -> l.dst != null } } ?: 0),
"pending" to listen.pending,
+ "ending" to app.ending?.let { mapOf("reason" to it.reason.toString(), "left" to app.endingLeft(it)) },
+ "autoEnded" to app.autoEnded,
"say" to mapOf("can" to listen.canSay, "holding" to listen.holding, "saying" to listen.saying, "muted" to listen.muted, "speaking" to app.voice.speaking, "their" to listen.theirLanguage, "problem" to listen.sayProblem),
"spoken" to listen.spoken,
"target" to listen.target,
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/FaceActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/FaceActivity.kt
new file mode 100644
index 0000000..af49e08
--- /dev/null
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/FaceActivity.kt
@@ -0,0 +1,141 @@
+package com.wquguru.cicada
+
+import android.app.Activity
+import android.os.Bundle
+import android.view.Gravity
+import android.view.HapticFeedbackConstants
+import android.view.MotionEvent
+import android.view.View
+import android.widget.FrameLayout
+import android.widget.ImageView
+import android.widget.LinearLayout
+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
+ private lateinit var theirText: TextView
+ private lateinit var myLabel: TextView
+ private lateinit var myText: TextView
+ private lateinit var status: TextView
+ private lateinit var hint: TextView
+ private lateinit var hold: FrameLayout
+ private lateinit var holdIcon: ImageView
+ private var shown: String? = null
+ private var unobserve: (() -> Unit)? = null
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ ui = Ui(this)
+ window.statusBarColor = Palette.ground
+ window.navigationBarColor = Palette.ground
+ window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ theirLabel = ui.text("", 13f, Palette.secondary)
+ theirText = ui.text("", 28f, Palette.ink, bold = true).apply { leading(1.3f) }
+ myLabel = ui.text("", 13f, Palette.secondary)
+ myText = ui.text("", 22f, Palette.ink).apply { leading(1.45f) }
+ status = ui.text("", 13f, Palette.secondary).apply { gravity = Gravity.CENTER; accessibilityLiveRegion = View.ACCESSIBILITY_LIVE_REGION_POLITE }
+ hint = ui.text("", 14f, Palette.secondary).apply { gravity = Gravity.CENTER }
+ val theirs = ui.stack(12, theirLabel, theirText).apply {
+ background = ui.rounded(Palette.card, 28)
+ setPadding(ui.dp(24), ui.dp(24), ui.dp(24), ui.dp(24))
+ rotation = 180f
+ }
+ val mine = ui.stack(12, myLabel, myText).apply {
+ background = ui.rounded(Palette.card, 28)
+ setPadding(ui.dp(24), ui.dp(24), ui.dp(24), ui.dp(24))
+ }
+ holdIcon = ImageView(this).apply { setImageDrawable(ui.drawable(R.drawable.i_mic, android.graphics.Color.WHITE)); importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO }
+ hold = FrameLayout(this).apply {
+ addView(holdIcon, FrameLayout.LayoutParams(ui.dp(36), ui.dp(36), Gravity.CENTER))
+ contentDescription = L("按住说话")
+ isClickable = true; isFocusable = true
+ elevation = ui.dp(6).toFloat()
+ }
+ hold.setOnTouchListener { v, e ->
+ when (e.actionMasked) {
+ MotionEvent.ACTION_DOWN -> { v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); cicada.holdToSay(); update(); true }
+ MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); cicada.releaseToSay(); update(); true }
+ 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 {
+ addView(status, FrameLayout.LayoutParams(-1, -2, Gravity.CENTER))
+ addView(close, FrameLayout.LayoutParams(ui.dp(48), ui.dp(48), Gravity.END or Gravity.CENTER_VERTICAL))
+ }
+ val root = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(ui.dp(16), ui.dp(12), ui.dp(16), ui.dp(20))
+ addView(theirs, LinearLayout.LayoutParams(-1, 0, 1.1f))
+ addView(middle, LinearLayout.LayoutParams(-1, ui.dp(64)))
+ addView(mine, LinearLayout.LayoutParams(-1, 0, 0.8f))
+ addView(LinearLayout(context).apply {
+ orientation = LinearLayout.VERTICAL
+ gravity = Gravity.CENTER_HORIZONTAL
+ setPadding(0, ui.dp(28), 0, 0)
+ clipToPadding = false; clipChildren = false
+ addView(hold, LinearLayout.LayoutParams(ui.dp(104), ui.dp(104)))
+ addView(hint, LinearLayout.LayoutParams(-1, -2).apply { topMargin = ui.dp(18) })
+ }, 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
+ addView(root, FrameLayout.LayoutParams(-1, -1))
+ })
+ }
+
+ override fun onResume() {
+ super.onResume()
+ if (!cicada.listen.listening || cicada.listen.sourceKind != "mic") { finish(); return }
+ unobserve = cicada.observe(::update)
+ shown = null
+ update()
+ }
+
+ override fun onPause() { super.onPause(); unobserve?.invoke(); unobserve = null }
+
+ private fun update() {
+ val app = cicada
+ val l = app.listen
+ if (!l.listening) { finish(); return }
+ val their = l.theirLanguage
+ val mineLang = app.settings.targetCode
+ val line: TranscriptLine? = NotesViews.currentLines(app).lastOrNull()
+ val key = listOf(line?.id, line?.src, 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.src }
+ theirLabel.text = NotesViews.languageName(their)
+ theirText.text = when { line == null -> "…"; mine -> translated ?: "…"; else -> line.src }
+ myLabel.text = (if (line == null || mine) L("你") else L("对方")) + " · " + NotesViews.languageName(mineLang)
+ myText.text = when { line == null -> L("按住下面的按钮说话,松开后对方会听到译文"); mine -> line.src; else -> translated ?: line.src }
+ myText.setTextColor(if (line == null) Palette.secondary else Palette.ink)
+ val live = l.holding || app.voice.speaking
+ status.text = l.sayProblem ?: when {
+ l.holding -> L("正在听你说,念的时候不收音")
+ l.saying -> L("正在翻译…")
+ app.voice.speaking -> L("正在读…")
+ else -> L("正在听对方说")
+ }
+ status.setTextColor(if (l.sayProblem != null) Palette.link else Palette.secondary)
+ 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
new file mode 100644
index 0000000..1200a97
--- /dev/null
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/FileSource.kt
@@ -0,0 +1,130 @@
+package com.wquguru.cicada
+
+import android.content.Context
+import android.media.MediaCodec
+import android.media.MediaExtractor
+import android.media.MediaFormat
+import android.net.Uri
+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
+
+ override fun start() {
+ stopped = false
+ Thread({
+ 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
+ onEnded?.invoke(reason)
+ }, "FileSource").apply { isDaemon = true }.start()
+ }
+
+ override fun stop() { stopped = true }
+
+ private fun decode() {
+ val ex = MediaExtractor()
+ ex.setDataSource(context, uri, null)
+ val track = (0 until ex.trackCount).firstOrNull { ex.getTrackFormat(it).getString(MediaFormat.KEY_MIME)?.startsWith("audio/") == true }
+ ?: throw IllegalArgumentException("no audio track")
+ ex.selectTrack(track)
+ val format = ex.getTrackFormat(track)
+ if (format.containsKey(MediaFormat.KEY_DURATION)) total = format.getLong(MediaFormat.KEY_DURATION) / 1e6
+ val codec = MediaCodec.createDecoderByType(format.getString(MediaFormat.KEY_MIME)!!)
+ codec.configure(format, null, null, 0)
+ 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 carry = 0.0f; var hasCarry = false
+ val started = System.nanoTime()
+ var handed = 0L
+ val info = MediaCodec.BufferInfo()
+ var inputDone = false
+ try {
+ while (!stopped) {
+ if (!inputDone) {
+ val i = codec.dequeueInputBuffer(10_000)
+ if (i >= 0) {
+ val n = ex.readSampleData(codec.getInputBuffer(i)!!, 0)
+ if (n < 0) { codec.queueInputBuffer(i, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM); inputDone = true }
+ else { codec.queueInputBuffer(i, 0, n, ex.sampleTime, 0); ex.advance() }
+ }
+ }
+ val o = codec.dequeueOutputBuffer(info, 10_000)
+ if (o == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
+ rate = codec.outputFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE)
+ channels = codec.outputFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT)
+ continue
+ }
+ if (o < 0) continue
+ val buf = codec.getOutputBuffer(o)!!.order(java.nio.ByteOrder.LITTLE_ENDIAN)
+ 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]
+ val b = mono[minOf(frames - 1, i0 + 1)]
+ val v = a + (b - a) * (pos - i0).toFloat()
+ out.add(v.toInt().coerceIn(-32768, 32767).toShort())
+ pos += step
+ }
+ 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
+ while (k < all.size && !stopped) {
+ val piece = all.copyOfRange(k, minOf(all.size, k + chunk))
+ onSamples?.invoke(piece)
+ handed += piece.size; k += piece.size
+ done = handed.toDouble() / Segmenter.RATE
+ val due = started + (done / speed * 1e9).toLong()
+ val wait = (due - System.nanoTime()) / 1_000_000
+ if (wait > 0) Thread.sleep(wait)
+ }
+ }
+ if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) break
+ }
+ } finally {
+ try { codec.stop() } catch (_: Exception) {}
+ codec.release(); ex.release()
+ }
+ if (total <= 0) total = done
+ Log.d("import: decoded ${done.toInt()} s")
+ }
+
+ 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 ->
+ if (c.moveToFirst()) c.getString(0)?.takeIf { it.isNotBlank() }?.let { return it }
+ }
+ } catch (_: Exception) {}
+ return uri.lastPathSegment?.substringAfterLast('/') ?: "audio"
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/ImportActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/ImportActivity.kt
new file mode 100644
index 0000000..128e18a
--- /dev/null
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/ImportActivity.kt
@@ -0,0 +1,122 @@
+package com.wquguru.cicada
+
+import android.app.Activity
+import android.content.Intent
+import android.net.Uri
+import android.os.Build
+import android.os.Bundle
+import android.view.Gravity
+import android.widget.FrameLayout
+import android.widget.LinearLayout
+import cicada.Languages
+import cicada.Strings.L
+
+/// 导入录音或视频 (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
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ ui = Ui(this)
+ watching = savedInstanceState?.getString("watching")
+ content = FrameLayout(this)
+ val body = ui.stack(0, content).apply { setPadding(ui.dp(16), ui.dp(8), ui.dp(16), ui.dp(24)) }
+ setContentView(ui.screen(this, L("导入录音或视频"), back = true, ground = Palette.ground, body = body))
+ if (savedInstanceState == null) shared(intent)?.let(::start)
+ }
+
+ 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)
+ else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_STREAM)
+ }
+
+ private fun start(uri: Uri) {
+ cicada.importFile(this, uri)
+ watching = null
+ shown = null
+ render()
+ }
+
+ override fun onResume() { super.onResume(); unobserve = cicada.observe(::render); shown = null; render() }
+ override fun onPause() { super.onPause(); unobserve?.invoke(); unobserve = null }
+ override fun onSaveInstanceState(out: Bundle) { super.onSaveInstanceState(out); watching?.let { out.putString("watching", it) } }
+
+ private fun render() {
+ val app = cicada
+ val file = app.importing
+ if (file != null) watching = app.listen.sessionId
+ val done = watching?.takeIf { file == null }?.let { app.store.get(it) }
+ val key = listOf(file?.done?.toInt(), file?.total?.toInt(), done?.id, done?.lines?.size, app.startProblem, app.listen.listening, app.settings.target).joinToString("|")
+ if (key == shown) return
+ shown = key
+ content.removeAllViews()
+ val column = ui.stack(12)
+ when {
+ file != null -> {
+ val s = app.listen.sessionId?.let { app.store.get(it) }
+ column.addView(ui.card(fileRow(s?.sourceFile ?: "", file.total)).apply {
+ addView(ui.row(8, ui.dot(Palette.accent), ui.text(L("正在转写"), 15f, Palette.ink, bold = true)), ui.lp(top = 18))
+ addView(NotesViews.progress(ui, file), ui.lp(top = 10))
+ addView(ui.helper(L("切到别的 app 也会继续,通知栏里能看进度")), ui.lp(top = 10))
+ })
+ column.addView(ui.group(listOf(
+ ui.listRow(L("文件里说的"), null, trailing = ui.text(app.listen.spoken?.let { NotesViews.languageName(it) } ?: L("自动识别"), 15f, Palette.secondary), chevron = false),
+ ui.listRow(L("翻译成"), null, trailing = ui.text(NotesViews.languageName(app.settings.targetCode), 15f, Palette.secondary), chevron = false),
+ ui.listRow(L("转完后生成纪要"), null, trailing = ui.text(L("开"), 15f, Palette.secondary), chevron = false))), ui.lp(top = 12))
+ column.addView(ui.button(L("在后台继续"), "primary") { finish() }, ui.lp(top = 20))
+ column.addView(ui.button(L("停止转写"), "quiet") { app.stopListening() }.apply { background = null }, ui.lp(top = 4))
+ }
+ done != null -> {
+ column.addView(ui.card(fileRow(done.sourceFile ?: "", done.durationSeconds), gap = 16).apply {
+ addView(ui.text(L("转写完成"), 17f, Palette.ink, bold = true), ui.lp(top = 18))
+ addView(ui.helper("${done.lines.size} ${L("句")} · ${L("纪要在会议记录里")}"), ui.lp(top = 4))
+ addView(ui.button(L("查看会议记录"), "primary") {
+ startActivity(Intent(this@ImportActivity, RecordActivity::class.java).putExtra("id", done.id)); finish()
+ }, ui.lp(top = 18))
+ })
+ }
+ else -> {
+ val card = ui.card(gap = 14)
+ card.addView(ui.row(12, ui.tile(R.drawable.i_import, 52, Palette.ink, android.graphics.Color.WHITE).apply { background = ui.rounded(Palette.ink, 14) },
+ ui.stack(3, ui.text(L("录音、视频都可以"), 17f, Palette.ink, bold = true), ui.helper(L("m4a、mp3、wav、mp4、mov…"))).apply { layoutParams = ui.weight() }))
+ card.addView(ui.helper(L("转成一场会议记录:双语文字记录和纪要。也可以在别的 app 里分享到知了。")))
+ app.startProblem?.let { card.addView(ui.text(it, 14f, Palette.link)) }
+ card.addView(ui.button(L("选择文件"), "primary", R.drawable.i_import) { pick() }.apply { isEnabled = !app.listen.listening })
+ column.addView(card)
+ }
+ }
+ content.addView(column)
+ }
+
+ private fun fileRow(name: String, seconds: Double) = LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ background = ui.rounded(Palette.ground, 20)
+ setPadding(ui.dp(14), ui.dp(14), ui.dp(14), ui.dp(14))
+ addView(ui.tile(R.drawable.i_pip, 52, Palette.ink, android.graphics.Color.WHITE).apply { background = ui.rounded(Palette.ink, 12) })
+ addView(ui.stack(3, ui.text(name, 16f, Palette.ink, bold = true, lines = 2), ui.helper(if (seconds > 0) Languages.clock(seconds) else "")),
+ ui.weight().apply { leftMargin = ui.dp(14) })
+ }
+
+ private fun pick() {
+ val i = Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*")
+ .putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("audio/*", "video/*"))
+ @Suppress("DEPRECATION") startActivityForResult(i, 9)
+ }
+
+ @Deprecated("Deprecated in Java")
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ if (requestCode == 9 && resultCode == RESULT_OK) data?.data?.let(::start)
+ }
+}
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 26b99a0..b0ca022 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/ListenService.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/ListenService.kt
@@ -29,10 +29,15 @@ class ListenService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val app = cicada
if (intent?.action == ACTION_STOP) { app.stopListening(); return START_NOT_STICKY }
+ 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 = if (kind == "playback") ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION else ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
+ val type = when (kind) {
+ "playback" -> ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
+ "import" -> ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
+ else -> ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
+ }
try {
startForeground(ID, notification(this), type)
} catch (e: Exception) {
@@ -43,6 +48,11 @@ class ListenService : Service() {
stopSelf()
return START_NOT_STICKY
}
+ if (kind == "import") {
+ val uri = intent.data ?: run { stopSelf(); return START_NOT_STICKY }
+ app.beginImport(uri)
+ return START_NOT_STICKY
+ }
val source = if (kind == "playback") {
val data: Intent? = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra("data", Intent::class.java) else @Suppress("DEPRECATION") intent.getParcelableExtra("data")
val code = intent.getIntExtra("code", Activity.RESULT_CANCELED)
@@ -66,6 +76,7 @@ class ListenService : Service() {
companion object {
const val ID = 1
const val ACTION_STOP = "com.wquguru.cicada.STOP"
+ const val ACTION_KEEP = "com.wquguru.cicada.KEEP"
private const val CHANNEL = "listening"
private var lastText: String? = null
@@ -85,26 +96,40 @@ class ListenService : Service() {
.addNextIntent(Intent(context, ListeningActivity::class.java))
.getPendingIntent(0, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val stop = PendingIntent.getService(context, 1, Intent(context, ListenService::class.java).setAction(ACTION_STOP), PendingIntent.FLAG_IMMUTABLE)
- val title = if (listen.sourceKind == "mic") L("知了 · 面对面") else L("知了 · 正在听手机里的声音")
- return Notification.Builder(context, CHANNEL)
+ val ending = app.ending
+ val file = app.importing
+ val title = when {
+ file != null -> L("知了 · 正在转写") + " " + (session?.sourceFile ?: "")
+ ending != null -> app.endingTitle(ending)
+ listen.sourceKind == "mic" -> L("知了 · 面对面")
+ else -> L("知了 · 正在听手机里的声音")
+ }
+ val text = if (file != null) "${cicada.Languages.clock(file.done)} / ${cicada.Languages.clock(file.total)}"
+ else if (ending != null) app.endingDetail(ending) else listen.problem ?: line?.let { it.dst ?: it.src } ?: L("等有人说话…")
+ val b = Notification.Builder(context, CHANNEL)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
- .setContentText(listen.problem ?: line?.let { it.dst ?: it.src } ?: L("等有人说话…"))
+ .setContentText(text)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setUsesChronometer(session != null)
.setWhen(session?.startedAt?.toEpochMilli() ?: System.currentTimeMillis())
.setContentIntent(open)
- .addAction(Notification.Action.Builder(null, L("结束"), stop).build())
- .setCategory(Notification.CATEGORY_SERVICE)
- .build()
+ // 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 b.addAction(Notification.Action.Builder(null, L("结束"), stop).build())
+ 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") { lastText = null; return }
- val text = app.listen.sessionId?.let { app.store.lines(it).lastOrNull()?.let { l -> l.dst ?: l.src } } + "|" + app.listen.problem
+ if (!app.listen.listening || (app.listen.sourceKind == "file" && app.importing == null)) { lastText = null; return }
+ val text = app.importing?.let { "${it.done.toInt()}" } + app.listen.sessionId?.let { app.store.lines(it).lastOrNull()?.let { l -> l.dst ?: l.src } } + "|" + app.listen.problem +
+ "|" + app.ending?.let { app.endingLeft(it) }
if (text == lastText) return
lastText = text
if (context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED && Build.VERSION.SDK_INT >= 33) return
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 c7c45de..b2d6a37 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/ListeningActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/ListeningActivity.kt
@@ -1,7 +1,6 @@
package com.wquguru.cicada
import android.app.Activity
-import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
@@ -11,7 +10,9 @@ import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
+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; 结束
@@ -33,7 +34,7 @@ class ListeningActivity : Activity() {
private var unobserve: (() -> Unit)? = 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(); cicada.main.postDelayed(this, 1000) }
+ override fun run() { badgeText.text = NotesViews.status(cicada); render(); NotesViews.tickEnding(content, cicada); cicada.main.postDelayed(this, 1000) }
}
override fun onCreate(savedInstanceState: Bundle?) {
@@ -42,30 +43,54 @@ class ListeningActivity : Activity() {
// 实时纪要 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.link, bold = true, lines = 1)
+ 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
- background = ui.rounded(Palette.accentPale, 16)
- setPadding(ui.dp(14), ui.dp(7), ui.dp(14), ui.dp(7))
+ background = ui.rounded(Palette.card, 22)
+ minimumHeight = ui.dp(44)
+ setPadding(ui.dp(14), 0, ui.dp(16), 0)
+ ui.lift(this, 1)
addView(ui.dot(Palette.accent, 8))
addView(badgeText, LinearLayout.LayoutParams(-2, -2).apply { leftMargin = ui.dp(8) })
accessibilityLiveRegion = View.ACCESSIBILITY_LIVE_REGION_NONE
}
sourceText = ui.helper("").apply { gravity = android.view.Gravity.CENTER }
tabsHost = FrameLayout(this)
- content = ui.stack(12).apply { setPadding(ui.dp(16), ui.dp(16), ui.dp(16), ui.dp(16)) }
+ content = ui.stack(12).apply { setPadding(ui.dp(16), ui.dp(12), ui.dp(16), ui.dp(16)) }
scroll = ScrollView(this).apply { isVerticalScrollBarEnabled = false; addView(content); isFillViewport = true }
val body = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
- addView(sourceText, LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = ui.dp(6) })
- addView(tabsHost, LinearLayout.LayoutParams(-1, -2).apply { leftMargin = ui.dp(16); rightMargin = ui.dp(16) })
- addView(ui.divider(), LinearLayout.LayoutParams(-1, 1).apply { leftMargin = ui.dp(16); rightMargin = ui.dp(16) })
+ addView(tabsHost, LinearLayout.LayoutParams(-1, -2).apply { leftMargin = ui.dp(16); rightMargin = ui.dp(16); topMargin = ui.dp(8) })
+ addView(sourceText, LinearLayout.LayoutParams(-1, -2).apply { topMargin = ui.dp(10) })
addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f))
}
bottomHost = FrameLayout(this)
buildBottom()
- setContentView(ui.screen(this, null, back = true, ground = Palette.ground, center = badge, bottom = bottomHost, scroll = false, body = body))
+ actionHost = FrameLayout(this)
+ setContentView(ui.screen(this, null, back = true, ground = Palette.ground, center = badge, bottom = bottomHost, scroll = false, body = body,
+ actions = listOf(actionHost)))
+ buildAction()
+ }
+
+ 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
+ actionKind = kind
+ actionHost.removeAllViews()
+ val b = when (kind) {
+ "mic" -> if (cicada.settings.speakBack) ui.roundButton(R.drawable.i_flip, L("面对面翻译")) { startActivity(Intent(this, FaceActivity::class.java)) } else null
+ "playback" -> ui.roundButton(R.drawable.i_pip, L("在视频上看")) { watchOver() }
+ else -> null
+ }
+ if (b != null) actionHost.addView(b)
+ 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
@@ -76,14 +101,15 @@ class ListeningActivity : Activity() {
bottomKind = kind
bottomHost.removeAllViews()
sayButton = null; sayLabel = null; sayHelper = null
- if (kind != "mic") {
- bottomHost.addView(ui.bottomBar(
- ui.button(L("在视频上看"), "quiet", R.drawable.i_pip) { watchOver() },
- ui.button(L("结束"), "primary", R.drawable.i_stop) { end() }))
+ if (kind != "mic" || !cicada.settings.speakBack) {
+ bottomHost.addView(if (kind == "playback") ui.bottomBar(
+ ui.button(L("在视频上看"), "white", R.drawable.i_pip) { watchOver() },
+ ui.button(L("结束"), "primary", R.drawable.i_stop) { end() })
+ else ui.bottomBar(ui.button(L("结束"), "primary", R.drawable.i_stop) { end() }))
return
}
val helper = ui.helper("").apply { gravity = android.view.Gravity.CENTER }
- val say = ui.button(L("按住说话"), "primary", R.drawable.i_mic) {}
+ val say = ui.button(L("按住说话"), "primary", R.drawable.i_mic, height = 64) {}
val label = (0 until say.childCount).map { say.getChildAt(it) }.filterIsInstance<TextView>().first()
say.setOnTouchListener { v, e ->
when (e.actionMasked) {
@@ -100,12 +126,13 @@ class ListeningActivity : Activity() {
}
// 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("结束"), "quiet", R.drawable.i_stop) { end() }, say)
- (say.layoutParams as LinearLayout.LayoutParams).weight = 1.6f
+ val bar = ui.bottomBar(ui.button(L("结束"), "white", height = 64) { end() }, say)
+ (say.layoutParams as LinearLayout.LayoutParams).weight = 2.2f
val box = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
- addView(helper, LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = ui.dp(8); leftMargin = ui.dp(16); rightMargin = ui.dp(16) })
- addView(bar)
+ background = ui.fade()
+ addView(helper, LinearLayout.LayoutParams(-1, -2).apply { topMargin = ui.dp(24); leftMargin = ui.dp(16); rightMargin = ui.dp(16) })
+ addView(bar.apply { background = null; setPadding(paddingLeft, ui.dp(8), paddingRight, paddingBottom) })
}
bottomHost.addView(box)
sayButton = say; sayLabel = label; sayHelper = helper
@@ -126,7 +153,11 @@ class ListeningActivity : Activity() {
}
sayLabel?.text = text
say.contentDescription = text
- say.background = ui.rounded(if (live) Palette.accent else Palette.ink, 16)
+ // 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)
sayHelper?.text = l.sayProblem ?: L("松开后用 {lang} 读出来").replace("{lang}", their)
sayHelper?.setTextColor(if (l.sayProblem != null) Palette.link else Palette.secondary)
}
@@ -154,23 +185,25 @@ class ListeningActivity : Activity() {
if (!app.listen.listening && app.listen.pending == 0) { openRecord(); return }
badgeText.text = NotesViews.status(app)
buildBottom()
+ buildAction()
updateSay()
sourceText.text = NotesViews.sourceLine(app)
val key = NotesViews.liveKey(app) + tab + app.listen.spoken
if (key == shown) return
shown = key
tabsHost.removeAllViews()
- tabsHost.addView(ui.tabs(listOf(L("实时纪要"), L("字幕")), tab) { tab = it; render() })
+ tabsHost.addView(ui.tabs(listOf(L("实时纪要"), L("字幕")), tab, ink = true, track = Palette.card) { tab = it; render() }.apply { ui.lift(this, 1) })
content.removeAllViews()
+ NotesViews.endingStrip(ui, app)?.let { content.addView(it) }
NotesViews.banner(ui, app) { switchToMic() }?.let { content.addView(it) }
if (tab == 1) {
content.addView(ui.spacer(), LinearLayout.LayoutParams(-1, 0, 1f))
- content.addView(NotesViews.stream(ui, app, 6))
+ content.addView(NotesViews.bubbles(ui, app, 12))
scroll.post { scroll.fullScroll(View.FOCUS_DOWN) }
} else {
val card = NotesViews.notesBody(ui, app.notes.notes, app.notes.status, app.listen.listening).apply {
- background = ui.rounded(Palette.card, 20)
- setPadding(ui.dp(18), ui.dp(18), ui.dp(18), ui.dp(18))
+ background = ui.rounded(Palette.card, 22)
+ setPadding(ui.dp(18), ui.dp(18), ui.dp(18), ui.dp(20))
}
content.addView(card)
}
@@ -187,7 +220,16 @@ class ListeningActivity : Activity() {
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 }
+ ui.confirm(this, L("结束这场会议?"), LF("已记录 %@ · %lld 句。结束后停止收听,并整理一份完整版纪要。", Languages.clock(s.durationSeconds), s.lines.size),
+ ok = L("结束会议"), cancel = L("继续记录")) { endNow() }
+ }
+
+ private fun endNow() {
val id = cicada.listen.sessionId
cicada.stopListening {
if (id != null && cicada.store.get(id) != null) startActivity(Intent(this, RecordActivity::class.java).putExtra("id", id))
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 0e2653f..d58f2aa 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/MainActivity.kt
@@ -2,7 +2,6 @@ package com.wquguru.cicada
import android.Manifest
import android.app.Activity
-import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
@@ -21,8 +20,9 @@ import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
-/// 首页: start listening (what the phone plays, or 面对面), the meeting going on if any, and the
-/// last few meetings. One job per area, the main action a 56dp button.
+/// 首页 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
@@ -40,13 +40,19 @@ class MainActivity : Activity() {
ui = Ui(this)
if (!cicada.settings.onboarded) startActivity(Intent(this, OnboardingActivity::class.java))
top = FrameLayout(this); recent = FrameLayout(this)
- val body = ui.stack(16, top, recent).apply { setPadding(ui.dp(16), ui.dp(4), ui.dp(16), ui.dp(32)) }
- setContentView(ui.screen(this, L("知了"), back = false, ground = Palette.ground, body = body,
- actions = listOf(ui.iconButton(R.drawable.i_settings, L("设置"), Palette.body) { startActivity(Intent(this, SettingsActivity::class.java)) })))
+ val body = ui.stack(8, top, recent).apply { setPadding(ui.dp(16), ui.dp(8), ui.dp(16), ui.dp(24)) }
+ builtTitle = L("会议记录")
+ setContentView(ui.screen(this, builtTitle, back = false, ground = Palette.ground, body = body, bottom = ui.nav(this, "records"),
+ actions = listOf(ui.roundButton(R.drawable.i_import, L("导入录音或视频")) { startActivity(Intent(this, ImportActivity::class.java)) })))
}
+ private var builtTitle = ""
+
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
render()
@@ -65,13 +71,19 @@ class MainActivity : Activity() {
private fun renderTop() {
val app = cicada
- val key = listOf(NotesViews.liveKey(app), app.settings.source, app.settings.target, app.canOverlay, app.settings.overlay, micDenied, app.listen.spoken).joinToString("|")
+ val file = app.importing
+ val key = listOf(NotesViews.liveKey(app), app.autoEnded, app.settings.source, app.settings.target, app.canOverlay, app.settings.overlay, micDenied, app.listen.spoken,
+ app.startProblem, file?.done?.toInt()).joinToString("|")
if (key == shownTop) return
shownTop = key
top.removeAllViews()
- val column = ui.stack(16)
- column.addView(if (app.listen.listening) liveCard() else startCard())
- if (app.settings.overlay && !app.canOverlay) column.addView(tipCard())
+ val column = ui.stack(12)
+ column.addView(when {
+ file != null -> importCard(file)
+ app.listen.listening -> liveCard()
+ else -> startCard()
+ })
+ if (app.settings.overlay && !app.canOverlay && file == null) column.addView(tipCard())
top.addView(column)
}
@@ -82,39 +94,62 @@ class MainActivity : Activity() {
clockText = status
val card = ui.card(ui.row(8, ui.dot(Palette.accent), status), gap = 12)
card.addView(ui.helper(NotesViews.sourceLine(app)), ui.lp(top = 4))
- NotesViews.currentLines(app).lastOrNull()?.let { l -> card.addView(ui.text(l.dst ?: l.src, 18f, Palette.ink, bold = true, lines = 3), ui.lp(top = 12)) }
+ NotesViews.currentLines(app).lastOrNull()?.let { l -> card.addView(ui.text(l.dst ?: l.src, 18f, Palette.ink, bold = true, lines = 3).apply { leading(1.4f) }, ui.lp(top = 12)) }
card.addView(ui.button(L("回到正在听"), "primary", R.drawable.i_waves) { app.openLive() }, ui.lp(top = 16))
return card
}
+ /// A file being transcribed: its name and how far it is.
+ private fun importCard(file: FileSource): LinearLayout {
+ clockText = null
+ val app = cicada
+ val name = app.listen.sessionId?.let { app.store.get(it) }?.sourceFile ?: ""
+ val card = ui.card(gap = 10)
+ card.addView(ui.row(8, ui.dot(Palette.accent), ui.text(L("正在转写"), 15f, Palette.link, bold = true), ui.text(name, 15f, Palette.ink, lines = 1).apply { layoutParams = ui.weight() }))
+ card.addView(NotesViews.progress(ui, file), ui.lp(top = 6))
+ card.addView(ui.button(L("查看进度"), "quiet") { startActivity(Intent(this, ImportActivity::class.java)) }, ui.lp(top = 10))
+ return card
+ }
+
private fun startCard(): LinearLayout {
val app = cicada
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
+ addView(ui.dot(Palette.outline, 8))
+ addView(ui.text(L("会议已自动结束"), 15f, Palette.ink, bold = true), ui.weight().apply { leftMargin = ui.dp(10) })
+ app.listen.sessionId?.takeIf { app.store.get(it) != null }?.let { id ->
+ addView(ui.textButton(L("查看纪要")) { startActivity(Intent(this@MainActivity, RecordActivity::class.java).putExtra("id", id)) })
+ }
+ }, ui.lp(top = 0).apply { bottomMargin = ui.dp(12) })
card.addView(ui.segmented(listOf("playback" to L("手机里的声音"), "mic" to L("面对面")), app.settings.source) {
app.settings.source = it; app.saveSettings(); shownTop = null; renderTop()
})
val desc = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
- addView(ui.tile(if (pb) R.drawable.i_speaker else R.drawable.i_mic))
+ gravity = Gravity.CENTER_VERTICAL
+ addView(ui.logo(44))
addView(ui.stack(2,
- ui.text(if (pb) L("视频、直播、网课里的声音") else L("用麦克风听身边的人"), 15f, Palette.ink, medium = true),
+ ui.text(if (pb) L("视频、直播、网课里的声音") else L("用麦克风听身边的人"), 17f, Palette.ink, bold = true),
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_VERTICAL
- minimumHeight = ui.dp(52)
+ gravity = Gravity.CENTER
+ minimumHeight = ui.dp(44)
setPadding(ui.dp(16), 0, ui.dp(12), 0)
addView(ui.text(L("自动识别"), 15f, Palette.secondary))
- addView(ui.icon(R.drawable.i_arrow_right, 18, Palette.secondary), LinearLayout.LayoutParams(ui.dp(18), ui.dp(18)).apply { leftMargin = ui.dp(10); rightMargin = ui.dp(10) })
- addView(ui.text(NotesViews.languageName(app.settings.targetCode), 15f, Palette.ink, medium = true), ui.weight())
- addView(ui.icon(R.drawable.i_chevron_right, 20, Palette.tertiary))
+ addView(ui.icon(R.drawable.i_arrow_right, 16, Palette.secondary), LinearLayout.LayoutParams(ui.dp(16), ui.dp(16)).apply { leftMargin = ui.dp(8); rightMargin = ui.dp(8) })
+ addView(ui.text(NotesViews.languageName(app.settings.targetCode), 15f, Palette.ink, medium = true))
+ addView(ui.icon(R.drawable.i_chevron_down, 18, Palette.tertiary), LinearLayout.LayoutParams(ui.dp(18), ui.dp(18)).apply { leftMargin = ui.dp(6) })
contentDescription = L("翻译成") + " " + NotesViews.languageName(app.settings.targetCode)
- ui.tappable(this, 14, ui.rounded(Palette.ground, 14)) { chooseTarget() }
+ ui.tappable(this, 22, ui.rounded(Palette.ground, 22)) { chooseTarget() }
}
card.addView(lang, ui.lp(top = 16))
app.startProblem?.let { card.addView(ui.text(it, 14f, Palette.link).apply { accessibilityLiveRegion = 1 }, ui.lp(top = 16)) }
@@ -129,7 +164,7 @@ class MainActivity : Activity() {
private fun tipCard() = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
- background = ui.rounded(Palette.card, 20)
+ 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_pip, 40, Palette.accentPale, Palette.link).apply { background = ui.rounded(Palette.accentPale, 20) })
addView(ui.stack(2, ui.text(L("在视频上直接看字幕"), 15f, Palette.ink, medium = true), ui.helper(L("开启“显示在其他应用上层”"))),
@@ -137,36 +172,31 @@ class MainActivity : Activity() {
addView(ui.textButton(L("去开启")) { OverlayGuideActivity.open(this@MainActivity, direct = true) })
}
+ /// 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()
+ val sessions = app.store.all().take(60)
val liveId = if (app.listen.listening) app.listen.sessionId else null
- val key = sessions.take(3).joinToString { "${it.id}:${SessionStore.displayTitle(it)}:${it.lines.size}:${it.endedAt}" } + liveId + app.store.loaded
+ val key = sessions.joinToString { "${it.id}:${SessionStore.displayTitle(it)}:${it.lines.size}:${it.endedAt}:${it.notes?.todos?.size}" } + liveId + app.store.loaded
if (key == shownRecent) return
shownRecent = key
recent.removeAllViews()
- val column = ui.stack(8)
- val header = LinearLayout(this).apply {
- orientation = LinearLayout.HORIZONTAL
- gravity = Gravity.CENTER_VERTICAL
- setPadding(ui.dp(4), 0, 0, 0)
- addView(ui.heading(L("最近的会议"), 16f), ui.weight())
- if (sessions.isNotEmpty()) addView(ui.textButton(L("全部")) { startActivity(Intent(this@MainActivity, RecordsActivity::class.java)) })
+ val column = ui.stack(0)
+ if (sessions.isEmpty() && !app.store.loaded) column.addView(android.widget.ProgressBar(this).apply { isIndeterminate = true; contentDescription = L("正在加载…") }, ui.lp(top = 16, width = ui.dp(32), height = ui.dp(32)))
+ else if (sessions.isEmpty()) column.addView(ui.helper(L("还没有会议记录")).apply { setPadding(ui.dp(16), ui.dp(20), 0, 0) })
+ val days = LinkedHashMap<String, MutableList<Session>>()
+ for (s in sessions) days.getOrPut(day(s.startedAt)) { mutableListOf() }.add(s)
+ for ((d, items) in days) {
+ column.addView(ui.sectionLabel(d))
+ column.addView(ui.group(items.map { recordRow(this, ui, it, it.id == liveId) }))
}
- column.addView(header)
- if (sessions.isEmpty() && !app.store.loaded) column.addView(android.widget.ProgressBar(this).apply { isIndeterminate = true; contentDescription = L("正在加载…") }, ui.lp(top = 8, width = ui.dp(32), height = ui.dp(32)))
- else if (sessions.isEmpty()) column.addView(ui.helper(L("还没有会议记录")).apply { setPadding(ui.dp(4), ui.dp(4), 0, 0) })
- else column.addView(ui.group(sessions.take(3).map { recordRow(this, ui, it, it.id == liveId) }))
recent.addView(column)
}
private fun chooseTarget() {
val app = cicada
val options = listOf("system" to L("跟随系统")) + Languages.targets.map { it.code to it.name }
- AlertDialog.Builder(this).setTitle(L("翻译成"))
- .setSingleChoiceItems(options.map { it.second }.toTypedArray(), options.indexOfFirst { it.first == app.settings.target }) { d, i ->
- d.dismiss(); app.settings.target = options[i].first; app.saveSettings(); shownTop = null; renderTop()
- }.setNegativeButton(L("取消"), null).show()
+ ui.choose(this, L("翻译成"), options, app.settings.target) { app.settings.target = it; app.saveSettings(); shownTop = null; renderTop() }
}
companion object {
@@ -196,11 +226,13 @@ class MainActivity : Activity() {
val titleView = LinearLayout(activity).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
- if (live) addView(ui.badge(L("正在听"), dot = true), LinearLayout.LayoutParams(-2, -2).apply { rightMargin = ui.dp(8) })
- addView(ui.text(title, 16f, Palette.ink, medium = true, lines = 1), ui.weight())
+ 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 "${day(s.startedAt)} ${time(s.startedAt)} · ${Languages.clock(s.durationSeconds)} · ${s.lines.size} ${L("句")}"
+ else listOfNotNull("${time(s.startedAt)}", Languages.clock(s.durationSeconds), "${s.lines.size} ${L("句")}", from).joinToString(" · ")
val todos = s.notes?.todos?.size ?: 0
val trailing = if (todos > 0) ui.badge(cicada.Strings.LF("%@ 个待办", todos), Palette.body, Palette.ground) else null
return ui.listRow(title, meta, trailing = trailing, titleView = titleView) {
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 2a58faa..84b2921 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/NotesViews.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/NotesViews.kt
@@ -3,6 +3,7 @@ package com.wquguru.cicada
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
+import android.widget.TextView
import cicada.Languages
import cicada.MeetingNotes
import cicada.NotesEngine
@@ -29,7 +30,8 @@ object NotesViews {
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?.src, line?.dst, app.notes.status, app.notes.notes.updatedAt, app.notes.notes.covered).joinToString("|")
+ line?.id, line?.src, line?.dst, app.notes.status, app.notes.notes.updatedAt, app.notes.notes.covered,
+ app.ending?.deadline).joinToString("|")
}
/// "正在听 · 03:12" / "面对面 · 03:12".
@@ -58,6 +60,40 @@ object NotesViews {
}
/// 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 {
+ background = ui.rounded(Palette.accentPale, 16)
+ setPadding(ui.dp(16), ui.dp(14), ui.dp(16), ui.dp(14))
+ accessibilityLiveRegion = View.ACCESSIBILITY_LIVE_REGION_POLITE
+ addView(ui.stack(3, ui.text(app.endingTitle(p), if (compact) 15f else 16f, Palette.ink, bold = true),
+ ui.text(app.endingDetail(p), 13f, Palette.secondary).apply { tag = ENDING_DETAIL }))
+ addView(LinearLayout(ui.context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ addView(ui.button(L("继续记录"), "primary", height = 44) { app.keepRecording() }, ui.weight())
+ addView(ui.button(L("现在结束"), "quiet", height = 44) { app.stopListening() }.apply { background = ui.rounded(Palette.card, 16) },
+ ui.weight().apply { leftMargin = ui.dp(10) })
+ })
+ }
+ }
+
+ 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)
+ (root?.findViewWithTag<TextView>(ENDING_BAR))?.text = endingBarText(app)
+ }
+
fun banner(ui: Ui, app: CicadaApp, onMic: (() -> Unit)?): View? {
val problem = app.listen.problem
val (iconRes, text) = when {
@@ -80,6 +116,73 @@ object NotesViews {
}
}
+ /// 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
+ box.addView(LinearLayout(ui.context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ background = ui.rounded(android.graphics.Color.parseColor("#E7E9EE"), 4)
+ weightSum = 1f
+ addView(View(ui.context).apply { background = ui.rounded(Palette.accent, 4) }, LinearLayout.LayoutParams(0, -1, frac.toFloat()))
+ contentDescription = "${(frac * 100).toInt()}%"
+ }, LinearLayout.LayoutParams(-1, ui.dp(8)))
+ box.addView(ui.text("${Languages.clock(file.done)} / ${Languages.clock(file.total)}", 13f, Palette.secondary).apply { fontFeatureSettings = "tnum" })
+ 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 {
+ gravity = Gravity.CENTER
+ background = ui.rounded(if (line.speaker == "me") Palette.ink else voiceColor(numbers[line.id]).first, size / 2)
+ layoutParams = LinearLayout.LayoutParams(ui.dp(size), ui.dp(size))
+ 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): 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.src
+ if (translated) card.addView(ui.text(line.src, Ui.Type.ORIGINAL, Palette.secondary).apply { leading(1.45f) })
+ card.addView(ui.text(line.dst?.takeIf { translated } ?: line.src, Ui.Type.TRANSLATION, Palette.ink).apply { leading(1.5f) })
+ 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)
+ if (lines.isEmpty()) return stream(ui, app, 0)
+ val numbers = cicada.SpeakerLabels.numbers(lines)
+ val names = app.listen.sessionId?.let { app.store.get(it) }?.let { cicada.SpeakerLabels.names(it) } ?: emptyMap()
+ val shown = lines.takeLast(count)
+ shown.forEachIndexed { i, l -> box.addView(bubble(ui, l, numbers, names, i == shown.lastIndex, app.listen.listening)) }
+ if (app.listen.listening) box.addView(LinearLayout(ui.context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ setPadding(ui.dp(8), 0, 0, 0)
+ listOf(1f, 0.6f, 0.3f).forEach { a -> addView(ui.dot(Palette.accent, 6).apply { alpha = a }, LinearLayout.LayoutParams(ui.dp(6), ui.dp(6)).apply { rightMargin = ui.dp(5) }) }
+ addView(ui.text(L("正在听下一句…"), 13f, Palette.secondary), LinearLayout.LayoutParams(-2, -2).apply { leftMargin = ui.dp(4) })
+ })
+ 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)
@@ -119,7 +222,7 @@ object NotesViews {
val translated = !line.dst.isNullOrEmpty() && line.dst != line.src
if (!translated && line.speaker == "me") card.addView(ui.text(L("你"), 14f, Palette.secondary))
if (translated) card.addView(ui.text(said(line), 14f, Palette.secondary, lines = if (lines > 0) lines - 1 else 0))
- card.addView(ui.text(line.dst ?: line.src, big, Palette.ink, bold = true, lines = lines).apply { setLineSpacing(0f, 1.25f) }, ui.lp(top = if (translated || line.speaker == "me") 8 else 0))
+ card.addView(ui.text(line.dst ?: line.src, big, Palette.ink, bold = true, lines = lines).apply { leading(1.25f) }, ui.lp(top = if (translated || line.speaker == "me") 8 else 0))
if (dots && app.listen.listening) card.addView(LinearLayout(ui.context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
@@ -148,25 +251,29 @@ object NotesViews {
val head = LinearLayout(ui.context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
- addView(ui.heading(notes.title ?: L("纪要"), 19f).apply { maxLines = 2 }, ui.weight())
+ addView(ui.heading(notes.title ?: L("纪要"), Ui.Type.TITLE).apply { maxLines = 2; leading(1.3f) }, ui.weight())
val fresh = if (status == NotesEngine.State.Updating) L("正在整理纪要…") else updated(notes.updatedAt)
if (fresh != null) addView(ui.text(fresh, 12f, Palette.secondary), LinearLayout.LayoutParams(-2, -2).apply { leftMargin = ui.dp(8) })
}
body.addView(head)
- if (notes.summary.isNotEmpty()) body.addView(ui.text(notes.summary, 15f, Palette.body).apply { setLineSpacing(0f, 1.35f) }, ui.lp(top = 10))
+ if (notes.summary.isNotEmpty()) {
+ body.addView(ui.notesLabel(L("总结")), ui.lp(top = 16))
+ body.addView(ui.notesText(notes.summary), ui.lp(top = 6))
+ }
}
val topics = if (compact) notes.topics.takeLast(1) else notes.topics
topics.forEachIndexed { i, t ->
- body.addView(ui.row(10, ui.text(Languages.clock(t.start), 12f, Palette.link, bold = true), ui.text(t.title, 15f, Palette.ink, bold = true).apply { layoutParams = ui.weight() }),
- ui.lp(top = if (compact && i == 0) 0 else 18))
- for (p in if (compact) t.points.takeLast(3) else t.points) body.addView(bullet(ui, p, if (compact) 14f else 15f), ui.lp(top = 6))
+ body.addView(ui.row(10, ui.text(Languages.clock(t.start), 12f, Palette.link, bold = true).apply { fontFeatureSettings = "tnum" },
+ ui.text(t.title, if (compact) 15f else Ui.Type.BODY, Palette.ink, bold = true).apply { layoutParams = ui.weight() }),
+ ui.lp(top = if (compact && i == 0) 0 else 20))
+ for (p in if (compact) t.points.takeLast(3) else t.points) body.addView(bullet(ui, p, if (compact) 14f else Ui.Type.BODY), ui.lp(top = 6))
}
if (!compact && notes.conclusions.isNotEmpty()) {
- body.addView(ui.text(L("结论"), 13f, Palette.secondary, bold = true), ui.lp(top = 20))
- for (c in notes.conclusions) body.addView(bullet(ui, c.text, 15f), ui.lp(top = 6))
+ body.addView(ui.notesLabel(L("结论")), ui.lp(top = 22))
+ for (c in notes.conclusions) body.addView(bullet(ui, c.text, Ui.Type.BODY), ui.lp(top = 6))
}
if (!compact && notes.todos.isNotEmpty()) {
- body.addView(ui.text(L("待办"), 13f, Palette.secondary, bold = true), ui.lp(top = 20))
+ body.addView(ui.notesLabel(L("待办")), ui.lp(top = 22))
for (t in notes.todos) body.addView(todo(ui, t.text, t.owner), ui.lp(top = 8))
}
return body
@@ -174,13 +281,13 @@ object NotesViews {
fun bullet(ui: Ui, text: String, size: Float) = LinearLayout(ui.context).apply {
orientation = LinearLayout.HORIZONTAL
- addView(ui.dot(Palette.tertiary, 5), LinearLayout.LayoutParams(ui.dp(5), ui.dp(5)).apply { topMargin = ui.dp((size * 0.6).toInt()); rightMargin = ui.dp(10); leftMargin = ui.dp(2) })
- addView(ui.text(text, size, Palette.body).apply { setLineSpacing(0f, 1.3f) }, ui.weight())
+ addView(ui.dot(Palette.tertiary, 5), LinearLayout.LayoutParams(ui.dp(5), ui.dp(5)).apply { topMargin = ui.dp((size * 0.72).toInt()); rightMargin = ui.dp(10); leftMargin = ui.dp(2) })
+ addView(ui.text(text, size, Palette.ink).apply { leading(if (size >= Ui.Type.BODY) Ui.Type.LINE else 1.35f) }, ui.weight())
}
fun todo(ui: Ui, text: String, owner: String?) = LinearLayout(ui.context).apply {
orientation = LinearLayout.HORIZONTAL
- addView(View(ui.context).apply { background = ui.rounded(0, 4, Palette.outline, 2) }, LinearLayout.LayoutParams(ui.dp(16), ui.dp(16)).apply { topMargin = ui.dp(3); rightMargin = ui.dp(10) })
- addView(ui.text(text + (owner?.let { " · $it" } ?: ""), 15f, Palette.body), ui.weight())
+ addView(View(ui.context).apply { background = ui.rounded(0, 8, Palette.tertiary, 1.5) }, LinearLayout.LayoutParams(ui.dp(16), ui.dp(16)).apply { topMargin = ui.dp(5); rightMargin = ui.dp(10) })
+ addView(ui.notesText(text + (owner?.let { " · $it" } ?: "")), ui.weight())
}
}
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 ca4d507..24ff838 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/OnboardingActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/OnboardingActivity.kt
@@ -128,7 +128,7 @@ class OnboardingActivity : Activity() {
return root
}
- private fun intro(title: String, lead: String) = ui.stack(8, ui.title(title), ui.text(lead, 16f, Palette.body).apply { setLineSpacing(0f, 1.3f) })
+ private fun intro(title: String, lead: String) = ui.stack(8, ui.title(title), ui.text(lead, 16f, Palette.body).apply { leading(1.3f) })
private fun keyStep(): View {
val app = cicada
@@ -295,7 +295,7 @@ class OnboardingActivity : Activity() {
}
content.addView(notesCard, ui.lp(top = 12))
} else if (playing) {
- // Ming answers a stretch once it ends (~6 s in for the first): say it's coming.
+ // 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 02162f9..7b54096 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/Overlay.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Overlay.kt
@@ -33,11 +33,11 @@ class Overlay(private val app: CicadaApp) {
private var params: WindowManager.LayoutParams? = null
private var dismissTarget: View? = null
private var clockText: TextView? = null
- private var live: FrameLayout? = null
+ private var live: LinearLayout? = null
private var notes: FrameLayout? = null
private var shownKey: String? = null
private val tick = object : Runnable {
- override fun run() { if (root != null) { clockText?.text = NotesViews.clock(app); render(); app.main.postDelayed(this, 1000) } }
+ 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).
@@ -142,7 +142,7 @@ class Overlay(private val app: CicadaApp) {
card.addView(handle, LinearLayout.LayoutParams(-1, ui.dp(12)))
val head = header(dark = false)
card.addView(head)
- live = FrameLayout(app); notes = FrameLayout(app)
+ live = LinearLayout(app).apply { orientation = LinearLayout.VERTICAL }; notes = FrameLayout(app)
card.addView(live, LinearLayout.LayoutParams(-1, -2).apply { leftMargin = ui.dp(10); rightMargin = ui.dp(10) })
card.addView(notes, LinearLayout.LayoutParams(-1, -2).apply { leftMargin = ui.dp(16); rightMargin = ui.dp(16); topMargin = ui.dp(14) })
frame.addView(card)
@@ -157,7 +157,7 @@ class Overlay(private val app: CicadaApp) {
}
val head = header(dark = true)
bar.addView(head)
- live = FrameLayout(app); notes = null
+ live = LinearLayout(app).apply { orientation = LinearLayout.VERTICAL }; notes = null
bar.addView(live, LinearLayout.LayoutParams(-1, -2).apply { leftMargin = ui.dp(12); rightMargin = ui.dp(16) })
frame.addView(bar)
}
@@ -317,13 +317,16 @@ class Overlay(private val app: CicadaApp) {
box.removeAllViews()
val line = NotesViews.currentLines(app).lastOrNull()
val banner = NotesViews.banner(ui, app, null)
+ if (dark) NotesViews.endingBarText(app)?.let {
+ box.addView(ui.text(it, 13f, Palette.accentPale, bold = true).apply { tag = NotesViews.ENDING_BAR }, ui.lp().apply { bottomMargin = ui.dp(6) })
+ } else NotesViews.endingStrip(ui, app, compact = true)?.let { box.addView(it, ui.lp().apply { bottomMargin = ui.dp(8) }) }
when {
banner != null && line == null -> box.addView(if (dark) ui.text((banner as LinearLayout).let { (it.getChildAt(1) as TextView).text }, 15f, Color.WHITE) else banner)
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)
if (!line.dst.isNullOrEmpty() && line.dst != line.src) col.addView(ui.text(line.src, 13f, Palette.onScrim, lines = 2))
- col.addView(ui.text(line.dst ?: line.src, 20f, Color.WHITE, bold = true, lines = 3).apply { setLineSpacing(0f, 1.2f) })
+ col.addView(ui.text(line.dst ?: line.src, 20f, Color.WHITE, bold = true, lines = 3).apply { leading(1.2f) })
box.addView(col)
}
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)) })
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Recorder.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Recorder.kt
new file mode 100644
index 0000000..06601bf
--- /dev/null
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Recorder.kt
@@ -0,0 +1,106 @@
+package com.wquguru.cicada
+
+import android.media.MediaCodec
+import android.media.MediaCodecInfo
+import android.media.MediaFormat
+import android.media.MediaMuxer
+import cicada.Log
+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 } }
+ private var codec: MediaCodec? = null
+ private var muxer: MediaMuxer? = null
+ private var track = -1
+ private var samples = 0L
+ private var failed = false
+
+ init {
+ worker.execute {
+ try {
+ partial.parentFile?.mkdirs()
+ val format = MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_AAC, Segmenter.RATE, 1).apply {
+ setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC)
+ setInteger(MediaFormat.KEY_BIT_RATE, 32_000)
+ setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 16_384)
+ }
+ codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_AAC).apply { configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); start() }
+ muxer = MediaMuxer(partial.path, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)
+ } catch (e: Exception) { fail(e) }
+ }
+ }
+
+ 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)
+ val ok = !failed && try {
+ if (track >= 0) muxer?.stop()
+ muxer?.release(); codec?.stop(); codec?.release()
+ track >= 0 && partial.renameTo(target)
+ } catch (e: Exception) { fail(e); false }
+ if (!ok) partial.delete()
+ Log.d("recorder: ${if (ok) "saved ${target.length() / 1024} KB, ${samples / Segmenter.RATE} s" else "nothing saved"}")
+ done(ok)
+ }
+ worker.shutdown()
+ }
+
+ private fun feed(pcm: ShortArray, end: Boolean) {
+ val c = codec ?: return
+ try {
+ var off = 0
+ var queuedEnd = false
+ var tries = 0
+ do {
+ val i = c.dequeueInputBuffer(10_000)
+ if (i < 0 && ++tries > 300) throw IllegalStateException("encoder stalled")
+ if (i >= 0) {
+ val buf = c.getInputBuffer(i)!!
+ buf.clear()
+ val n = minOf(pcm.size - off, buf.remaining() / 2)
+ for (k in 0 until n) buf.putShort(pcm[off + k])
+ val us = samples * 1_000_000 / Segmenter.RATE
+ off += n; samples += n
+ val last = end && off >= pcm.size
+ c.queueInputBuffer(i, 0, n * 2, us, if (last) MediaCodec.BUFFER_FLAG_END_OF_STREAM else 0)
+ if (last) queuedEnd = true
+ }
+ drain(c, false)
+ } while (off < pcm.size || (end && !queuedEnd))
+ if (end) drain(c, true)
+ } catch (e: Exception) { fail(e) }
+ }
+
+ private fun drain(c: MediaCodec, untilEnd: Boolean) {
+ val info = MediaCodec.BufferInfo()
+ var waits = 0
+ while (waits < 300) {
+ if (untilEnd) waits++
+ val o = c.dequeueOutputBuffer(info, if (untilEnd) 10_000 else 0)
+ when {
+ o == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> { track = muxer!!.addTrack(c.outputFormat); muxer!!.start() }
+ o >= 0 -> {
+ val out = c.getOutputBuffer(o)!!
+ if (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG == 0 && info.size > 0 && track >= 0) muxer!!.writeSampleData(track, out, info)
+ c.releaseOutputBuffer(o, false)
+ if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) return
+ }
+ o == MediaCodec.INFO_TRY_AGAIN_LATER -> if (!untilEnd) return
+ }
+ }
+ }
+
+ private fun fail(e: Exception) {
+ if (!failed) Log.d("recorder: failed ${e.javaClass.simpleName}: ${e.message}")
+ failed = 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 9a76228..2f4b6bc 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt
@@ -1,7 +1,6 @@
package com.wquguru.cicada
import android.app.Activity
-import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.text.Editable
@@ -13,7 +12,6 @@ import android.widget.EditText
import android.widget.FrameLayout
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
-import android.widget.PopupMenu
import android.widget.TextView
import cicada.Languages
import cicada.Log
@@ -22,6 +20,9 @@ import cicada.Session
import cicada.SessionStore
import cicada.Strings.L
import cicada.Strings.LF
+import cicada.SpeakerLabels
+import cicada.Strings
+import cicada.TranscriptExport
/// 会议记录: every meeting, newest first, grouped by day; search covers titles, notes and what
/// was said; chips narrow to meetings with notes or to-dos.
@@ -56,6 +57,7 @@ class RecordsActivity : Activity() {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
background = ui.rounded(Palette.card, 26)
+ ui.lift(this, 1)
minimumHeight = ui.dp(52)
setPadding(ui.dp(16), 0, ui.dp(16), 0)
addView(ui.icon(R.drawable.i_search, 20, Palette.secondary))
@@ -65,7 +67,9 @@ class RecordsActivity : Activity() {
list = FrameLayout(this)
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, L("会议记录"), back = true, ground = Palette.ground, body = body))
+ 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) }
}
override fun onResume() { super.onResume(); unobserve = cicada.observe(::render); shown = null; render() }
@@ -110,7 +114,9 @@ class RecordsActivity : Activity() {
}
}
-/// One meeting: 纪要 (or a way to write them) and the bilingual 文字记录, on one white sheet.
+/// 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
@@ -119,61 +125,74 @@ class RecordActivity : Activity() {
private lateinit var list: android.widget.ListView
private lateinit var header: FrameLayout
private lateinit var footer: FrameLayout
+ private lateinit var playerHost: FrameLayout
private val adapter = LinesAdapter()
private var tab = 0
private var shown: String? = null
private var unobserve: (() -> Unit)? = null
+ private var player: android.media.MediaPlayer? = null
+ private var playButton: android.widget.ImageView? = null
+ private var playTime: TextView? = null
+ private var playBar: LinearLayout? = null
+ private var playing = -1 // the line being played, for the highlight
+ private val tickPlayer = object : Runnable {
+ override fun run() { updatePlayer(); if (player?.isPlaying == true) list.postDelayed(this, 250) }
+ }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ui = Ui(this)
id = intent.getStringExtra("id") ?: run { finish(); return }
tab = savedInstanceState?.getInt("tab") ?: 0
- header = FrameLayout(this); footer = FrameLayout(this)
+ header = FrameLayout(this); footer = FrameLayout(this); playerHost = FrameLayout(this)
list = android.widget.ListView(this).apply {
divider = null
selector = android.graphics.drawable.ColorDrawable(0)
isVerticalScrollBarEnabled = false
- setPadding(ui.dp(20), 0, ui.dp(20), ui.dp(40))
+ setPadding(0, 0, 0, ui.dp(40))
clipToPadding = false
addHeaderView(header, null, false)
addFooterView(footer, null, false)
+ setOnItemClickListener { _, _, pos, _ -> (pos - headerViewsCount).takeIf { it >= 0 }?.let { seekTo(it) } }
}
- lateinit var more: View
- more = ui.iconButton(R.drawable.i_more, L("更多"), Palette.ink) { menu(more) }
- setContentView(ui.screen(this, null, back = true, ground = Palette.card, body = list, scroll = false, actions = listOf(
- ui.iconButton(R.drawable.i_share, L("分享"), Palette.ink) { cicada.store.get(id)?.let(::share) }, more)))
+ setContentView(ui.screen(this, null, back = true, ground = Palette.card, body = list, scroll = false, bottom = playerHost.takeIf { audio().isFile }, actions = listOf(
+ 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() })))
+ if (audio().isFile) buildPlayer()
}
+ private fun audio() = cicada.store.audioFile(id)
+
override fun onResume() { super.onResume(); unobserve = cicada.observe(::render); shown = null; render() }
- override fun onPause() { super.onPause(); unobserve?.invoke(); unobserve = null }
+ override fun onPause() { super.onPause(); unobserve?.invoke(); unobserve = null; player?.pause(); updatePlayer() }
+ override fun onDestroy() { super.onDestroy(); player?.release(); player = null }
private fun render() {
val app = cicada
val s = app.store.get(id) ?: run { if (app.store.loaded) finish(); return }
val generating = app.notes.generating == id
- val key = listOf(SessionStore.displayTitle(s), s.lines.size, s.notes?.updatedAt, generating, app.notes.status, tab, s.lines.lastOrNull()?.dst).joinToString("|")
+ val key = listOf(SessionStore.displayTitle(s), s.lines.size, s.notes?.updatedAt, generating, app.notes.status, tab, s.lines.lastOrNull()?.dst,
+ s.voiceNames, app.settings.speakerVoices).joinToString("|")
if (key == shown) return
shown = key
- val top = ui.stack(0).apply { setPadding(0, ui.dp(4), 0, 0) }
- top.addView(ui.title(SessionStore.displayTitle(s), 24f))
- val meta = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
+ val top = ui.stack(0).apply { setPadding(ui.dp(20), ui.dp(4), ui.dp(20), ui.dp(6)) }
+ top.addView(ui.title(SessionStore.displayTitle(s), 28f).apply { leading(1.2f) })
val first = s.lines.firstOrNull()
- listOfNotNull("${MainActivity.day(s.startedAt)} ${MainActivity.time(s.startedAt)}", Languages.clock(s.durationSeconds),
- first?.let { "${NotesViews.languageName(it.srcLang)} → ${NotesViews.languageName(it.dstLang)}" })
- .forEachIndexed { i, t -> meta.addView(ui.badge(t, Palette.body, Palette.ground, size = 13f), LinearLayout.LayoutParams(-2, -2).apply { if (i > 0) leftMargin = ui.dp(6) }) }
- top.addView(HorizontalScrollView(this).apply { isHorizontalScrollBarEnabled = false; addView(meta) }, ui.lp(top = 12))
+ val meta = listOfNotNull("${MainActivity.day(s.startedAt)} ${MainActivity.time(s.startedAt)}", Languages.clock(s.durationSeconds),
+ first?.let { "${NotesViews.languageName(it.srcLang)} → ${NotesViews.languageName(it.dstLang)}" },
+ s.sourceFile?.let { L("导入") }).joinToString(" · ")
+ top.addView(ui.text(meta, 13f, Palette.secondary), ui.lp(top = 6))
+ speakerChips(s)?.let { top.addView(it, ui.lp(top = 14)) }
top.addView(ui.tabs(listOf(L("纪要"), "${L("文字记录")} · ${s.lines.size} ${L("句")}"), tab) { tab = it; render() }, ui.lp(top = 18))
- top.addView(ui.divider())
header.removeAllViews(); header.addView(top)
- val bottom = ui.stack(0)
+ val bottom = ui.stack(0).apply { setPadding(ui.dp(20), 0, ui.dp(20), 0) }
if (tab == 0) {
val n = s.notes
when {
n != null && !n.isEmpty ->
- bottom.addView(NotesViews.notesBody(ui, n, NotesEngine.State.Idle, false).apply { (getChildAt(0) as? LinearLayout)?.visibility = View.GONE }, ui.lp(top = 18))
+ bottom.addView(NotesViews.notesBody(ui, n, NotesEngine.State.Idle, false).apply { (getChildAt(0) as? LinearLayout)?.visibility = View.GONE }, ui.lp(top = 6))
generating -> bottom.addView(ui.text(L("正在整理纪要…"), 15f, Palette.secondary), ui.lp(top = 24))
else -> {
if (app.notes.status == NotesEngine.State.Failed) bottom.addView(ui.text(L("纪要没生成出来,稍后再试"), 15f, Palette.link), ui.lp(top = 24))
@@ -183,13 +202,48 @@ class RecordActivity : Activity() {
}
}
footer.removeAllViews(); footer.addView(bottom)
- adapter.show(if (tab == 1) app.store.lines(id) else emptyList())
+ val lines = if (tab == 1) app.store.lines(id) else emptyList()
+ adapter.show(lines, SpeakerLabels.numbers(lines), SpeakerLabels.names(s), s.sourceFile == null)
+ }
+
+ /// 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
+ val names = SpeakerLabels.names(s)
+ val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
+ numbers.values.toSortedSet().forEachIndexed { i, n ->
+ val (bg, fg) = NotesViews.voiceColor(n)
+ val label = SpeakerLabels.label(n, names)
+ row.addView(ui.text(label, 13f, fg, bold = true, lines = 1).apply {
+ gravity = android.view.Gravity.CENTER
+ minHeight = ui.dp(36)
+ setPadding(ui.dp(14), 0, ui.dp(14), 0)
+ contentDescription = label + "," + L("改名")
+ ui.tappable(this, 18, ui.rounded(bg, 18)) { nameVoice(s, n, label) }
+ }, LinearLayout.LayoutParams(-2, -2).apply { if (i > 0) leftMargin = ui.dp(8) })
+ }
+ return HorizontalScrollView(this).apply { isHorizontalScrollBarEnabled = false; addView(row) }
}
- /// One transcript line per row: time, what was said, its translation. Rows are reused.
+ /// 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("只改这场会议,前面的字幕和纪要一起改"),
+ hint = Strings.LF("说话人 %lld", number)) { name ->
+ cicada.store.setVoiceName(s.id, voice, name.ifEmpty { null })
+ }
+ }
+
+ /// 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()
- fun show(l: List<cicada.TranscriptLine>) { lines = l; notifyDataSetChanged() }
+ private var numbers: Map<String, Int> = emptyMap()
+ private var names: Map<Int, String> = emptyMap()
+ private var who = true
+ fun show(l: List<cicada.TranscriptLine>, n: Map<String, Int>, nm: Map<Int, String>, speakers: Boolean) {
+ lines = l; numbers = n; names = nm; who = speakers; notifyDataSetChanged()
+ }
override fun getCount() = lines.size
override fun getItem(i: Int) = lines[i]
override fun getItemId(i: Int) = i.toLong()
@@ -197,46 +251,146 @@ class RecordActivity : Activity() {
override fun getView(i: Int, convertView: View?, parent: android.view.ViewGroup?): View {
val row = convertView as? LinearLayout ?: LinearLayout(this@RecordActivity).apply {
orientation = LinearLayout.HORIZONTAL
- setPadding(0, ui.dp(18), 0, 0)
- addView(ui.text("", 12f, Palette.link, bold = true), LinearLayout.LayoutParams(-2, -2).apply { topMargin = ui.dp(2); rightMargin = ui.dp(12) })
- addView(ui.stack(3, ui.text("", 15f, Palette.ink).apply { setLineSpacing(0f, 1.3f) }, ui.text("", 14f, Palette.secondary).apply { setLineSpacing(0f, 1.3f) }), ui.weight())
+ setPadding(ui.dp(20), ui.dp(14), ui.dp(20), ui.dp(14))
+ addView(ui.text("", 12f, Palette.tertiary).apply { fontFeatureSettings = "tnum" }, LinearLayout.LayoutParams(ui.dp(44), -2).apply { topMargin = ui.dp(2) })
+ addView(ui.stack(3,
+ ui.text("", 12f, Palette.secondary, bold = true, lines = 1),
+ ui.text("", Ui.Type.ORIGINAL, Palette.secondary).apply { leading(1.45f) },
+ ui.text("", Ui.Type.BODY, Palette.ink).apply { leading(1.5f) }), ui.weight())
}
val l = lines[i]
- (row.getChildAt(0) as TextView).text = Languages.clock(l.t)
+ val now = i == playing
+ row.setBackgroundColor(if (now) 0x0FE8552B else 0)
+ (row.getChildAt(0) as TextView).apply { text = Languages.clock(l.t); setTextColor(if (now) Palette.link else Palette.tertiary) }
val texts = row.getChildAt(1) as LinearLayout
- (texts.getChildAt(0) as TextView).text = NotesViews.said(l)
- val dst = texts.getChildAt(1) as TextView
+ val name = SpeakerLabels.speakerName(l, numbers, names)
+ (texts.getChildAt(0) as TextView).apply {
+ text = name
+ visibility = if (who) View.VISIBLE else View.GONE
+ setTextColor(if (l.speaker == "me") Palette.ink else NotesViews.voiceColor(numbers[l.id]).second.takeIf { numbers[l.id] != null } ?: Palette.secondary)
+ }
val translated = !l.dst.isNullOrEmpty() && l.dst != l.src
- dst.visibility = if (translated) View.VISIBLE else View.GONE
- dst.text = l.dst ?: ""
+ (texts.getChildAt(1) as TextView).apply { text = l.src; visibility = if (translated) View.VISIBLE else View.GONE }
+ (texts.getChildAt(2) as TextView).text = if (translated) l.dst else l.src
return row
}
}
override fun onSaveInstanceState(out: Bundle) { super.onSaveInstanceState(out); out.putInt("tab", tab) }
- private fun menu(anchor: View) {
- val s = cicada.store.get(id) ?: return
- PopupMenu(this, anchor).apply {
- menu.add(0, 1, 0, L("重命名")); menu.add(0, 2, 1, L("导出 Markdown")); menu.add(0, 3, 2, L("删除"))
- setOnMenuItemClickListener { when (it.itemId) { 1 -> rename(s); 2 -> export(s); else -> delete(s) }; true }
- show()
+ // MARK: The recording (保存会议录音)
+
+ 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 {
+ contentDescription = L("播放原声")
+ addView(play, FrameLayout.LayoutParams(ui.dp(20), ui.dp(20), android.view.Gravity.CENTER))
+ ui.tappable(this, 24, ui.rounded(Palette.ink, 24), dark = true) { toggle() }
+ }
+ val bar = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL; background = ui.rounded(Palette.line, 2); weightSum = 1f
+ addView(View(context).apply { background = ui.rounded(Palette.accent, 2) }, LinearLayout.LayoutParams(0, -1, 0f)) }
+ val time = ui.text("00:00", 11f, Palette.secondary).apply { fontFeatureSettings = "tnum" }
+ val pill = 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(8), ui.dp(18), ui.dp(8))
+ addView(button, LinearLayout.LayoutParams(ui.dp(48), ui.dp(48)))
+ addView(ui.stack(6, bar.apply { layoutParams = LinearLayout.LayoutParams(-1, ui.dp(4)) }, time), ui.weight().apply { leftMargin = ui.dp(14) })
}
+ playButton = play; playTime = time; playBar = bar
+ playerHost.addView(LinearLayout(this).apply {
+ background = ui.fade(Palette.card)
+ setPadding(ui.dp(16), ui.dp(28), ui.dp(16), ui.dp(16))
+ addView(pill, LinearLayout.LayoutParams(-1, ui.dp(64)))
+ })
+ updatePlayer()
}
- /// The Markdown export through the share sheet (chat apps, notes apps, Files…).
+ private fun ensurePlayer(): android.media.MediaPlayer? {
+ player?.let { return it }
+ return try {
+ android.media.MediaPlayer().apply {
+ setDataSource(audio().path); prepare()
+ setOnCompletionListener { updatePlayer() }
+ }.also { player = it }
+ } catch (e: Exception) { Log.d("record: play failed ${e.javaClass.simpleName}"); null }
+ }
+
+ private fun toggle() {
+ val p = ensurePlayer() ?: return
+ if (p.isPlaying) p.pause() else { p.start(); list.post(tickPlayer) }
+ updatePlayer()
+ }
+
+ /// A tap on a line plays the recording from there.
+ private fun seekTo(index: Int) {
+ if (!audio().isFile) return
+ val l = adapter.getItem(index)
+ val p = ensurePlayer() ?: return
+ p.seekTo((l.t * 1000).toInt())
+ if (!p.isPlaying) { p.start(); list.post(tickPlayer) }
+ updatePlayer()
+ }
+
+ private fun updatePlayer() {
+ val p = player
+ val pos = (p?.currentPosition ?: 0) / 1000.0
+ val dur = (p?.duration ?: 0).takeIf { it > 0 }?.div(1000.0) ?: cicada.store.get(id)?.durationSeconds ?: 0.0
+ playButton?.setImageDrawable(ui.drawable(if (p?.isPlaying == true) R.drawable.i_pause else R.drawable.i_play, android.graphics.Color.WHITE))
+ playTime?.text = "${Languages.clock(pos)} / ${Languages.clock(dur)}"
+ playBar?.getChildAt(0)?.let { (it.layoutParams as LinearLayout.LayoutParams).weight = if (dur > 0) (pos / dur).toFloat().coerceIn(0f, 1f) else 0f; it.requestLayout() }
+ // The line being heard, highlighted.
+ val lines = (0 until adapter.count).map { adapter.getItem(it) }
+ val now = if (p?.isPlaying == true || pos > 0) lines.indexOfLast { it.t <= pos } else -1
+ if (now != playing) { playing = now; adapter.notifyDataSetChanged() }
+ }
+
+ // MARK: 更多: export and the rest
+
+ private fun more() {
+ 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() }
+ val box = ui.stack(0,
+ act(R.drawable.i_clipboard, L("复制为 Markdown")) { copy(s) },
+ act(R.drawable.i_doc, L("导出 Markdown…")) { export(s, "md") },
+ act(R.drawable.i_doc, L("导出 Word…")) { export(s, "docx") },
+ 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))
- .putExtra(Intent.EXTRA_TEXT, SessionStore.markdown(s))
+ .putExtra(Intent.EXTRA_TEXT, TranscriptExport.markdown(s))
startActivity(Intent.createChooser(send, L("分享")))
}
- /// Saves the Markdown as a file where the user picks (the system file picker).
- private fun export(s: Session) {
- val name = SessionStore.displayTitle(s).replace(Regex("[\\\\/:*?\"<>|]"), "-") + ".md"
+ 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" }
@Suppress("DEPRECATION")
- startActivityForResult(Intent(Intent.ACTION_CREATE_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("text/markdown").putExtra(Intent.EXTRA_TITLE, name), 7)
+ startActivityForResult(Intent(Intent.ACTION_CREATE_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType(type).putExtra(Intent.EXTRA_TITLE, TranscriptExport.fileName(s, kind)), 7)
}
@Deprecated("Deprecated in Java")
@@ -244,23 +398,19 @@ class RecordActivity : Activity() {
val uri = data?.data ?: return
val s = cicada.store.get(id) ?: return
if (requestCode == 7 && resultCode == RESULT_OK) {
- try { contentResolver.openOutputStream(uri)?.use { it.write(SessionStore.markdown(s).toByteArray()) } }
+ val bytes = when (exportKind) { "docx" -> TranscriptExport.docx(s); "srt" -> TranscriptExport.srt(s).toByteArray(); else -> TranscriptExport.markdown(s).toByteArray() }
+ try { contentResolver.openOutputStream(uri)?.use { it.write(bytes) }; Log.d("export: $exportKind ${bytes.size} bytes") }
catch (e: Exception) { Log.d("export failed ${e.javaClass.simpleName}") }
}
}
private fun rename(s: Session) {
- val box = EditText(this).apply { setText(MainActivity.name(s)); setSelectAllOnFocus(true); setSingleLine() }
- val frame = FrameLayout(this).apply { setPadding(ui.dp(24), ui.dp(8), ui.dp(24), 0); addView(box) }
- AlertDialog.Builder(this).setTitle(L("重命名")).setView(frame)
- .setPositiveButton(L("保存")) { _, _ -> if (box.text.toString().isNotBlank()) cicada.store.rename(s.id, box.text.toString()) }
- .setNegativeButton(L("取消"), null).show()
- box.requestFocus()
+ 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) }
}
private fun delete(s: Session) {
- AlertDialog.Builder(this).setMessage(LF("删除“%@”?删掉后不能恢复", SessionStore.displayTitle(s)))
- .setPositiveButton(L("删除")) { _, _ -> cicada.store.delete(s.id); finish() }
- .setNegativeButton(L("取消"), null).show()
+ ui.confirm(this, L("删除"), LF("删除“%@”?删掉后不能恢复", SessionStore.displayTitle(s)), ok = L("删除"), destructive = true) { cicada.store.delete(s.id); finish() }
}
}
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 3a04a19..005ae92 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt
@@ -1,7 +1,6 @@
package com.wquguru.cicada
import android.app.Activity
-import android.app.AlertDialog
import android.content.ClipboardManager
import android.content.Intent
import android.content.res.ColorStateList
@@ -19,8 +18,9 @@ import cicada.Log
import cicada.Strings
import cicada.Strings.L
-/// 设置: grouped list rows (56dp), each a value that opens its choices, or a switch whose effect is
-/// said under it.
+/// 设置, 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
@@ -30,11 +30,15 @@ class SettingsActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ui = Ui(this)
- page = ui.stack(8).apply { setPadding(ui.dp(16), ui.dp(4), ui.dp(16), ui.dp(32)) }
- setContentView(ui.screen(this, L("设置"), back = true, ground = Palette.ground, body = page))
+ page = ui.stack(0).apply { setPadding(ui.dp(16), ui.dp(4), ui.dp(16), ui.dp(24)) }
+ builtTitle = L("设置")
+ setContentView(ui.screen(this, builtTitle, back = false, ground = Palette.ground, body = page, bottom = ui.nav(this, "settings")))
}
- override fun onResume() { super.onResume(); unobserve = cicada.observe(::build); shown = null; build() }
+ 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() }
override fun onPause() { super.onPause(); unobserve?.invoke(); unobserve = null }
private fun value(text: String) = ui.text(text, 15f, Palette.secondary, lines = 1)
@@ -47,7 +51,7 @@ class SettingsActivity : Activity() {
shown = key
page.removeAllViews()
- page.addView(ui.sectionLabel("Ling"))
+ page.addView(ui.sectionLabel(L("AI 服务")))
val k = app.key.read()
val keyStatus = when (app.ling.keyState) {
KeyState.None -> L("还没填 API key")
@@ -57,7 +61,8 @@ class SettingsActivity : Activity() {
KeyState.Ok -> AIKey.masked(k ?: "") + " · " + L("正常")
else -> AIKey.masked(k ?: "")
}
- page.addView(ui.group(listOf(ui.listRow(L("Ling key"), keyStatus, leading = ui.icon(R.drawable.i_lock, 22, Palette.body)) { editKey() })))
+ page.addView(ui.group(listOf(ui.listRow(L("Ling key"), keyStatus, leading = ui.icon(R.drawable.i_lock, 22, Palette.body)) { editKey() },
+ choiceRow(L("纪要和翻译模型"), listOf("Ling-3.1-flash" to "Ling-3.1-flash", "Ling-3.0-flash" to "Ling-3.0-flash"), s.model) { s.model = it; app.saveSettings() })))
page.addView(ui.sectionLabel(L("语言")))
val targets = listOf("system" to L("跟随系统")) + Languages.targets.map { it.code to it.name }
@@ -68,6 +73,19 @@ class SettingsActivity : Activity() {
s.uiLanguage = it; app.saveSettings(); app.loadStrings(); shown = null; recreate()
})))
+ // 听对方: the Mac's listening switches. Android doesn't tell voices apart itself yet (no
+ // voiceprint runtime in the framework), so 说话人识别 numbers the voices of records made
+ // on the Mac or Windows; the helper says so.
+ page.addView(ui.sectionLabel(L("听对方")))
+ page.addView(ui.group(listOf(
+ switchRow(L("说话人识别"), L("显示 Mac 和 Windows 上分出的说话人;这台手机还不能按声音分人"), s.speakerVoices) { s.speakerVoices = it; app.saveSettings() },
+ switchRow(L("保存会议录音"), L("只存在这台手机上,会议记录里能回放原声"), s.recordAudio) { s.recordAudio = it; app.saveSettings() })))
+
+ page.addView(ui.sectionLabel(L("我说 · 面对面")))
+ page.addView(ui.group(listOf(
+ switchRow(L("把我说的翻译给对方"), L("按住说话,松开后用对方的语言读出来"), s.speakBack) { s.speakBack = it; app.saveSettings() },
+ ui.listRow(L("试一句"), L("用手机的声音读一句英语"), trailing = ui.icon(R.drawable.i_play, 20, Palette.ink), chevron = false) { tryVoice() })))
+
page.addView(ui.sectionLabel(L("在其他应用上")))
val rows = mutableListOf<View>(
switchRow(L("悬浮窗"), L("切到其他应用时,在上面显示字幕或纪要"), s.overlay) { s.overlay = it; app.saveSettings(); if (!it) app.overlay.hide() },
@@ -78,14 +96,23 @@ 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,
+ helper = L("按识别出的话算,背景音乐不算")) { s.silenceEnd = it; app.saveSettings() })
+ if (s.silenceEnd != "off") endRows.add(choiceRow(L("多久算没人说话"), listOf(5, 10, 15, 30).map { "$it" to Strings.LF("%lld 分钟", it) },
+ "${s.silenceMinutes.toInt()}") { s.silenceMinutes = it.toDouble(); app.saveSettings() })
+ page.addView(ui.group(endRows))
+
page.addView(ui.sectionLabel(L("其他")))
page.addView(ui.group(listOf(
- choiceRow(L("纪要和翻译模型"), listOf("Ling-3.1-flash" to "Ling-3.1-flash", "Ling-3.0-flash" to "Ling-3.0-flash"), s.model) { s.model = it; app.saveSettings() },
+ 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()))
val version = packageManager.getPackageInfo(packageName, 0).versionName
- page.addView(ui.helper("${L("知了")} $version · Android").apply { gravity = Gravity.CENTER; setPadding(0, ui.dp(12), 0, 0) })
+ page.addView(ui.helper("${L("知了")} $version · Android").apply { gravity = Gravity.CENTER; setPadding(0, ui.dp(20), 0, 0) })
}
private fun addTile() {
@@ -98,12 +125,9 @@ 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, changed: (String) -> Unit) =
- ui.listRow(label, trailing = value(options.firstOrNull { it.first == selected }?.second ?: selected)) {
- AlertDialog.Builder(this).setTitle(label)
- .setSingleChoiceItems(options.map { it.second }.toTypedArray(), options.indexOfFirst { it.first == selected }) { d, i ->
- d.dismiss(); changed(options[i].first); shown = null; build()
- }.setNegativeButton(L("取消"), null).show()
+ 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 row with a switch; the whole row toggles it.
@@ -134,20 +158,26 @@ class SettingsActivity : Activity() {
return row
}
- /// Change or remove the key: a dialog with the field, 粘贴, and 删除 Ling key.
+ /// A sample of how my words will sound to them (the Mac's 试一句), in English.
+ private fun tryVoice() {
+ val r = cicada.voice.speak("Could you send the revised quote by Friday? We can sign next week.", "en", onStart = {}, onEnd = {})
+ if (r != Voice.Result.Spoken) android.widget.Toast.makeText(this, if (r == Voice.Result.NoVoice) L("手机不会读这个语言") else L("没能读出来"), android.widget.Toast.LENGTH_SHORT).show()
+ }
+
+ /// Change or remove the key: a sheet with the field, 粘贴, and 删除 Ling key.
private fun editKey() {
val app = cicada
val status = ui.helper("")
- lateinit var dialog: AlertDialog
+ lateinit var dialog: android.app.Dialog
lateinit var submit: () -> Unit
val box = ui.keyField { submit() }
val field = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
- background = ui.rounded(Palette.card, 14, Palette.outline, 2)
- setPadding(ui.dp(14), ui.dp(4), ui.dp(4), ui.dp(4))
+ background = ui.rounded(Palette.ground, 16)
+ setPadding(ui.dp(16), ui.dp(4), ui.dp(4), ui.dp(4))
addView(box, ui.weight())
- addView(ui.button(L("粘贴"), "quiet", R.drawable.i_clipboard, height = 44) { paste(box) })
+ addView(ui.button(L("粘贴"), "white", R.drawable.i_clipboard, height = 44) { paste(box) })
}
submit = submit@{
val text = box.text.toString().trim()
@@ -157,13 +187,15 @@ class SettingsActivity : Activity() {
app.background.execute { app.ling.check() }
dialog.dismiss()
}
- val body = ui.stack(10, field, status).apply { setPadding(ui.dp(24), ui.dp(8), ui.dp(24), 0) }
- dialog = AlertDialog.Builder(this).setTitle(L("更换 Ling key")).setView(body)
- .setPositiveButton(L("保存"), null)
- .setNegativeButton(L("取消"), null)
- .setNeutralButton(L("删除 Ling key")) { _, _ -> app.key.remove(); app.ling.keyChanged() }
- .create()
- dialog.setOnShowListener { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { submit() } }
+ val body = ui.stack(10, field, status,
+ LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL
+ addView(ui.button(L("取消"), "quiet") { dialog.dismiss() }, ui.weight())
+ addView(ui.button(L("保存"), "primary") { submit() }, ui.weight().apply { leftMargin = ui.dp(10) })
+ },
+ ui.textButton(L("删除 Ling key"), Palette.link) { app.key.remove(); app.ling.keyChanged(); dialog.dismiss() })
+ dialog = ui.sheet(this, L("更换 Ling key"), body)
+ dialog.window?.setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE or android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
dialog.show()
box.requestFocus()
}
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 9436ab6..bfb3bdd 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/Ui.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Ui.kt
@@ -41,6 +41,11 @@ 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) {
@@ -56,13 +61,28 @@ class Ui(val context: Context) {
else -> Typeface.DEFAULT
}
if (lines > 0) { maxLines = lines; ellipsize = TextUtils.TruncateAt.END }
- setLineSpacing(0f, 1.2f)
+ leading(1.4f)
}
- fun title(text: String, size: Float = 28f) = text(text, size, Palette.ink, bold = true).apply { setLineSpacing(0f, 1.1f); isAccessibilityHeading = true }
+ 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)
- fun sectionLabel(text: String) = text(text, 13f, Palette.secondary, bold = true).apply { setPadding(dp(4), dp(12), 0, dp(2)); isAccessibilityHeading = true }
+ /// 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
+ const val LINE = 1.6f
+ const val LABEL = 13f
+ const val ORIGINAL = 14f
+ const val TRANSLATION = 17f
+ }
+ fun notesLabel(text: String) = text(text, Type.LABEL, Palette.secondary, medium = true).apply { isAccessibilityHeading = true }
+ fun notesText(text: CharSequence, color: Int = Palette.ink) = text(text, Type.BODY, color).apply { leading(Type.LINE) }
fun rounded(color: Int, radius: Number, stroke: Int? = null, strokeDp: Number = 1) = GradientDrawable().apply {
setColor(color); cornerRadius = dp(radius).toFloat()
@@ -82,13 +102,13 @@ class Ui(val context: Context) {
setOnClickListener { onClick() }
}
- fun card(vararg children: View, padding: Int = 20, gap: Int = 14, radius: Int = 24) = stack(gap, *children).apply {
+ fun card(vararg children: View, padding: Int = 20, gap: Int = 14, radius: Int = 28) = stack(gap, *children).apply {
background = rounded(Palette.card, radius)
setPadding(dp(padding), dp(padding), dp(padding), dp(padding))
}
/// A white group of rows with thin dividers (lists, settings).
- fun group(rows: List<View>, radius: Int = 20) = LinearLayout(context).apply {
+ fun group(rows: List<View>, radius: Int = 22) = LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
background = rounded(Palette.card, radius)
clipToOutline = true
@@ -144,11 +164,13 @@ class Ui(val context: Context) {
tappable(this, 24, dark = dark, onClick = onClick)
}
- /// Main buttons: ink (primary), a quiet grey one, or the pale accent (tonal).
+ /// 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
"tonal" -> Palette.accentPale to Palette.link
+ "white" -> Palette.card to Palette.ink
else -> Palette.ground to Palette.ink
}
return LinearLayout(context).apply {
@@ -160,10 +182,31 @@ class Ui(val context: Context) {
addView(text(label, if (height >= 56) 17f else 15f, fg, bold = true, lines = 2).apply { gravity = Gravity.CENTER })
setPadding(dp(16), dp(6), dp(16), dp(6))
contentDescription = label
- tappable(this, 16, rounded(bg, 16), dark = kind == "primary", onClick = onClick)
+ tappable(this, height / 2, rounded(bg, height / 2), dark = kind == "primary", onClick = onClick)
+ if (kind == "white") lift(this)
}
}
+ /// 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 {
+ setImageDrawable(drawable(res, Palette.ink))
+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
+ }, FrameLayout.LayoutParams(dp(20), dp(20), Gravity.CENTER))
+ layoutParams = LinearLayout.LayoutParams(dp(48), dp(48))
+ tappable(this, 24, rounded(if (onWhite) Palette.ground else Palette.card, 24), onClick = onClick)
+ 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
@@ -218,21 +261,19 @@ class Ui(val context: Context) {
if (onClick != null) tappable(this, 0, onClick = onClick)
}
- /// Material segmented button: choices in one outlined pill; the chosen one filled and checked.
- fun segmented(options: List<Pair<String, String>>, selected: String, onPick: (String) -> Unit) = LinearLayout(context).apply {
+ /// 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(Color.TRANSPARENT, 24, Palette.outline)
- clipToOutline = true
- options.forEachIndexed { i, (value, label) ->
- if (i > 0) addView(View(context).apply { setBackgroundColor(Palette.outline) }, LinearLayout.LayoutParams(dp(1), ViewGroup.LayoutParams.MATCH_PARENT))
+ background = rounded(track, 24)
+ setPadding(dp(4), dp(4), dp(4), dp(4))
+ options.forEach { (value, label) ->
val on = value == selected
- val seg = LinearLayout(context).apply {
- orientation = LinearLayout.HORIZONTAL
+ val fg = if (on && ink) Color.WHITE else if (on) Palette.ink else Palette.secondary
+ val seg = text(label, 15f, fg, bold = on, medium = !on, lines = 1).apply {
gravity = Gravity.CENTER
- if (on) addView(icon(R.drawable.i_check, 18, Palette.ink), LinearLayout.LayoutParams(dp(18), dp(18)).apply { rightMargin = dp(6) })
- addView(text(label, 15f, Palette.ink, bold = on, medium = !on, lines = 2).apply { gravity = Gravity.CENTER })
- minimumHeight = dp(48)
- setPadding(dp(8), dp(6), dp(8), dp(6))
+ minHeight = dp(40)
+ setPadding(dp(8), 0, dp(8), 0)
contentDescription = label
accessibilityDelegate = object : View.AccessibilityDelegate() {
override fun onInitializeAccessibilityNodeInfo(host: View, info: android.view.accessibility.AccessibilityNodeInfo) {
@@ -240,39 +281,26 @@ class Ui(val context: Context) {
info.isCheckable = true; info.isChecked = on; info.className = "android.widget.RadioButton"
}
}
- tappable(this, 0, if (on) ColorDrawable(Palette.selected) else null) { onPick(value) }
+ tappable(this, 20, if (on) rounded(if (ink) Palette.ink else Palette.card, 20) else null, dark = on && ink) { if (!on) onPick(value) }
+ if (on && !ink) lift(this, 1)
}
- addView(seg, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f))
+ addView(seg, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f))
}
+ clipToPadding = false; clipChildren = false
}
- /// A filter chip: outlined, or filled ink when on.
+ /// 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)
- setPadding(dp(14), 0, dp(14), 0)
+ setPadding(dp(16), 0, dp(16), 0)
isSelected = on
- tappable(this, 10, rounded(if (on) Palette.ink else Palette.card, 10, if (on) Palette.ink else Palette.outline), dark = on, onClick = onClick)
+ tappable(this, 20, rounded(if (on) Palette.ink else Palette.card, 20), dark = on, onClick = onClick)
}
- /// Tabs with an ink underline on the chosen one.
- fun tabs(labels: List<String>, selected: Int, onPick: (Int) -> Unit) = LinearLayout(context).apply {
- orientation = LinearLayout.HORIZONTAL
- labels.forEachIndexed { i, l ->
- val on = i == selected
- val tab = FrameLayout(context).apply {
- addView(text(l, 15f, if (on) Palette.ink else Palette.secondary, bold = on, medium = !on, lines = 1).apply { setPadding(0, dp(12), 0, dp(14)) },
- FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER))
- addView(View(context).apply { background = rounded(if (on) Palette.ink else Color.TRANSPARENT, 2) },
- FrameLayout.LayoutParams(dp(64), dp(3), Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL))
- isSelected = on
- contentDescription = l
- tappable(this, 0) { onPick(i) }
- }
- tab.minimumHeight = dp(48)
- addView(tab, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f))
- }
- }
+ /// 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 {
@@ -299,45 +327,100 @@ class Ui(val context: Context) {
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(1))
}
- /// An Activity's frame: top bar (back arrow when `back`, title, actions), a body that scrolls,
- /// an optional bottom bar pinned above the gesture area. Edge-to-edge via fitsSystemWindows.
+ /// 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): LinearLayout {
+ bottom: View? = null, scroll: Boolean = true, body: View, center: View? = null): FrameLayout {
activity.window.statusBarColor = ground
- activity.window.navigationBarColor = if (bottom != null) Palette.card else ground
- val root = LinearLayout(context).apply {
- orientation = LinearLayout.VERTICAL
+ activity.window.navigationBarColor = ground
+ val root = FrameLayout(context).apply {
setBackgroundColor(ground)
fitsSystemWindows = true
}
+ val column = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL }
+ val side = sideInset()
val bar = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
minimumHeight = dp(64)
- setPadding(dp(if (back) 4 else 20), 0, dp(4), 0)
- if (back) addView(iconButton(R.drawable.i_back, cicada.Strings.L("返回")) { activity.finish() })
+ setPadding(dp(16) + side, dp(8), dp(16) + side, 0)
+ if (back) addView(roundButton(R.drawable.i_back, cicada.Strings.L("返回"), onWhite = ground == Palette.card) { activity.finish() })
when {
center != null -> addView(FrameLayout(context).apply { addView(center, FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER)) }, weight())
- title != null -> addView(text(title, if (back) 22f else 26f, Palette.ink, bold = true, lines = 1).apply { isAccessibilityHeading = true },
- weight().apply { leftMargin = dp(if (back) 4 else 0) })
+ title != null && !back -> addView(text(title, 34f, Palette.ink, bold = true, lines = 1).apply { isAccessibilityHeading = true; setPadding(dp(4), 0, 0, 0) }, weight())
else -> addView(spacer())
}
- actions.forEach { addView(it) }
+ actions.forEachIndexed { i, a -> addView(a, LinearLayout.LayoutParams(a.layoutParams?.width ?: -2, a.layoutParams?.height ?: -2).apply { if (i > 0) leftMargin = dp(10) }) }
if (back && center != null && actions.isEmpty()) addView(View(context), LinearLayout.LayoutParams(dp(48), dp(48)))
}
- root.addView(bar)
- val content = if (scroll) ScrollView(context).apply { isVerticalScrollBarEnabled = false; addView(readable(body)) } else readable(body)
- root.addView(content, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f))
+ column.addView(bar)
+ if (back && title != null) column.addView(text(title, 30f, Palette.ink, bold = true, lines = 2).apply {
+ isAccessibilityHeading = true; setPadding(dp(20) + side, dp(12), dp(20) + side, dp(4))
+ })
+ 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
+ }
+ column.addView(content, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f))
+ root.addView(column, FrameLayout.LayoutParams(-1, -1))
if (bottom != null) {
- val side = sideInset()
if (side > 0) bottom.setPadding(bottom.paddingLeft + side, bottom.paddingTop, bottom.paddingRight + side, bottom.paddingBottom)
- root.addView(bottom)
+ root.addView(bottom, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM))
}
- val side = sideInset()
- if (side > 0) bar.setPadding(bar.paddingLeft + side, 0, bar.paddingRight + side, 0)
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
+ setPadding(dp(16), dp(28), dp(16), dp(16))
+ background = fade()
+ val pill = LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ background = rounded(Palette.card, 32)
+ setPadding(dp(6), dp(6), dp(6), dp(6))
+ lift(this, 4)
+ listOf(Triple("records", R.drawable.i_list, cicada.Strings.L("会议记录")), Triple("settings", R.drawable.i_settings, cicada.Strings.L("设置"))).forEach { (id, res, label) ->
+ val on = id == current
+ val item = LinearLayout(context).apply {
+ orientation = LinearLayout.VERTICAL
+ gravity = Gravity.CENTER
+ minimumHeight = dp(52)
+ contentDescription = label
+ isSelected = on
+ addView(icon(res, 22, if (on) Palette.ink else Palette.secondary), LinearLayout.LayoutParams(dp(22), dp(22)))
+ addView(text(label, 11f, if (on) Palette.ink else Palette.secondary, bold = on, lines = 1), LinearLayout.LayoutParams(-2, -2).apply { topMargin = dp(2) })
+ tappable(this, 26, if (on) rounded(Palette.ground, 26) else null) {
+ if (on) return@tappable
+ val target = if (id == "settings") SettingsActivity::class.java else MainActivity::class.java
+ activity.startActivity(android.content.Intent(activity, target).addFlags(android.content.Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
+ @Suppress("DEPRECATION") activity.overridePendingTransition(0, 0)
+ }
+ }
+ addView(item, LinearLayout.LayoutParams(0, -2, 1f).apply { if (id != "records") leftMargin = dp(4) })
+ }
+ }
+ addView(pill, LinearLayout.LayoutParams(0, dp(64), 1f))
+ val search = FrameLayout(context).apply {
+ contentDescription = cicada.Strings.L("搜索会议、人名、词语")
+ addView(icon(R.drawable.i_search, 22, Palette.ink), FrameLayout.LayoutParams(dp(22), dp(22), Gravity.CENTER))
+ tappable(this, 32, rounded(Palette.card, 32)) { activity.startActivity(android.content.Intent(activity, RecordsActivity::class.java)) }
+ lift(this, 4)
+ }
+ 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
@@ -353,12 +436,123 @@ class Ui(val context: Context) {
}
}
- /// The pinned bottom area: white, rounded top, one or two main buttons side by side.
- fun bottomBar(vararg buttons: View) = LinearLayout(context).apply {
+ /// 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 = GradientDrawable().apply { setColor(Palette.card); cornerRadii = floatArrayOf(dp(24).toFloat(), dp(24).toFloat(), dp(24).toFloat(), dp(24).toFloat(), 0f, 0f, 0f, 0f) }
- elevation = dp(8).toFloat()
- setPadding(dp(16), dp(14), dp(16), dp(14))
+ background = fade(ground)
+ clipToPadding = false; clipChildren = false
+ setPadding(dp(16), dp(28), dp(16), dp(16))
buttons.forEachIndexed { i, b -> addView(b, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f).apply { if (i > 0) leftMargin = dp(12) }) }
}
+
+ // 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)
+ val box = LinearLayout(activity).apply {
+ orientation = LinearLayout.VERTICAL
+ background = rounded(Palette.card, 32)
+ setPadding(dp(16), dp(10), dp(16), dp(20))
+ addView(View(activity).apply { background = rounded(Color.parseColor("#D5D7DC"), 3) }, LinearLayout.LayoutParams(dp(36), dp(5)).apply { gravity = Gravity.CENTER_HORIZONTAL; bottomMargin = dp(12) })
+ if (title != null) addView(text(title, 17f, Palette.ink, bold = true).apply { gravity = Gravity.CENTER; isAccessibilityHeading = true; setPadding(dp(8), 0, dp(8), dp(10)) })
+ addView(content)
+ }
+ val frame = FrameLayout(activity).apply { setPadding(dp(8), 0, dp(8), dp(8)); addView(box) }
+ d.setContentView(frame)
+ d.window?.apply {
+ setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
+ setGravity(Gravity.BOTTOM)
+ setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
+ setDimAmount(0.38f)
+ val w = context.resources.configuration.screenWidthDp
+ if (w > 600) setLayout(dp(560), ViewGroup.LayoutParams.WRAP_CONTENT)
+ }
+ 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
+ minimumHeight = dp(56)
+ setPadding(dp(8), dp(6), dp(8), dp(6))
+ val red = Color.parseColor("#B3261E")
+ addView(FrameLayout(context).apply {
+ background = rounded(if (destructive) Color.parseColor("#FBEAE8") else Palette.ground, 20)
+ addView(icon(res, 20, if (destructive) red else Palette.ink), FrameLayout.LayoutParams(dp(20), dp(20), Gravity.CENTER))
+ }, LinearLayout.LayoutParams(dp(40), dp(40)))
+ addView(stack(2, text(label, 16f, if (destructive) red else Palette.ink, lines = 1)).apply { if (helper != null) addView(text(helper, 13f, Palette.secondary)) },
+ weight().apply { leftMargin = dp(14) })
+ contentDescription = listOfNotNull(label, helper).joinToString(",")
+ 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
+ options.forEach { (value, label) ->
+ val on = value == selected
+ list.addView(LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ minimumHeight = dp(52)
+ setPadding(dp(16), 0, dp(12), 0)
+ addView(text(label, 16f, Palette.ink, bold = on, lines = 1), weight())
+ if (on) addView(icon(R.drawable.i_check, 20, Palette.ink), LinearLayout.LayoutParams(dp(20), dp(20)))
+ contentDescription = label
+ isSelected = on
+ tappable(this, 16, if (on) rounded(Palette.ground, 16) else null) { d.dismiss(); if (!on) onPick(value) }
+ })
+ }
+ val body: View = if (options.size > 8) ScrollView(context).apply { addView(list); layoutParams = LinearLayout.LayoutParams(-1, dp(52 * 8)) } else list
+ d = sheet(activity, title, body)
+ 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
+ val body = stack(0)
+ if (message != null) body.addView(text(message, 15f, Palette.secondary).apply { gravity = Gravity.CENTER; setPadding(dp(12), 0, dp(12), 0) })
+ val okButton = button(ok, "primary") { d.dismiss(); onOk() }
+ if (destructive) okButton.background = ripple(rounded(Color.parseColor("#B3261E"), 28), 28, dark = true)
+ body.addView(LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ addView(button(cancel, "quiet") { d.dismiss() }, weight())
+ addView(okButton, weight().apply { leftMargin = dp(10) })
+ }, lp(top = 18))
+ d = sheet(activity, title, body)
+ d.show()
+ }
+
+ /// A text to type (rename): the field, 取消 and 保存. The keyboard comes up with the sheet.
+ fun input(activity: Activity, title: String, initial: String, helper: String? = null, hint: String? = null, onSave: (String) -> Unit) {
+ lateinit var d: android.app.Dialog
+ val box = android.widget.EditText(activity).apply {
+ setText(initial); setSelectAllOnFocus(true); setSingleLine()
+ this.hint = hint
+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
+ background = rounded(Palette.ground, 16)
+ setPadding(dp(16), 0, dp(16), 0)
+ minHeight = dp(52)
+ imeOptions = android.view.inputmethod.EditorInfo.IME_ACTION_DONE
+ setOnEditorActionListener { _, a, _ -> if (a == android.view.inputmethod.EditorInfo.IME_ACTION_DONE) { d.dismiss(); onSave(text.toString().trim()); true } else false }
+ }
+ val body = stack(0, box)
+ if (helper != null) body.addView(helper(helper).apply { setPadding(dp(4), 0, dp(4), 0) }, lp(top = 8))
+ body.addView(LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ addView(button(cicada.Strings.L("取消"), "quiet") { d.dismiss() }, weight())
+ addView(button(cicada.Strings.L("保存"), "primary") { d.dismiss(); onSave(box.text.toString().trim()) }, weight().apply { leftMargin = dp(10) })
+ }, lp(top = 16))
+ d = sheet(activity, title, body)
+ d.window?.setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE or android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
+ d.show()
+ box.requestFocus()
+ }
}
diff --git a/android/app/src/main/res/drawable/i_doc.xml b/android/app/src/main/res/drawable/i_doc.xml
new file mode 100644
index 0000000..239661c
--- /dev/null
+++ b/android/app/src/main/res/drawable/i_doc.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generated icon (Lucide-style stroke, ISC): tinted in code. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M14 3v5h5"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M9 13h6"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M9 17h4"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/i_edit.xml b/android/app/src/main/res/drawable/i_edit.xml
new file mode 100644
index 0000000..e32fd9e
--- /dev/null
+++ b/android/app/src/main/res/drawable/i_edit.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generated icon (Lucide-style stroke, ISC): tinted in code. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M4 20h4l10.5-10.5a2.1 2.1 0 0 0-4-4L4 16z"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M13.5 6.5l4 4"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/i_flip.xml b/android/app/src/main/res/drawable/i_flip.xml
new file mode 100644
index 0000000..d7f3793
--- /dev/null
+++ b/android/app/src/main/res/drawable/i_flip.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generated icon (Lucide-style stroke, ISC): tinted in code. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M7 4v16"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M3 8l4-4l4 4"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M17 20V4"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M21 16l-4 4l-4-4"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/i_import.xml b/android/app/src/main/res/drawable/i_import.xml
new file mode 100644
index 0000000..82e26b6
--- /dev/null
+++ b/android/app/src/main/res/drawable/i_import.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generated icon (Lucide-style stroke, ISC): tinted in code. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M12 4v11"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M7 10l5 5l5-5"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M5 20h14"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/i_pause.xml b/android/app/src/main/res/drawable/i_pause.xml
new file mode 100644
index 0000000..7c8b365
--- /dev/null
+++ b/android/app/src/main/res/drawable/i_pause.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generated icon (Lucide-style stroke, ISC): tinted in code. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M7 5v14"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M17 5v14"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/i_people.xml b/android/app/src/main/res/drawable/i_people.xml
new file mode 100644
index 0000000..9725042
--- /dev/null
+++ b/android/app/src/main/res/drawable/i_people.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generated icon (Lucide-style stroke, ISC): tinted in code. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M9 5a3.2 3.2 0 1 0 0 6.4a3.2 3.2 0 1 0 0-6.4z"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M3.5 19c0.6-3.2 2.8-5 5.5-5s4.9 1.8 5.5 5"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M17 6.6a2.4 2.4 0 1 0 0 4.8a2.4 2.4 0 1 0 0-4.8z"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M16.5 14c2.2 0.2 3.6 1.7 4 4.5"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/i_restore.xml b/android/app/src/main/res/drawable/i_restore.xml
new file mode 100644
index 0000000..b74bd89
--- /dev/null
+++ b/android/app/src/main/res/drawable/i_restore.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generated icon (Lucide-style stroke, ISC): tinted in code. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M4 12a8 8 0 1 0 2.3-5.7L4 8.6"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M4 4v4.6h4.6"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/i_trash.xml b/android/app/src/main/res/drawable/i_trash.xml
new file mode 100644
index 0000000..172a6b9
--- /dev/null
+++ b/android/app/src/main/res/drawable/i_trash.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generated icon (Lucide-style stroke, ISC): tinted in code. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M4 7h16"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M10 11v6"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M14 11v6"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M6 7l1 13h10l1-13"/>
+ <path android:strokeColor="#FF000000" android:strokeWidth="1.9" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M9 7V4h6v3"/>
+</vector>
diff --git a/android/app/src/main/strings/en.lproj/Android.strings b/android/app/src/main/strings/en.lproj/Android.strings
index 252a234..f7840f9 100644
--- a/android/app/src/main/strings/en.lproj/Android.strings
+++ b/android/app/src/main/strings/en.lproj/Android.strings
@@ -102,13 +102,12 @@
"下拉通知栏,一键开始或结束听" = "Pull down from the top to start or end listening in one tap";
"手机不会读这个语言" = "This phone can't speak that language";
"没能读出来" = "Couldn't read it aloud";
-"松开,说给对方" = "Release to speak";
+"松开,说给对方" = "Let go to send it to them";
"正在读…" = "Speaking…";
-"松开后用 {lang} 读出来" = "Release to say it in {lang}";
+"松开后用 {lang} 读出来" = "Let go and it's read aloud in {lang}";
"按住说完再松开" = "Hold until you've finished speaking";
"没听清,再说一次" = "Didn't catch that. Try again";
"这句已经是对方的语言" = "That's already in their language";
-"没翻译出来,再说一次" = "Couldn't translate. Try again";
"没听到声音,靠近手机再说" = "Didn't hear anything. Move closer and try again";
"让字幕浮在视频上" = "Subtitles on top of the video";
"需要打开“显示在其他应用上层”。只用来显示字幕卡片。" = "Turn on “Display over other apps”. It's only used for the subtitle card.";
@@ -140,3 +139,37 @@
"已完成" = "Done";
"应用信息" = "App info";
"允许受限制的设置" = "Allow restricted settings";
+"查看纪要" = "View notes";
+
+/* Design B: import, face-to-face interpreting, speakers, recording */
+"正在听的时候不能导入,先结束这场会议" = "Can't import while listening. End this meeting first.";
+"这个文件读不出声音" = "Couldn't read any sound from this file";
+"按住下面的按钮说话,松开后对方会听到译文" = "Hold the button below and speak. Let go and they'll hear the translation.";
+"正在听你说,念的时候不收音" = "Listening to you. The mic is off while it reads aloud.";
+"正在听对方说" = "Listening to them";
+"导入录音或视频" = "Import a recording or video";
+"正在转写" = "Transcribing";
+"切到别的 app 也会继续,通知栏里能看进度" = "Keeps going in other apps. Progress is in the notification.";
+"开" = "On";
+"在后台继续" = "Continue in background";
+"转写完成" = "Transcription done";
+"纪要在会议记录里" = "notes are in the record";
+"查看会议记录" = "Open record";
+"录音、视频都可以" = "Recordings and videos";
+"m4a、mp3、wav、mp4、mov…" = "m4a, mp3, wav, mp4, mov…";
+"转成一场会议记录:双语文字记录和纪要。也可以在别的 app 里分享到知了。" = "Becomes a meeting record with a bilingual transcript and notes. You can also share a file to Cicada from another app.";
+"选择文件" = "Choose file";
+"知了 · 正在转写" = "Cicada · Transcribing";
+"面对面翻译" = "Face-to-face interpreting";
+"查看进度" = "View progress";
+"改名" = "Rename";
+"%@ 是谁?" = "Who is %@?";
+"只改这场会议,前面的字幕和纪要一起改" = "This meeting only. Earlier subtitles and notes change too.";
+"播放原声" = "Play recording";
+"配回原视频用" = "To put back on the video";
+"显示 Mac 和 Windows 上分出的说话人;这台手机还不能按声音分人" = "Shows speakers told apart on Mac and Windows. This phone can't tell voices apart yet.";
+"只存在这台手机上,会议记录里能回放原声" = "Kept on this phone only. Play it back in the record.";
+"我说 · 面对面" = "Me · Face to face";
+"按住说话,松开后用对方的语言读出来" = "Hold to speak; let go and it's read aloud in their language";
+"用手机的声音读一句英语" = "Hear an English sentence in the phone's voice";
+"转成一场会议记录" = "Turn it into a meeting record";
diff --git a/android/app/src/main/strings/ja.lproj/Android.strings b/android/app/src/main/strings/ja.lproj/Android.strings
index 64a0657..7f91e31 100644
--- a/android/app/src/main/strings/ja.lproj/Android.strings
+++ b/android/app/src/main/strings/ja.lproj/Android.strings
@@ -108,7 +108,6 @@
"按住说完再松开" = "話し終えるまで押したまま";
"没听清,再说一次" = "聞き取れませんでした。もう一度";
"这句已经是对方的语言" = "すでに相手の言語です";
-"没翻译出来,再说一次" = "翻訳できませんでした。もう一度";
"没听到声音,靠近手机再说" = "声が聞こえません。近づいてもう一度";
"让字幕浮在视频上" = "字幕を動画の上に表示";
"需要打开“显示在其他应用上层”。只用来显示字幕卡片。" = "「他のアプリの上に重ねて表示」をオンにします。字幕カードの表示にだけ使います。";
@@ -140,3 +139,37 @@
"已完成" = "完了";
"应用信息" = "アプリ情報";
"允许受限制的设置" = "制限付き設定を許可";
+"查看纪要" = "メモを見る";
+
+/* Design B: import, face-to-face interpreting, speakers, recording */
+"正在听的时候不能导入,先结束这场会议" = "聞き取り中はインポートできません。先に会議を終了してください";
+"这个文件读不出声音" = "このファイルから音声を読み取れません";
+"按住下面的按钮说话,松开后对方会听到译文" = "下のボタンを押しながら話し、離すと相手に訳が聞こえます";
+"正在听你说,念的时候不收音" = "あなたの声を聞いています。読み上げ中は録音しません";
+"正在听对方说" = "相手の声を聞いています";
+"导入录音或视频" = "録音・動画をインポート";
+"正在转写" = "文字起こし中";
+"切到别的 app 也会继续,通知栏里能看进度" = "他のアプリに切り替えても続きます。進捗は通知で確認できます";
+"开" = "オン";
+"在后台继续" = "バックグラウンドで続ける";
+"转写完成" = "文字起こし完了";
+"纪要在会议记录里" = "メモは会議記録にあります";
+"查看会议记录" = "会議記録を見る";
+"录音、视频都可以" = "録音も動画も OK";
+"m4a、mp3、wav、mp4、mov…" = "m4a、mp3、wav、mp4、mov…";
+"转成一场会议记录:双语文字记录和纪要。也可以在别的 app 里分享到知了。" = "バイリンガルの文字起こしとメモ付きの会議記録になります。他のアプリから知了に共有することもできます。";
+"选择文件" = "ファイルを選択";
+"知了 · 正在转写" = "知了 · 文字起こし中";
+"面对面翻译" = "対面通訳";
+"查看进度" = "進捗を見る";
+"改名" = "名前を変更";
+"%@ 是谁?" = "%@ は誰?";
+"只改这场会议,前面的字幕和纪要一起改" = "この会議だけ。これまでの字幕とメモも変わります";
+"播放原声" = "録音を再生";
+"配回原视频用" = "元の動画に付けるとき";
+"显示 Mac 和 Windows 上分出的说话人;这台手机还不能按声音分人" = "Mac と Windows で分けた話者を表示します。このスマホはまだ声で話者を分けられません";
+"只存在这台手机上,会议记录里能回放原声" = "このスマホにだけ保存。会議記録で再生できます";
+"我说 · 面对面" = "自分 · 対面";
+"按住说话,松开后用对方的语言读出来" = "押しながら話し、離すと相手の言語で読み上げます";
+"用手机的声音读一句英语" = "スマホの声で英語を一文読み上げます";
+"转成一场会议记录" = "会議記録にします";
diff --git a/android/app/src/main/strings/ko.lproj/Android.strings b/android/app/src/main/strings/ko.lproj/Android.strings
index 5d1c3a5..0143f27 100644
--- a/android/app/src/main/strings/ko.lproj/Android.strings
+++ b/android/app/src/main/strings/ko.lproj/Android.strings
@@ -108,7 +108,6 @@
"按住说完再松开" = "말을 마칠 때까지 누르고 있어요";
"没听清,再说一次" = "잘 못 들었어요. 다시 말해 주세요";
"这句已经是对方的语言" = "이미 상대방 언어예요";
-"没翻译出来,再说一次" = "번역하지 못했어요. 다시 말해 주세요";
"没听到声音,靠近手机再说" = "소리가 안 들려요. 가까이에서 다시 말해 주세요";
"让字幕浮在视频上" = "자막을 영상 위에 띄우기";
"需要打开“显示在其他应用上层”。只用来显示字幕卡片。" = "‘다른 앱 위에 표시’를 켜 주세요. 자막 카드를 띄우는 데만 써요.";
@@ -140,3 +139,37 @@
"已完成" = "완료";
"应用信息" = "앱 정보";
"允许受限制的设置" = "제한된 설정 허용";
+"查看纪要" = "회의록 보기";
+
+/* Design B: import, face-to-face interpreting, speakers, recording */
+"正在听的时候不能导入,先结束这场会议" = "듣는 중에는 가져올 수 없어요. 먼저 회의를 끝내세요";
+"这个文件读不出声音" = "이 파일에서 소리를 읽을 수 없어요";
+"按住下面的按钮说话,松开后对方会听到译文" = "아래 버튼을 누른 채 말하고, 손을 떼면 상대에게 번역이 들려요";
+"正在听你说,念的时候不收音" = "듣고 있어요. 읽는 동안에는 녹음하지 않아요";
+"正在听对方说" = "상대의 말을 듣고 있어요";
+"导入录音或视频" = "녹음이나 영상 가져오기";
+"正在转写" = "받아쓰는 중";
+"切到别的 app 也会继续,通知栏里能看进度" = "다른 앱으로 가도 계속돼요. 진행 상황은 알림에서 볼 수 있어요";
+"开" = "켬";
+"在后台继续" = "백그라운드에서 계속";
+"转写完成" = "받아쓰기 완료";
+"纪要在会议记录里" = "노트는 회의 기록에 있어요";
+"查看会议记录" = "회의 기록 보기";
+"录音、视频都可以" = "녹음, 영상 모두 돼요";
+"m4a、mp3、wav、mp4、mov…" = "m4a, mp3, wav, mp4, mov…";
+"转成一场会议记录:双语文字记录和纪要。也可以在别的 app 里分享到知了。" = "이중 언어 기록과 노트가 있는 회의 기록이 돼요. 다른 앱에서 지랴오로 공유해도 돼요.";
+"选择文件" = "파일 선택";
+"知了 · 正在转写" = "지랴오 · 받아쓰는 중";
+"面对面翻译" = "대면 통역";
+"查看进度" = "진행 상황 보기";
+"改名" = "이름 바꾸기";
+"%@ 是谁?" = "%@ 은(는) 누구인가요?";
+"只改这场会议,前面的字幕和纪要一起改" = "이 회의에만 적용돼요. 앞의 자막과 노트도 함께 바뀌어요";
+"播放原声" = "녹음 재생";
+"配回原视频用" = "원래 영상에 붙일 때";
+"显示 Mac 和 Windows 上分出的说话人;这台手机还不能按声音分人" = "Mac과 Windows에서 구분한 화자를 보여 줘요. 이 휴대전화는 아직 목소리로 구분하지 못해요";
+"只存在这台手机上,会议记录里能回放原声" = "이 휴대전화에만 저장돼요. 회의 기록에서 다시 들을 수 있어요";
+"我说 · 面对面" = "나 · 대면";
+"按住说话,松开后用对方的语言读出来" = "누른 채 말하고, 떼면 상대의 언어로 읽어 줘요";
+"用手机的声音读一句英语" = "휴대전화 목소리로 영어 한 문장 듣기";
+"转成一场会议记录" = "회의 기록으로 만들어요";
diff --git a/android/cli/src/main/kotlin/cicada/cli/Tests.kt b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
index 0f17454..067d191 100644
--- a/android/cli/src/main/kotlin/cicada/cli/Tests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
@@ -22,19 +22,36 @@ object Tests {
val tests: List<Pair<String, () -> Unit>> = listOf(
"sessionJsonMatchesTheMac" to ::sessionJsonMatchesTheMac,
"readsAMacRecordAndWritesItBackByteForByte" to ::readsAMacRecord,
+ "keepsTheMacsImportAndRoomFields" to ::keepsTheMacsImportAndRoomFields,
"jsonEdgeCases" to ::jsonEdgeCases,
+ "renamesLikeTheMac" to ::renamesLikeTheMac,
+ "theLiveMeetingCantBeDeleted" to ::theLiveMeetingCantBeDeleted,
+ "followSystemLikeTheMac" to ::followSystemLikeTheMac,
+ "anUntranslatedSentenceIsNeitherSentNorRecorded" to ::anUntranslatedSentenceIsNeitherSentNorRecorded,
"storeSavesAndDropsEmptyMeetings" to ::storeSavesAndDropsEmptyMeetings,
"closesInterruptedMeetings" to ::closesInterruptedMeetings,
+ "exportsLikeTheMac" to ::exportsLikeTheMac,
+ "namesAVoiceLikeTheMac" to ::namesAVoiceLikeTheMac,
"displayTitle" to ::displayTitle,
"parsesMingReplies" to ::parsesMingReplies,
"speaksOnlyTranslations" to ::speaksOnlyTranslations,
+ "hangUpEndsAfterTheGrace" to ::hangUpEndsAfterTheGrace,
+ "rejoiningWithinTheGraceKeepsGoing" to ::rejoiningWithinTheGraceKeepsGoing,
+ "speechDoesNotCancelAHangUp" to ::speechDoesNotCancelAHangUp,
+ "keepGoingForgetsTheHangUp" to ::keepGoingForgetsTheHangUp,
+ "silencePromptsThenEnds" to ::silencePromptsThenEnds,
+ "wordsCancelTheSilencePrompt" to ::wordsCancelTheSilencePrompt,
+ "silenceEndModeEndsAtOnceAndOffNever" to ::silenceEndModeEndsAtOnceAndOffNever,
+ "silenceDoesNotCountDuringACall" to ::silenceDoesNotCountDuringACall,
+ "nothingSaidStopsQuietlyAfterTheSilence" to ::nothingSaidStopsQuietlyAfterTheSilence,
+ "nothingSaidKeepsListening" to ::nothingSaidKeepsListening,
+ "endsAtTheGivenTime" to ::endsAtTheGivenTime,
"holdToSayAndEchoGate" to ::holdToSayAndEchoGate,
"normalizesLanguages" to ::normalizesLanguages,
"cleansTranslations" to ::cleansTranslations,
"joinsCutSentences" to ::joinsCutSentences,
"segmentsOnPauses" to ::segmentsOnPauses,
"cutsLongSpeechAtItsQuietestMoment" to ::cutsLongSpeech,
- "cutsTheFirstStretchEarly" to ::cutsTheFirstStretchEarly,
"ignoresClicks" to ::ignoresClicks,
"wavRoundTrip" to ::wavRoundTrip,
"parsesNotes" to ::parsesNotes,
@@ -152,6 +169,75 @@ 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\"")
+ check(mac.contains("\"room\"") && mac.contains("\"importing\""), "test record has the fields")
+ val s = Session.read(mac)!!
+ equal("周会.m4a", s.sourceFile, "source file")
+ equal("/Users/me/周会.m4a", s.sourcePath, "source path")
+ equal(true, s.importing, "importing"); equal(true, s.room, "room")
+ equal(mac, Json.write(s.toJson()), "written back byte for byte")
+ val untitled = Session.read(mac.replace("\"title\" : \"标题\",\n", ""))!!
+ equal("周会", SessionStore.displayTitle(untitled), "an imported file is known by its name until the notes name it")
+ }
+
+ fun renamesLikeTheMac() {
+ val store = SessionStore(loadNow = false)
+ val s = store.begin(Instant.parse("2026-03-01T01:00:00Z"))
+ store.append(s.id, TranscriptLine(id = "h1-1", src = "hi", srcLang = "en", dstLang = "zh-CN"))
+ store.setNotes(s.id, MeetingNotes(title = "路线评审", summary = "x"))
+ val auto = SessionStore.displayTitle(s)
+ store.rename(s.id, auto)
+ check(s.renamed != true, "saving the title already shown is no rename")
+ store.rename(s.id, " 我的会 ")
+ equal("我的会", s.title, "trimmed"); equal(true, s.renamed, "renamed")
+ store.rename(s.id, "")
+ equal(false, s.renamed, "emptied goes back to the automatic title")
+ equal(auto, SessionStore.displayTitle(s), "the notes' name again")
+ check(s.title.startsWith("会议 "), "the stored default title")
+ store.end(s.id)
+ }
+
+ fun theLiveMeetingCantBeDeleted() {
+ val store = SessionStore(loadNow = false)
+ val s = store.begin(Instant.parse("2026-03-02T01:00:00Z"))
+ store.append(s.id, TranscriptLine(id = "h1-1", src = "hi", srcLang = "en", dstLang = "zh-CN"))
+ equal(s.id, store.liveId, "live")
+ store.delete(s.id)
+ check(store.get(s.id) != null, "kept while listening")
+ store.end(s.id)
+ equal(null, store.liveId, "not live once ended")
+ store.delete(s.id)
+ check(store.get(s.id) == null && !File(Paths.sessions, s.id).exists(), "deleted once ended")
+ val empty = store.begin(Instant.parse("2026-03-02T02:00:00Z"))
+ store.end(empty.id)
+ 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")
+ equal("zh-CN", Languages.fromSystem("zh-Hans-HK"), "the script decides")
+ equal("zh-TW", Languages.fromSystem("zh-HK"), "a region without a script")
+ val zhEn = listOf("zh-Hans-CN", "en-US")
+ equal("zh-CN", Languages.followSystemTarget("en", zhEn), "English into my language")
+ equal("en", Languages.followSystemTarget("zh-CN", zhEn), "my language into the next system one")
+ equal("en", Languages.followSystemTarget("zh-CN", listOf("zh-Hans-CN")), "only Chinese: English")
+ equal("zh-CN", Languages.followSystemTarget("en", listOf("en-US")), "only English: Chinese")
+ equal("zh-CN", Languages.followSystemTarget(null, zhEn), "not known yet: my language")
+ val old = AppSettings.systemLanguages
+ try {
+ AppSettings.systemLanguages = { zhEn }
+ val follow = AppSettings()
+ equal("zh-CN", follow.targetCode, "my language"); equal("en", follow.targetFor("zh-CN"), "follows")
+ equal("zh-CN", follow.notesCode, "notes in my language")
+ equal("zh-CN", AppSettings(target = "zh-CN").targetFor("zh-CN"), "a chosen language stays")
+ } finally { AppSettings.systemLanguages = old }
+ }
+
fun jsonEdgeCases() {
equal("3", Json.number(3.0), "whole doubles without .0")
equal("0.0001", Json.number(0.0001), "small doubles without an exponent")
@@ -180,7 +266,49 @@ object Tests {
check(SessionStore().get(s.id) != null, "loaded again")
check(s.title.startsWith("会议 "), "default title is the Mac's Chinese form")
val md = SessionStore.markdown(store.get(s.id)!!)
- check(md.contains("## 文字记录") && md.contains("hi"), "markdown export")
+ 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),
+ TranscriptLine(id = "b$i", t = i * 10.0 + 5, speaker = "them", src = "not before the freeze", dst = "封版前不行", voice = 2))
+ }
+ val s = Session(id = "20260103-040506", title = "会议 1月3日 04:05", startedAt = Instant.parse("2026-01-03T04:05:06Z"),
+ lines = (them + TranscriptLine(id = "m1", t = 61.0, speaker = "me", src = "好的", dst = "OK")).toMutableList())
+ s.endedAt = Instant.parse("2026-01-03T04:07:06Z")
+ val numbers = SpeakerLabels.numbers(s.lines)
+ equal(1, numbers["a1"], "first voice to say five lines is 1")
+ equal(2, numbers["b5"], "second is 2")
+ equal(emptyMap<String, Int>(), SpeakerLabels.numbers(s.lines.filter { it.voice != 2 }), "one voice stays 对方")
+ s.voiceNames = mapOf("2" to "Ken")
+ val md = TranscriptExport.markdown(s)
+ check(md.contains("**[00:10] 说话人 1** \nwe should ship it now\n> 我们现在就该发布\n"), "markdown speaker number")
+ check(md.contains("**[00:15] Ken**"), "markdown speaker name")
+ check(md.contains("**[01:01] 你** \n好的\n> OK\n"), "markdown me")
+ val srt = TranscriptExport.srt(s)
+ check(srt.startsWith("1\n00:00:10,000 --> 00:00:15,000\nwe should ship it now\n我们现在就该发布\n\n2\n"), "srt cue")
+ check(srt.contains("11\n00:01:01,000 --> 00:01:05,000\n好的\nOK\n"), "srt last cue ends 4 s on")
+ val docx = TranscriptExport.docx(s)
+ val names = java.util.zip.ZipInputStream(docx.inputStream()).use { z -> generateSequence { z.nextEntry?.name }.toList() }
+ equal(listOf("[Content_Types].xml", "_rels/.rels", "word/document.xml"), names, "docx parts")
+ val doc = java.util.zip.ZipInputStream(docx.inputStream()).use { z -> while (z.nextEntry?.name != "word/document.xml") {}; z.readBytes().toString(Charsets.UTF_8) }
+ check(doc.contains(">[00:15] Ken<") && doc.contains(">我们现在就该发布<"), "docx text")
+ SpeakerLabels.voices = false
+ check(TranscriptExport.markdown(s).contains("**[00:15] 对方**"), "说话人识别 off: no numbers")
+ SpeakerLabels.voices = true
+ }
+
+ fun namesAVoiceLikeTheMac() {
+ val store = SessionStore()
+ val s = store.begin(Instant.parse("2026-01-04T02:00:00Z"))
+ store.append(s.id, TranscriptLine(id = "h1-1", src = "hi there everyone", voice = 3))
+ store.setVoiceName(s.id, 3, " Maya ")
+ equal(mapOf("3" to "Maya"), store.get(s.id)!!.voiceNames, "trimmed, by voice id")
+ store.setVoiceName(s.id, 3, null)
+ equal(emptyMap<String, String>(), store.get(s.id)!!.voiceNames, "null drops it")
}
fun closesInterruptedMeetings() {
@@ -280,13 +408,6 @@ object Tests {
check(abs(list[2].start - (list[1].start + list[1].seconds)) < 0.001, "the rest carries on without a gap")
}
- fun cutsTheFirstStretchEarly() {
- // A meeting's first stretch is cut by 4 s (at its quietest moment), so a line shows soon.
- val list = cut(tone(3.0), tone(0.3, 0.004), tone(4.0), silence(1.0))
- equal(2, list.size, "split in two")
- check(list[0].seconds in 2.9..3.5, "cut inside the dip, got ${list[0].seconds}")
- }
-
fun ignoresClicks() {
equal(0, cut(silence(1.0), tone(0.1), silence(1.0)).size, "under 0.25 s of sound is not speech")
equal(0, cut(tone(3.0, 0.002)).size, "below the gate is silence")
@@ -553,4 +674,133 @@ object Tests {
check(s.lines[1].t >= 2.0, "my line's time is when I pressed")
} finally { LingClient.spacing = old }
}
+
+ 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, "")
+ }
+ val old = LingClient.spacing
+ LingClient.spacing = 0.05
+ try {
+ val ling = client(fake)
+ val store = SessionStore(loadNow = false)
+ val engine = ListenEngine(ling, Translator(ling, fake), store, NotesEngine(ling, store), AppSettings(target = "zh-CN"))
+ var spoken: String? = null
+ engine.onSaid = { text, _ -> spoken = text }
+ val src = ManualSource()
+ engine.start(src, "mic")
+ engine.hold(); src.push(tone(1.2)); engine.release(); src.push(silence(0.3))
+ val until = System.currentTimeMillis() + 4000
+ while (engine.sayProblem == null && System.currentTimeMillis() < until) Thread.sleep(20)
+ equal("翻译失败,这句话未发送", engine.sayProblem, "the Mac's message")
+ equal(null, spoken, "nothing spoken")
+ check(store.get(engine.sessionId!!)!!.lines.none { it.speaker == "me" }, "nothing recorded")
+ engine.stop()
+ } finally { LingClient.spacing = old }
+ }
+
+ // MARK: Meeting end (MeetingEndTests.swift, the same cases)
+
+ private val zoom = mapOf("us.zoom.xos" to "Zoom")
+ private fun watch(silence: MeetingEndWatch.Silence = MeetingEndWatch.Silence.Prompt, followApps: Boolean = true) =
+ MeetingEndWatch(MeetingEndWatch.Config(followApps = followApps, silence = silence), 0.0)
+ private val none = emptyMap<String, String>()
+
+ fun hangUpEndsAfterTheGrace() {
+ val w = watch()
+ equal(null, w.tick(10.0, zoom, true), "in a call")
+ equal(null, w.tick(20.0, none, true), "hung up")
+ equal(MeetingEndWatch.Pending(MeetingEndWatch.Reason.AppLeft("Zoom"), 50.0), w.pending, "grace")
+ equal(null, w.tick(49.0, none, true), "not yet")
+ equal(MeetingEndWatch.Reason.AppLeft("Zoom"), w.tick(50.0, none, true), "ends")
+ }
+
+ fun rejoiningWithinTheGraceKeepsGoing() {
+ val w = watch()
+ w.tick(10.0, zoom, true); w.tick(20.0, none, true)
+ equal(null, w.tick(30.0, zoom, true), "rejoined")
+ equal(null, w.pending, "no pending")
+ }
+
+ fun speechDoesNotCancelAHangUp() {
+ val w = watch()
+ w.tick(10.0, zoom, true); w.tick(20.0, none, true)
+ w.heard(25.0)
+ equal(MeetingEndWatch.Reason.AppLeft("Zoom"), w.tick(50.0, none, true), "still ends")
+ }
+
+ fun keepGoingForgetsTheHangUp() {
+ val w = watch()
+ w.tick(10.0, zoom, true); w.tick(20.0, none, true)
+ w.keepGoing(30.0)
+ equal(null, w.tick(100.0, none, true), "kept going")
+ equal(null, w.pending, "no pending")
+ }
+
+ fun silencePromptsThenEnds() {
+ val w = watch()
+ w.heard(5.0)
+ equal(null, w.tick(604.0, none, true), "not yet")
+ equal(null, w.pending, "no prompt yet")
+ equal(null, w.tick(605.0, none, true), "prompts")
+ equal(MeetingEndWatch.Pending(MeetingEndWatch.Reason.Silence, 665.0), w.pending, "60 s countdown")
+ equal(MeetingEndWatch.Reason.Silence, w.tick(665.0, none, true), "ends")
+ }
+
+ fun wordsCancelTheSilencePrompt() {
+ val w = watch()
+ w.tick(600.0, none, true)
+ equal(MeetingEndWatch.Reason.Silence, w.pending?.reason, "prompting")
+ w.heard(620.0)
+ equal(null, w.pending, "words cancel it")
+ equal(null, w.tick(700.0, none, true), "and the clock restarts")
+ }
+
+ fun silenceEndModeEndsAtOnceAndOffNever() {
+ equal(MeetingEndWatch.Reason.Silence, watch(MeetingEndWatch.Silence.End).tick(600.0, none, true), "ends at once")
+ val off = watch(MeetingEndWatch.Silence.Off)
+ equal(null, off.tick(99_999.0, none, true), "off never ends")
+ equal(null, off.pending, "off never prompts")
+ }
+
+ fun silenceDoesNotCountDuringACall() {
+ 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
+ equal(null, plain.tick(600.0, zoom, true), "prompts")
+ equal(MeetingEndWatch.Reason.Silence, plain.pending?.reason, "silence counts")
+ }
+
+ fun nothingSaidStopsQuietlyAfterTheSilence() {
+ val w = watch()
+ equal(null, w.tick(599.0, none, false), "not yet")
+ equal(MeetingEndWatch.Reason.NobodySpoke, w.tick(600.0, none, false), "stops")
+ equal(null, w.pending, "without a countdown")
+ equal(MeetingEndWatch.Reason.NobodySpoke, watch(MeetingEndWatch.Silence.End).tick(600.0, none, false), "end mode too")
+ equal(null, watch(MeetingEndWatch.Silence.Off).tick(5_000.0, none, false), "off keeps listening")
+ equal(null, watch().tick(5_000.0, zoom, false), "a call keeps listening")
+ }
+
+ fun nothingSaidKeepsListening() {
+ val w = watch()
+ w.tick(10.0, zoom, false)
+ equal(null, w.tick(500.0, none, false), "a call that ended before anyone spoke")
+ equal(null, w.pending, "no pending")
+ w.heard(5_001.0)
+ equal(null, w.tick(5_002.0, none, true), "is forgotten once someone does")
+ equal(null, w.pending, "no pending")
+ }
+
+ 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"))
+ store.end(s.id, java.time.Instant.parse("2026-11-04T10:00:06Z"))
+ equal(java.time.Instant.parse("2026-11-04T10:00:06Z"), store.get(s.id)?.endedAt, "endedAt")
+ equal("已经 10 分钟没人说话", Strings.LF("已经 %lld 分钟没人说话", 10), "number placeholder")
+ }
}
diff --git a/android/core/src/main/kotlin/cicada/Export.kt b/android/core/src/main/kotlin/cicada/Export.kt
new file mode 100644
index 0000000..95589eb
--- /dev/null
+++ b/android/core/src/main/kotlin/cicada/Export.kt
@@ -0,0 +1,196 @@
+package cicada
+
+import java.io.ByteArrayOutputStream
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+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.
+/// Android doesn't tell voices apart itself yet (no voiceprint runtime in the framework): the
+/// voices come from records made on the Mac or Windows, and the names the user gives here.
+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
+ return text.codePoints().filter { c ->
+ Character.isIdeographic(c) || c in 0x3040..0x30FF || c in 0xAC00..0xD7A3
+ }.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 ->
+ val v = l.voice
+ if (l.speaker != "them" || v == null || !substantive(l.src)) return@forEachIndexed
+ count[v] = (count[v] ?: 0) + 1
+ if (count[v] == SHOWN_AFTER) reached[v] = i
+ }
+ val shown = reached.keys.sortedBy { reached[it] }
+ if (shown.size < 2) return emptyMap()
+ 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)
+ val out = HashMap<String, Int>()
+ for (l in lines) if (l.speaker == "them") l.voice?.let { v -> number[v]?.let { out[l.id] = it } }
+ 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>()
+ for ((v, n) in voiceNumbers(s.lines)) {
+ val mine = s.voiceNames?.get(v.toString())
+ if (mine != null) { if (mine.isNotEmpty()) out[n] = mine }
+ else s.voiceGuesses?.get(v.toString())?.let { out[n] = it.name }
+ }
+ 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)
+
+ /// Who said a line: 你, 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) }
+ return if (numbers.isEmpty()) Strings.L("对方") else Strings.L("未识别")
+ }
+}
+
+/// 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()
+ val at = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT)
+ .withLocale(Strings.locale).withZone(ZoneId.systemDefault()).format(s.startedAt)
+ return "$at · " + if (mins < 1) Strings.L("不到 1 分钟") else Strings.LF("%lld 分钟", mins)
+ }
+
+ fun notesMarkdown(n: MeetingNotes?): String {
+ if (n == null || n.isEmpty) return ""
+ val b = StringBuilder("## ${Strings.L("纪要")}\n\n${n.summary}\n\n")
+ for (t in n.topics) {
+ b.append("### ${Languages.clock(t.start)} ${t.title}\n\n")
+ if (t.summary.isNotEmpty()) b.append("${t.summary}\n\n")
+ for (p in t.points) b.append("- $p\n")
+ t.fishbone?.let { f ->
+ b.append("\n**${f.question}**\n\n")
+ for (br in f.branches) b.append("- ${br.label}:${br.detail}\n")
+ }
+ b.append("\n")
+ }
+ if (n.conclusions.isNotEmpty()) b.append("### ${Strings.L("结论")}\n\n").append(n.conclusions.joinToString("") { "- ${it.text}\n" }).append("\n")
+ if (n.todos.isNotEmpty()) b.append("### ${Strings.L("待办")}\n\n").append(n.todos.joinToString("") { "- [ ] ${it.text}" + (it.owner?.let { o -> "($o)" } ?: "") + "\n" }).append("\n")
+ if (n.terms.isNotEmpty()) b.append("### ${Strings.L("人名和术语")}\n\n").append(n.terms.joinToString("") { "- **${it.name}** ${it.note}\n" }).append("\n")
+ return b.toString()
+ }
+
+ fun markdown(s: Session): String {
+ val b = StringBuilder("# ${SessionStore.displayTitle(s)}\n\n${header(s)}\n\n")
+ val notes = notesMarkdown(s.notes)
+ if (notes.isNotEmpty()) b.append(notes).append("## ${Strings.L("文字记录")}\n\n")
+ val numbers = SpeakerLabels.numbers(s.lines); val names = SpeakerLabels.names(s)
+ for (l in s.lines) {
+ // An imported file has no "other side" to name.
+ val who = if (s.sourceFile == null) " ${SpeakerLabels.speakerName(l, numbers, names)}" else ""
+ b.append("**[${Languages.clock(l.t)}]$who** \n${l.src}\n")
+ l.dst?.takeIf { it != l.src && it.isNotEmpty() }?.let { b.append("> $it\n") }
+ b.append("\n")
+ }
+ return b.toString()
+ }
+
+ fun srt(s: Session): String {
+ fun ts(t: Double): String {
+ val ms = Math.round(maxOf(0.0, t) * 1000)
+ return "%02d:%02d:%02d,%03d".format(ms / 3_600_000, (ms / 60_000) % 60, (ms / 1000) % 60, ms % 1000)
+ }
+ val b = StringBuilder()
+ 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))
+ b.append("${i + 1}\n${ts(l.t)} --> ${ts(end)}\n${l.src}\n")
+ l.dst?.takeIf { it != l.src && it.isNotEmpty() }?.let { b.append("$it\n") }
+ b.append("\n")
+ }
+ 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) {
+ val esc = text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+ body.append("<w:p><w:pPr><w:spacing w:after=\"${(after * 20).toInt()}\"/></w:pPr><w:r><w:rPr>")
+ if (bold) body.append("<w:b/>")
+ body.append("<w:color w:val=\"$color\"/><w:sz w:val=\"${(size * 2).toInt()}\"/></w:rPr><w:t xml:space=\"preserve\">$esc</w:t></w:r></w:p>")
+ }
+ add(SessionStore.displayTitle(s), 20.0, bold = true, after = 6.0)
+ add(header(s), 10.0, color = "555555", after = 14.0)
+ val n = s.notes
+ if (n != null && !n.isEmpty) {
+ add(Strings.L("纪要"), 15.0, bold = true, after = 6.0)
+ add(n.summary, 11.0, after = 10.0)
+ for (t in n.topics) {
+ add("${Languages.clock(t.start)} ${t.title}", 12.0, bold = true, after = 3.0)
+ if (t.summary.isNotEmpty()) add(t.summary, 11.0, color = "555555", after = 3.0)
+ for (p in t.points) add("• $p", 11.0, after = 2.0)
+ t.fishbone?.let { f ->
+ add(f.question, 11.0, bold = true, after = 2.0)
+ for (br in f.branches) add(" – ${br.label}:${br.detail}", 11.0, after = 2.0)
+ }
+ add("", 6.0, after = 4.0)
+ }
+ if (n.conclusions.isNotEmpty()) { add(Strings.L("结论"), 12.0, bold = true, after = 3.0); for (c in n.conclusions) add("• ${c.text}", 11.0, after = 2.0) }
+ if (n.todos.isNotEmpty()) { add(Strings.L("待办"), 12.0, bold = true, after = 3.0); for (t in n.todos) add("☐ ${t.text}" + (t.owner?.let { "($it)" } ?: ""), 11.0, after = 2.0) }
+ add(Strings.L("文字记录"), 15.0, bold = true, after = 6.0)
+ }
+ val numbers = SpeakerLabels.numbers(s.lines); val names = SpeakerLabels.names(s)
+ for (l in s.lines) {
+ add("[${Languages.clock(l.t)}]" + if (s.sourceFile == null) " ${SpeakerLabels.speakerName(l, numbers, names)}" else "", 9.0, bold = true, color = "555555", after = 2.0)
+ add(l.src, 11.0, after = 2.0)
+ l.dst?.takeIf { it != l.src && it.isNotEmpty() }?.let { add(it, 11.0, color = "4D4D4D", after = 10.0) }
+ }
+ val doc = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
+ "<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><w:body>$body" +
+ "<w:sectPr><w:pgSz w:w=\"11906\" w:h=\"16838\"/><w:pgMar w:top=\"1440\" w:right=\"1440\" w:bottom=\"1440\" w:left=\"1440\"/></w:sectPr></w:body></w:document>"
+ val types = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
+ "<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">" +
+ "<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>" +
+ "<Default Extension=\"xml\" ContentType=\"application/xml\"/>" +
+ "<Override PartName=\"/word/document.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml\"/></Types>"
+ val rels = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">" +
+ "<Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\" Target=\"word/document.xml\"/></Relationships>"
+ val out = ByteArrayOutputStream()
+ ZipOutputStream(out).use { z ->
+ for ((name, text) in listOf("[Content_Types].xml" to types, "_rels/.rels" to rels, "word/document.xml" to doc)) {
+ z.putNextEntry(ZipEntry(name)); z.write(text.toByteArray(Charsets.UTF_8)); z.closeEntry()
+ }
+ }
+ 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/ListenEngine.kt b/android/core/src/main/kotlin/cicada/ListenEngine.kt
index 2ca929a..dd49930 100644
--- a/android/core/src/main/kotlin/cicada/ListenEngine.kt
+++ b/android/core/src/main/kotlin/cicada/ListenEngine.kt
@@ -55,7 +55,12 @@ class ListenEngine(
/// of speech on mobile data). Null or a throw falls back to WAV, which Ming always takes.
@Volatile var encoder: (ShortArray) -> Clip? = { null }
- init { translator.glossary = { notes.glossary() } }
+ // 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) }
+ }
fun onChange(listener: () -> Unit) { synchronized(listeners) { listeners.add(listener) } }
private fun changed() { synchronized(listeners) { listeners.toList() }.forEach { it() } }
@@ -70,6 +75,9 @@ class ListenEngine(
// 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.
@@ -120,6 +128,10 @@ 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) {
if (listening) return
val session = store.begin()
@@ -132,7 +144,6 @@ class ListenEngine(
}
holding = false; saying = false; muted = false; sayProblem = null; saidCount = 0
heardSeconds = 0.0; peak = 0.0
- notes.language = { Languages.englishName(settings.notesCode) }
notes.begin(session.id)
val segmenter = Segmenter()
segmenter.onSegment = ::send
@@ -156,7 +167,7 @@ class ListenEngine(
segmenter.flush()
}, "ListenWorker").apply { isDaemon = true; start() }
source = from
- from.onSamples = { queue.offer(it) }
+ 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
@@ -167,7 +178,7 @@ class ListenEngine(
/// 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() {
+ 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
@@ -180,7 +191,7 @@ class ListenEngine(
for (f in waiting) {
try { f.get(maxOf(1, deadline - System.currentTimeMillis()), TimeUnit.MILLISECONDS) } catch (_: Exception) {}
}
- store.end(id)
+ store.end(id, endedAt)
Log.d("listen: stopped $id, $lineCount lines")
changed()
pool.execute { notes.finish() }
@@ -211,19 +222,21 @@ class ListenEngine(
if (heard == null) { sayProblem = Strings.L("没听清,再说一次"); return }
var dst = heard.translation
if (dst == null && !Languages.same(heard.lang, their)) dst = translator.translate(heard.original, heard.lang, their, Translator.Kind.Sentence)
+ val sameLanguage = Languages.same(heard.lang, their)
+ 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())
- val text = speakable(line)
- Log.d("listen: said ${heard.lang} -> $their, ${if (text != null) "speaking" else "not spoken"}")
- when {
- text != null -> onSaid?.invoke(text, their)
- Languages.same(heard.lang, their) -> sayProblem = Strings.L("这句已经是对方的语言")
- else -> sayProblem = Strings.L("没翻译出来,再说一次")
- }
+ onWords?.invoke()
+ if (text != null) onSaid?.invoke(text, their) else sayProblem = Strings.L("这句已经是对方的语言")
} catch (e: LingException) {
sayProblem = when (e.kind) {
LingException.Kind.NoKey, LingException.Kind.InvalidKey -> Strings.L("Ling key 无效")
@@ -248,13 +261,20 @@ class ListenEngine(
private fun send(seg: Segment) {
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 {
var heard: Heard? = null
val started = System.currentTimeMillis()
try {
val clip = encode(seg.samples)
- heard = translator.hear(clip, target, lang)
+ // 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)?.let { h ->
+ if (settings.targetFor(h.lang) == asked) h else h.copy(translation = null)
+ }
problem = null
} catch (e: LingException) {
problem = when (e.kind) {
@@ -291,7 +311,7 @@ class ListenEngine(
private fun record(seg: Segment, heard: Heard) {
val id = sessionId ?: return
- val target = target
+ 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) {
@@ -321,6 +341,7 @@ class ListenEngine(
}
val copy = synchronized(gate) { line.copy() }
if (joined) store.replace(id, copy) else store.append(id, copy)
+ onWords?.invoke()
// 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) {
diff --git a/android/core/src/main/kotlin/cicada/MeetingEnd.kt b/android/core/src/main/kotlin/cicada/MeetingEnd.kt
new file mode 100644
index 0000000..03cc8fe
--- /dev/null
+++ b/android/core/src/main/kotlin/cicada/MeetingEnd.kt
@@ -0,0 +1,94 @@
+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");
+ companion object { fun of(key: String) = values().firstOrNull { it.key == key } ?: Prompt }
+ }
+
+ data class Config(
+ 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()
+ pending = null
+ val inACall = config.followApps && calls.isNotEmpty()
+ if (config.silence != Silence.Off && !inACall && now - lastSpeech >= config.silenceAfter) return Reason.NobodySpoke
+ return null
+ }
+ 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 (hungUp && (pending == null || pending?.reason == Reason.Silence)) {
+ val name = inCall.toSortedMap().values.firstOrNull() ?: ""
+ pending = Pending(Reason.AppLeft(name), now + config.appGrace)
+ }
+ } else if (pending?.reason is Reason.AppLeft) {
+ pending = null
+ }
+ val inACall = config.followApps && calls.isNotEmpty()
+ if (pending == null && config.silence != Silence.Off && !inACall && now - lastSpeech >= config.silenceAfter) {
+ if (config.silence == Silence.End) return Reason.Silence
+ pending = Pending(Reason.Silence, now + config.countdown)
+ }
+ if ((config.silence == Silence.Off || inACall) && pending?.reason == Reason.Silence) pending = null
+ val p = pending
+ if (p != null && now >= p.deadline) {
+ pending = null
+ return p.reason
+ }
+ return null
+ }
+}
diff --git a/android/core/src/main/kotlin/cicada/Models.kt b/android/core/src/main/kotlin/cicada/Models.kt
index 6ba1a6c..7838189 100644
--- a/android/core/src/main/kotlin/cicada/Models.kt
+++ b/android/core/src/main/kotlin/cicada/Models.kt
@@ -63,6 +63,13 @@ 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,
) {
val durationSeconds: Double get() = ((endedAt ?: Instant.now()).toEpochMilli() - startedAt.toEpochMilli()) / 1000.0
@@ -70,6 +77,7 @@ class Session(
"id" to id, "title" to title, "startedAt" to Iso8601.write(startedAt), "endedAt" to endedAt?.let(Iso8601::write),
"lines" to lines.map { it.toJson() }, "hasAudio" to hasAudio, "notes" to notes?.toJson(), "renamed" to renamed,
"voiceNames" to voiceNames, "voiceGuesses" to voiceGuesses?.mapValues { it.value.toJson() },
+ "sourceFile" to sourceFile, "sourcePath" to sourcePath, "importing" to importing, "room" to room,
)
companion object {
@@ -81,6 +89,8 @@ class Session(
renamed = o["renamed"].bool(),
voiceNames = o["voiceNames"].obj()?.mapValues { it.value.str() ?: "" },
voiceGuesses = o["voiceGuesses"].obj()?.mapValues { VoiceGuess.from(it.value.obj() ?: emptyMap()) },
+ sourceFile = o["sourceFile"].str(), sourcePath = o["sourcePath"].str(),
+ importing = o["importing"].bool(), room = o["room"].bool(),
)
fun read(text: String): Session? = Json.parseObject(text)?.let(::from)
diff --git a/android/core/src/main/kotlin/cicada/Notes.kt b/android/core/src/main/kotlin/cicada/Notes.kt
index e21551d..f17ba2b 100644
--- a/android/core/src/main/kotlin/cicada/Notes.kt
+++ b/android/core/src/main/kotlin/cicada/Notes.kt
@@ -79,7 +79,9 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)
private fun tick() {
val id = synchronized(gate) {
- if (status == State.NoKey && ling.usable) status = State.Idle
+ // 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
diff --git a/android/core/src/main/kotlin/cicada/SessionStore.kt b/android/core/src/main/kotlin/cicada/SessionStore.kt
index 821eb19..6bf910f 100644
--- a/android/core/src/main/kotlin/cicada/SessionStore.kt
+++ b/android/core/src/main/kotlin/cicada/SessionStore.kt
@@ -20,6 +20,9 @@ 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
@@ -67,6 +70,7 @@ class SessionStore(loadNow: Boolean = true) {
val id = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss").withZone(ZoneId.systemDefault()).format(at)
val s = Session(id = id, title = defaultTitle(at), startedAt = at.truncatedTo(java.time.temporal.ChronoUnit.SECONDS))
synchronized(gate) { sessions[id] = s }
+ liveId = id
return s
}
@@ -79,19 +83,48 @@ class SessionStore(loadNow: Boolean = true) {
fun setNotes(id: String, notes: MeetingNotes) = mutate(id) { it.notes = notes }
- fun rename(id: String, title: String) = mutate(id) { it.title = title.trim(); it.renamed = true }
+ /// 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
+ if (t.isEmpty()) { s.title = defaultTitle(s.startedAt); s.renamed = false }
+ 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
+ }
+
+ /// 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: kept if anything was said, removed otherwise.
- fun end(id: String) {
+ /// 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
val s = sessions[id] ?: return
- s.endedAt = Instant.now()
+ s.endedAt = at ?: Instant.now()
s.lines.isEmpty()
}
- if (empty) delete(id) else { markDirty(id); flush() }
+ 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)
+ }
+
+ private fun deleteNow(id: String) {
synchronized(gate) { sessions.remove(id); dirty.remove(id) }
try { folder(id).deleteRecursively() } catch (e: Exception) { Log.d("store: delete failed ${e.javaClass.simpleName}") }
fire(id)
@@ -148,6 +181,8 @@ class SessionStore(loadNow: Boolean = true) {
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
return localDate(s.startedAt, Strings.L(if (thisYear) "M月d日" else "yyyy年M月d日")) + " " + name
@@ -155,39 +190,7 @@ 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: notes, then the bilingual transcript (the Windows export).
- fun markdown(s: Session): String {
- val b = StringBuilder()
- b.append("# ${s.notes?.title ?: s.title}\n\n")
- b.append(stamp(s.startedAt)).append("\n\n")
- val n = s.notes
- if (n != null && !n.isEmpty) {
- b.append("## ${Strings.L("纪要")}\n\n${n.summary}\n\n")
- for (t in n.topics) {
- b.append("### ${Languages.clock(t.start)} ${t.title}\n\n")
- if (t.summary.isNotEmpty()) b.append(t.summary).append("\n\n")
- for (p in t.points) b.append("- $p\n")
- b.append("\n")
- }
- if (n.conclusions.isNotEmpty()) {
- b.append("### ${Strings.L("结论")}\n\n")
- for (c in n.conclusions) b.append("- ${c.text}\n")
- b.append("\n")
- }
- if (n.todos.isNotEmpty()) {
- b.append("### ${Strings.L("待办")}\n\n")
- for (t in n.todos) b.append("- [ ] ${t.text}${t.owner?.let { "($it)" } ?: ""}\n")
- b.append("\n")
- }
- }
- b.append("## ${Strings.L("文字记录")}\n\n")
- for (l in s.lines) {
- val who = if (l.speaker == "me") Strings.L("你") + " · " else ""
- b.append("**${Languages.clock(l.t)}** $who${l.src} \n")
- if (!l.dst.isNullOrEmpty() && l.dst != l.src) b.append(l.dst).append("\n")
- b.append("\n")
- }
- return b.toString()
- }
+ /// 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 e5c222a..26e3b20 100644
--- a/android/core/src/main/kotlin/cicada/Settings.kt
+++ b/android/core/src/main/kotlin/cicada/Settings.kt
@@ -20,14 +20,32 @@ class AppSettings(
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,
+ /// 说话人识别: number the other side's voices in records and exports (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,
) {
- val targetCode: String get() = if (target == "system") Languages.fromSystem(Locale.getDefault().toLanguageTag()) else target
+ /// 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
+
fun toJson(): Map<String, Any?> = mapOf(
"target" to target, "notesLanguage" to notesLanguage, "model" to model, "view" to view,
"showInCapture" to showInCapture, "onboarded" to onboarded, "uiLanguage" to uiLanguage,
- "source" to source, "overlay" to overlay,
+ "source" to source, "overlay" to overlay, "silenceEnd" to silenceEnd, "silenceMinutes" to silenceMinutes,
+ "speakerVoices" to speakerVoices, "recordAudio" to recordAudio, "speakBack" to speakBack,
)
fun save() {
@@ -38,6 +56,10 @@ 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 {
try {
if (Paths.settings.isFile) {
@@ -50,6 +72,10 @@ class AppSettings(
showInCapture = o["showInCapture"].bool() ?: false, onboarded = o["onboarded"].bool() ?: false,
uiLanguage = o["uiLanguage"].str() ?: d.uiLanguage, source = o["source"].str() ?: d.source,
overlay = o["overlay"].bool() ?: true,
+ silenceEnd = o["silenceEnd"].str() ?: d.silenceEnd,
+ silenceMinutes = (o["silenceMinutes"] as? Number)?.toDouble() ?: d.silenceMinutes,
+ speakerVoices = o["speakerVoices"].bool() ?: true, recordAudio = o["recordAudio"].bool() ?: true,
+ speakBack = o["speakBack"].bool() ?: true,
)
}
}
diff --git a/site/changelog.json b/site/changelog.json
index 1ed1a41..aa182b5 100644
--- a/site/changelog.json
+++ b/site/changelog.json
@@ -120,6 +120,81 @@
"kind": "improved",
"title": "纪要窗口里“共享屏幕时让对方看到”的图标一直在,点一下开、再点一下关。",
"text": "橙灯亮着、光晕呼吸表示对方可见,灰色空心小灯表示只有你看得到;鼠标停在上面有提示。设置里的开关旁也有同一个指示灯。"
+ },
+ {
+ "kind": "fixed",
+ "title": "Android 上打开 Mac 导入或在会议室录的会议记录,再存回去不再丢掉这些信息。",
+ "text": "记录里的来源文件、会议室标记原样保留,Mac 再打开时和原来一样。"
+ },
+ {
+ "kind": "fixed",
+ "title": "Android 上正在听的会议不能删了。",
+ "text": "之前在听写时打开记录能把它删掉,后面听到的话会悄悄丢失。"
+ },
+ {
+ "kind": "fixed",
+ "title": "Android 上重命名照 Mac:没改字就保存不算改名,清空回到自动标题,菜单里可以恢复自动标题。",
+ "text": ""
+ },
+ {
+ "kind": "fixed",
+ "title": "Android 上面对面没翻译成功的话不再记进记录,提示“翻译失败,这句话未发送”。",
+ "text": ""
+ },
+ {
+ "kind": "fixed",
+ "title": "Android 上给旧会议生成纪要时用设置里的纪要语言,不再总是简体中文。",
+ "text": ""
+ },
+ {
+ "kind": "improved",
+ "title": "Android 上“跟随系统”照 Mac:对方说的就是我的语言时,翻成手机的下一个语言。",
+ "text": "手机只设了一种语言时,中英互换。"
+ },
+ {
+ "kind": "improved",
+ "title": "Android 上结束会议前先问一句“结束这场会议?”。",
+ "text": ""
+ },
+ {
+ "kind": "improved",
+ "title": "Android 重新设计:大标题、底部导航、按天分组的会议记录,和 iPhone 版一个样子。",
+ "text": "实时纪要的行高照 iOS,正在听时可在纪要和字幕间切换,每句标出谁在说。"
+ },
+ {
+ "kind": "new",
+ "title": "Android 上可以保存会议录音,在会议记录里回放,点一句跳到那里。",
+ "text": "录音只存在这台手机上,设置里可以关。"
+ },
+ {
+ "kind": "new",
+ "title": "Android 上会议记录可以导出 Word、Markdown 和 SRT 字幕,也能复制为 Markdown。",
+ "text": ""
+ },
+ {
+ "kind": "new",
+ "title": "Android 上导入录音或视频,转成一场会议记录;也可以从别的 app 分享到知了。",
+ "text": ""
+ },
+ {
+ "kind": "new",
+ "title": "Android 上打开 Mac 认出说话人的会议记录,能看到并改说话人的名字。",
+ "text": "手机自己还分不出不同的声音。"
+ },
+ {
+ "kind": "new",
+ "title": "Android 上面对面传译改成全屏,上半屏倒过来朝着对方。",
+ "text": ""
+ },
+ {
+ "kind": "new",
+ "title": "Android 上很久没人说话时,提示并自动结束会议、整理纪要。",
+ "text": "设置里可以改成直接结束或一直记录。"
+ },
+ {
+ "kind": "fixed",
+ "title": "Android 上会议的第一句不再出现两遍。",
+ "text": ""
}
]
},