知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
feat(android): after each meeting, notes and transcript can be saved as Markdown into a folder you pick
wquguru7f22d77beb2d
diff --git a/android/README.md b/android/README.mdindex eeb41c6..65c8994 100644--- a/android/README.md+++ b/android/README.md@@ -46,7 +46,7 @@ scripts/shot.sh # 截图:悬浮窗应是黑块;capture oscripts/tap.sh "开始听" # 按屏幕上的文字点(系统对话框也行),用来走真实界面```-`cicadactl.sh` 的命令见 `app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt`(state、start、stop、feed、sample、view、capture、overlay show|hide|collapse|expand、target、ui、show main|live|records|record|settings|ai|onboarding、import、provider、ai-model(hear|text|voice|notes)、ai-base、ai-notes same|own、ai-notes-base、notes-key import|remove、ai-custom-only on|off、key import、voice-try、updatefeed、update check|download|job|notify,以及改正听错的词的 fixes on|off、asknames on|off、silent、heard、vocab add|remove|state、fixstate、fixanswer yes|no、fixrevert、fixlater、fixundo、fixedit、pinyin,分享链接的 share <id>[,full][,pw]、unshare、shares、shareSheet、delete、shareserver、clipboard)。`share` 用正式的 cicada.indaloop.app(`adb reverse tcp:<端口> tcp:<端口>` 后 `shareserver http://127.0.0.1:<端口>` 改指本机的 wrangler dev(模拟器走代理时 10.0.2.2 连不上),另用 files/share-device-local.json),设备只注册一次(files/share-device.json,别删);测试只用合成的会议记录,用完 unshare。`silent` 开一场没有声音的会,`heard <一句话>` 当作听到一整句,翻译和改词都走当前的 AI 服务,不用放声音。只有开发版有,且只接受 adb。开发版默认不检查更新(点设置里的“检查更新”或用下面的命令后才查):`cicadactl.sh push feed.json && cicadactl.sh updatefeed feed.json` 指向一份测试用的 release JSON(不带参数就是 GitHub),`adb shell cmd jobscheduler run -f com.wquguru.cicada.dev 7` 立刻跑一次后台检查。+`cicadactl.sh` 的命令见 `app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt`(state、start、stop、feed、sample、view、capture、overlay show|hide|collapse|expand、target、ui、show main|live|records|record|settings|ai|onboarding、import、provider、ai-model(hear|text|voice|notes)、ai-base、ai-notes same|own、ai-notes-base、notes-key import|remove、ai-custom-only on|off、key import、voice-try、updatefeed、update check|download|job|notify,以及改正听错的词的 fixes on|off、asknames on|off、silent、heard、vocab add|remove|state、fixstate、fixanswer yes|no、fixrevert、fixlater、fixundo、fixedit、pinyin,分享链接的 share <id>[,full][,pw]、unshare、shares、shareSheet、delete、shareserver、clipboard,存到文件夹的 export state|pick|folder <tree uri>|all|retry|off)。`export pick` 打开系统的文件夹选择器(“使用此文件夹”和“允许”可以用 `tap.sh` 点);`export folder` 只接受已经授权过的 tree URI,没授权时显示“找不到”那一行。`share` 用正式的 cicada.indaloop.app(`adb reverse tcp:<端口> tcp:<端口>` 后 `shareserver http://127.0.0.1:<端口>` 改指本机的 wrangler dev(模拟器走代理时 10.0.2.2 连不上),另用 files/share-device-local.json),设备只注册一次(files/share-device.json,别删);测试只用合成的会议记录,用完 unshare。`silent` 开一场没有声音的会,`heard <一句话>` 当作听到一整句,翻译和改词都走当前的 AI 服务,不用放声音。只有开发版有,且只接受 adb。开发版默认不检查更新(点设置里的“检查更新”或用下面的命令后才查):`cicadactl.sh push feed.json && cicadactl.sh updatefeed feed.json` 指向一份测试用的 release JSON(不带参数就是 GitHub),`adb shell cmd jobscheduler run -f com.wquguru.cicada.dev 7` 立刻跑一次后台检查。界面按 claude.ai 上的设计画布实现:首页、正在听、悬浮窗(纪要卡片 / 字幕条 / 小圆点)、三步引导、会议记录、会议详情、设置。文案用 Gemini(`google/gemini-4-argon`)审过一遍,与 Mac 共用的文案沿用 Mac 的译法。diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 2c50542..b1e0317 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -14,6 +14,17 @@<!-- The daily update check: waits for a network, and keeps its schedule across a restart. --><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />+ <!-- 存到文件夹: whether anything opens a saved Markdown file or its folder (else the link is left out). -->+ <queries>+ <intent>+ <action android:name="android.intent.action.VIEW" />+ <data android:mimeType="text/markdown" />+ </intent>+ <intent>+ <action android:name="android.intent.action.VIEW" />+ <data android:mimeType="vnd.android.document/directory" />+ </intent>+ </queries><applicationandroid:name=".CicadaApp"diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt b/android/app/src/main/kotlin/com/wquguru/cicada/App.ktindex 4acdbd9..dbe98c2 100644--- a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt+++ b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt@@ -51,6 +51,8 @@ class CicadaApp : Application() {lateinit var overlay: Overlaylateinit var voice: Voicelateinit var updates: AppUpdates+ /// 存到文件夹 (设置 › 会后存一份).+ lateinit var folderExport: FolderExporter/// 分享…: the share service on cicada.indaloop.app (Share.kt). Its version without "-dev".val share by lazy {ShareClient("android", (packageManager.getPackageInfo(packageName, 0).versionName ?: "0.0.0").substringBefore('-'))@@ -99,6 +101,7 @@ class CicadaApp : Application() {ling.proxyHint = { AiCheckViews.proxyHint(this) }watchNetwork()store = SessionStore(loadNow = false)+ folderExport = FolderExporter(this)background.execute { val t = System.currentTimeMillis(); store.load(); Log.d("store: loaded ${store.all().size} in ${System.currentTimeMillis() - t} ms") }notes = NotesEngine(ling, store)translator = Translator(ling)@@ -128,6 +131,14 @@ class CicadaApp : Application() {listen.onChange(::changed)notes.onChange(::changed)store.onChange { changed() }+ // 存到文件夹: written once a record is settled, rewritten when it changes, forgotten (not+ // deleted) with it. "" is the records read at launch: try what was waiting.+ store.onChange { id -> main.post {+ if (id.isEmpty()) folderExport.retry()+ else if (store.get(id) == null) folderExport.deleted(id) else folderExport.saved(id)+ } }+ notes.finalDone = { id -> main.post { folderExport.settled(id) } }+ main.post { folderExport.retry() } // the records may have been read before the listener was inling.onChange(::changed)registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {// Meetings are private: the recent-apps preview shows a blank card, not the transcript@@ -135,7 +146,11 @@ class CicadaApp : Application() {override fun onActivityPreCreated(a: android.app.Activity, b: android.os.Bundle?) {if (Build.VERSION.SDK_INT >= 33 && a !is ProjectionActivity) a.setRecentsScreenshotEnabled(false)}- override fun onActivityResumed(a: android.app.Activity) { resumed++; updateOverlay() }+ override fun onActivityResumed(a: android.app.Activity) {+ // Coming back from elsewhere (a grant fixed, storage back): 存到文件夹 tries again.+ if (resumed++ == 0) folderExport.retry()+ updateOverlay()+ }// Moving between Cicada's own screens pauses one before resuming the next: wait a beat.override fun onActivityPaused(a: android.app.Activity) { resumed--; main.postDelayed(::updateOverlay, 400) }override fun onActivityCreated(a: android.app.Activity, b: android.os.Bundle?) {}@@ -366,6 +381,8 @@ class CicadaApp : Application() {// The whole meeting read once more for names.recId?.let { namer.guess(it, force = true) }if (imported != null && recId != null) store.update(recId) { it.importing = null }+ // A meeting or an imported file is over: 存到文件夹 writes it once its notes are.+ recId?.let { id -> main.post { folderExport.ended(id) } }rec?.finish { ok -> if (ok && recId != null && store.get(recId) != null) store.update(recId) { it.hasAudio = true } }main.post {starting = 0diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.ktindex dec7a47..007a2db 100644--- a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt+++ b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt@@ -28,6 +28,8 @@ import java.util.concurrent.TimeUnit/// fixstate · fixanswer yes|no · fixrevert <line> · fixlater · fixundo · fixedit <line>=<text>[|one][|keep0] · pinyin <text>/// 分享…: share <id>[,full][,pw] · unshare <id> · shares · shareSheet <id> (no id: closes it) · delete <id>/// shareserver [url] (a local Worker; none: cicada.indaloop.app) · clipboard+/// 存到文件夹: export state · export folder <tree uri> (one already granted; else the problem shows) · export pick+/// (the system picker) · export all (也存一份) · export retry · export offclass DebugReceiver : BroadcastReceiver() {override fun onReceive(context: Context, intent: Intent) {if (!BuildConfig.DEBUG) return@@ -182,6 +184,20 @@ class DebugReceiver : BroadcastReceiver() {app.store.import(s)}"delete" -> app.store.delete(arg)+ // rename <id>=<title>, as typed into the record's title (empty: the automatic one).+ "rename" -> app.store.rename(arg.substringBefore('='), arg.substringAfter('=', ""))+ "export" -> {+ val ex = app.folderExport+ val rest = arg.substringAfter(' ', "")+ when (arg.substringBefore(' ')) {+ "folder" -> ex.choose(android.net.Uri.parse(rest))+ "pick" -> { SettingsActivity.pickFolder = true; open(SettingsActivity::class.java) }+ "all" -> ex.writeAll()+ "retry" -> ex.retry()+ "off" -> ex.turnOff()+ else -> return ex.debugState()+ }+ }// 分享… (the Mac's share: / unshare: / shareSheet:): `share <id>[,full][,pw]` shares as the// sheet would and logs the link; `unshare <id>` turns it off; `shares` lists them (never the token)."share" -> {diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/FolderExportViews.kt b/android/app/src/main/kotlin/com/wquguru/cicada/FolderExportViews.ktnew file mode 100644index 0000000..3dd2f95--- /dev/null+++ b/android/app/src/main/kotlin/com/wquguru/cicada/FolderExportViews.kt@@ -0,0 +1,133 @@+package com.wquguru.cicada++import android.app.Activity+import android.content.Intent+import android.provider.DocumentsContract+import android.view.View+import android.widget.LinearLayout+import cicada.Log+import cicada.Session+import cicada.Strings+import cicada.Strings.L+import cicada.Strings.LF++/// 设置 › 会后存一份 and the record's line under its title (the Mac's FolderExportViews.swift).+/// There is no default folder on a phone: the system's folder picker chooses, and its grant is kept.+object FolderExportViews {+ const val PICK = 41++ /// The section: label, card, and the grey 上次存于 line under it.+ fun section(activity: Activity, ui: Ui, page: LinearLayout) {+ val ex = activity.cicada.folderExport+ page.addView(ui.sectionLabel(L("会后存一份")))+ val rows = mutableListOf<View>(ui.switchRow(L("存到文件夹"), L("纪要和文字记录存成 Markdown;文件夹同步到哪,内容就到哪"), ex.on) { on ->+ when {+ !on -> ex.turnOff()+ // A folder chosen before whose grant still holds: on again, as on the Mac.+ ex.tree?.let { t -> activity.contentResolver.persistedUriPermissions.any { it.uri == t && it.isWritePermission } } == true -> ex.choose(ex.tree!!)+ else -> pick(activity)+ }+ })+ if (ex.on) {+ if (ex.checking) rows.add(ui.listRow(LF("正在确认能写入 %@…", ex.shortPath), chevron = false))+ else ex.problem?.let { rows.add(problemRow(activity, ui, it)) }+ val buttons = ui.row(4).apply {+ if (ex.vault) addView(ui.badge(L("Obsidian 库"), fg = Palette.body, bg = Palette.ground))+ ex.openFolderIntent()?.let { open -> addView(ui.textButton(L("打开")) { activity.startActivity(open) }) }+ addView(ui.textButton(L("更改…")) { pick(activity) })+ }+ rows.add(ui.listRow(L("位置"), ex.shortPath, trailing = buttons, chevron = false))+ val left = ex.unwritten.size+ if (left > 0) rows.add(ui.listRow(L("以前的会议"), LF("还有 %lld 场没存", left), trailing = ui.textButton(L("也存一份")) { ex.writeAll() }, chevron = false))+ }+ page.addView(ui.group(rows))+ val last = ex.index.lastFile+ val at = ex.index.lastAt+ if (ex.on && last != null && at != null) {+ val pattern = android.text.format.DateFormat.getBestDateTimePattern(Strings.locale, "MMMdHHmm")+ val time = java.time.format.DateTimeFormatter.ofPattern(pattern, Strings.locale).withZone(java.time.ZoneId.systemDefault()).format(at)+ page.addView(ui.helper(LF("上次存于 %@ · %@", time, last), Palette.tertiary).apply {+ maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.MIDDLE+ setPadding(ui.dp(16), ui.dp(6), ui.dp(16), 0)+ })+ }+ }++ /// A lost grant and a folder that is gone look the same from here: 找不到, and 重新选.+ private fun problemRow(activity: Activity, ui: Ui, problem: FolderExporter.Problem): View {+ val ex = activity.cicada.folderExport+ val box = ui.stack(2).apply { setPadding(ui.dp(12), ui.dp(10), ui.dp(12), ui.dp(10)) }+ val texts = ui.stack(2)+ when (problem) {+ FolderExporter.Problem.Failed -> {+ texts.addView(ui.text(L("没存上"), 15f, Palette.ink, bold = true))+ ex.problemText?.let { texts.addView(ui.helper(it).apply { maxLines = 2 }) }+ }+ else -> {+ texts.addView(ui.text(LF("找不到 %@", ex.shortPath), 15f, Palette.ink, bold = true))+ if (problem == FolderExporter.Problem.Missing) texts.addView(ui.helper(L("接上或换个文件夹后自动补存")))+ }+ }+ val line = ui.row(8, texts.apply { layoutParams = ui.weight() }, ui.textButton(L("重新选")) { pick(activity) })+ box.addView(line)+ box.background = ui.rounded(if (problem == FolderExporter.Problem.Denied) Palette.accentPale else Palette.ground, 12)+ return LinearLayout(activity).apply {+ setPadding(ui.dp(10), ui.dp(8), ui.dp(10), ui.dp(8))+ addView(box, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT))+ }+ }++ /// The system's folder picker, starting at Documents (or the folder in use).+ fun pick(activity: Activity) {+ val start = activity.cicada.folderExport.tree?.let { DocumentsContract.buildDocumentUriUsingTree(it, DocumentsContract.getTreeDocumentId(it)) }+ ?: DocumentsContract.buildDocumentUri("com.android.externalstorage.documents", "primary:Documents")+ val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)+ .putExtra(DocumentsContract.EXTRA_INITIAL_URI, start)+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)+ try {+ @Suppress("DEPRECATION")+ activity.startActivityForResult(intent, PICK)+ } catch (e: Exception) { Log.d("folder export: no folder picker ${e.javaClass.simpleName}") }+ }++ /// The picker's answer: the grant kept, the folder chosen. Cancelled: the switch stays (or goes back) off.+ fun picked(activity: Activity, resultCode: Int, data: Intent?) {+ val uri = data?.data+ if (resultCode != Activity.RESULT_OK || uri == null) { activity.cicada.changed(); return }+ try {+ activity.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)+ } catch (e: Exception) { Log.d("folder export: grant not kept ${e.javaClass.simpleName}") }+ activity.cicada.folderExport.choose(uri)+ }++ /// The record's grey line: where its file is, or why it isn't there yet. Null when there is+ /// nothing to say (off, or the record isn't settled).+ fun recordLine(activity: Activity, ui: Ui, s: Session): View? {+ val ex = activity.cicada.folderExport+ if (!ex.on || !ex.ready(s)) return null+ fun note(text: String) = ui.text(text, 12f, Palette.tertiary, lines = 1)+ fun link(text: String, run: () -> Unit) = ui.text(text, 12f, Palette.link, bold = true, lines = 1).apply {+ setPadding(ui.dp(4), ui.dp(8), ui.dp(4), ui.dp(8))+ ui.tappable(this, 8, onClick = run)+ }+ val pending = ex.isPending(s.id)+ val row = LinearLayout(activity).apply { orientation = LinearLayout.HORIZONTAL; gravity = android.view.Gravity.CENTER_VERTICAL }+ when {+ !pending && ex.file(s.id) != null -> {+ val reveal = ex.revealIntent(s.id)+ // Nothing opens Markdown here: the line ends at the folder.+ row.addView(note(LF("已存到 %@ ·", ex.shortPath).let { if (reveal == null) it.removeSuffix("·").trimEnd() else it }))+ if (reveal != null) row.addView(link(L("打开")) {+ try { activity.startActivity(reveal) } catch (e: Exception) { Log.d("folder export: reveal failed ${e.javaClass.simpleName}") }+ })+ }+ pending && ex.problem != null -> {+ row.addView(note(L("没存到文件夹 ·")))+ row.addView(link(L("去设置")) { activity.startActivity(Intent(activity, SettingsActivity::class.java)) })+ }+ pending -> row.addView(note(LF("整理好后存到 %@", ex.shortPath)))+ else -> return null+ }+ return row+ }+}diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/FolderExporter.kt b/android/app/src/main/kotlin/com/wquguru/cicada/FolderExporter.ktnew file mode 100644index 0000000..655d5c6--- /dev/null+++ b/android/app/src/main/kotlin/com/wquguru/cicada/FolderExporter.kt@@ -0,0 +1,394 @@+package com.wquguru.cicada++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.ContentResolver+import android.content.Intent+import android.net.Uri+import android.provider.DocumentsContract+import android.provider.DocumentsContract.Document+import cicada.FolderExportFormat+import cicada.FolderExportIndex+import cicada.Log+import cicada.Paths+import cicada.Session+import cicada.Strings.L+import cicada.Strings.LF+import java.io.File+import java.time.Instant+import java.util.concurrent.Executors++/// 存到文件夹 (docs/folder-export.md, the Mac's FolderExporter): writes settled meetings as Markdown+/// into the folder the user picked (a SAF tree, held by a persisted grant) and keeps the index of+/// what it wrote. State lives on the main thread; the files are written one at a time on its own+/// thread, through DocumentsContract, since a provider may be slow or remote.+class FolderExporter(private val app: CicadaApp) {+ enum class Problem {+ /// The grant is gone (the user revoked it, or the app was restored without it).+ Denied,+ /// The folder, or the storage it was on, is gone.+ Missing,+ Failed,+ }++ var index: FolderExportIndex; private set+ var problem: Problem? = null; private set+ /// Failed's provider message.+ var problemText: String? = null; private set+ /// Checking a newly chosen folder.+ var checking = false; private set+ /// The folder is an Obsidian vault itself (it has `.obsidian`): the 位置 row says so.+ var vault = false; private set++ private val settings get() = app.settings+ private val store get() = app.store+ private val indexFile = File(Paths.root, "FolderExport.json")+ private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "FolderExport").apply { isDaemon = true } }+ private var scheduled: Runnable? = null+ /// Told about this problem already (cleared once a write works).+ private var notified = false++ init { index = FolderExportIndex.load(indexFile) }++ val on get() = settings.exportOn && settings.exportFolder.isNotEmpty()+ val tree: Uri? get() = settings.exportFolder.takeIf { it.isNotEmpty() }?.let(Uri::parse)++ /// "Documents › Cicada": the folder and the one it is in, named when it was chosen.+ val shortPath: String get() = settings.exportName.ifEmpty { "Cicada" }++ /// The record's file, when it is written to this folder.+ fun file(id: String): Uri? {+ if (!on || index.folder != settings.exportFolder || index.files[id] == null) return null+ return index.uris[id]?.let(Uri::parse)+ }++ fun isPending(id: String) = on && id in index.pending++ /// Ended, not being imported, with something said.+ fun ready(s: Session) = s.endedAt != null && s.importing != true && s.lines.isNotEmpty() && s.id != store.liveId++ /// Settled records not written to this folder yet.+ val unwritten: List<Session> get() = store.all().filter { ready(it) && index.files[it.id] == null && it.id !in index.pending }++ /// What the screens' keys compare, so they rebuild when any of it changes.+ fun stateKey(): String = listOf(on, settings.exportName, problem, problemText, checking, vault, index.pending.size, index.files.size, index.lastAt, unwritten.size).joinToString("|")++ // MARK: Triggers (main thread)++ /// A meeting ended or an import finished: write it once it is settled.+ fun ended(id: String) {+ if (!on) return+ if (id !in index.pending) index.pending.add(id)+ saveIndex()+ schedule()+ }++ /// A record changed: rewrite it if it was written, or write it if it is waiting.+ fun saved(id: String) {+ if (!on || (index.files[id] == null && id !in index.pending)) return+ if (id !in index.pending) index.pending.add(id)+ schedule()+ }++ /// The final notes pass for a meeting is over (done, failed, or no key).+ fun settled(id: String) { if (on && id in index.pending) schedule() }++ /// 也存一份: every settled record not written yet.+ fun writeAll() {+ if (!on) return+ index.pending.addAll(unwritten.map { it.id })+ saveIndex()+ flush(fromMeeting = false)+ }++ /// At launch (once the records are read) and when the app comes forward: try what is waiting.+ fun retry() {+ if (!on || index.pending.isEmpty() || !store.loaded) return+ schedule(500, fromMeeting = false)+ }++ /// The record is gone from Cicada; its file stays.+ fun deleted(id: String) {+ if (index.files.remove(id) == null && !index.pending.remove(id)) return+ index.uris.remove(id)+ saveIndex()+ }++ // MARK: Choosing the folder++ /// A new folder (its grant already taken), or the same one again: start its index and check it+ /// can be written now, so a problem shows while settings is open, not when a meeting ends.+ fun choose(folder: Uri) {+ val text = folder.toString()+ if (settings.exportFolder.isNotEmpty() && settings.exportFolder != text) release(Uri.parse(settings.exportFolder))+ settings.exportFolder = text+ settings.exportOn = true+ settings.save()+ if (index.folder != text) index = FolderExportIndex(folder = text)+ saveIndex()+ checking = true+ problem = null; problemText = null+ app.changed()+ val resolver = app.contentResolver+ worker.execute {+ val name = Saf.shortPath(resolver, folder)+ val result = Saf.probe(app, folder)+ val isVault = result.problem == null && Saf.children(resolver, folder).containsKey(".obsidian")+ app.main.post {+ if (settings.exportFolder != text) return@post+ checking = false+ problem = result.problem; problemText = result.message+ vault = isVault+ if (name != null) { settings.exportName = name; settings.save() }+ if (problem == null) { notified = false; retry() }+ Log.d("folder export: chose a folder → ${problem ?: "ok"}")+ app.changed()+ }+ }+ }++ fun turnOff() {+ settings.exportOn = false+ settings.save()+ problem = null; problemText = null+ app.changed()+ }++ /// The folder Cicada writes in no longer: its grant goes back (an app holds at most 128 or 512).+ private fun release(old: Uri) {+ try { app.contentResolver.releasePersistableUriPermission(old, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) } catch (_: Exception) {}+ }++ /// The folder in the Files app, if anything opens a folder.+ fun openFolderIntent(): Intent? {+ val t = tree ?: return null+ val doc = DocumentsContract.buildDocumentUriUsingTree(t, DocumentsContract.getTreeDocumentId(t))+ return Intent(Intent.ACTION_VIEW).setDataAndType(doc, Document.MIME_TYPE_DIR)+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)+ .takeIf { it.resolveActivity(app.packageManager) != null }+ }++ /// The record's file in a Markdown viewer, or null when nothing opens text/markdown.+ fun revealIntent(id: String): Intent? {+ val uri = file(id) ?: return null+ return Intent(Intent.ACTION_VIEW).setDataAndType(uri, "text/markdown")+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)+ .takeIf { it.resolveActivity(app.packageManager) != null }+ }++ // MARK: Writing++ private fun schedule(delay: Long = 2000, fromMeeting: Boolean = true) {+ scheduled?.let(app.main::removeCallbacks)+ val work = Runnable { flush(fromMeeting) }+ scheduled = work+ app.main.postDelayed(work, delay)+ }++ private class Job(val id: String, val stem: String, val old: String?, val oldUri: String?, val text: String)++ private sealed class Outcome {+ class Wrote(val id: String, val name: String, val uri: String) : Outcome()+ class Unchanged(val id: String) : Outcome()+ class Stopped(val problem: Problem, val message: String? = null) : Outcome()+ }++ /// Renders what is settled here, writes it on the worker.+ private fun flush(fromMeeting: Boolean) {+ val folder = tree+ if (!on || folder == null || !store.loaded) return+ val text = folder.toString()+ if (index.folder != text) index = FolderExportIndex(folder = text, pending = index.pending)+ val jobs = mutableListOf<Job>()+ for (id in index.pending.toList()) {+ val s = store.get(id) ?: run { index.pending.remove(id); null } ?: continue+ if (!ready(s) || app.notes.settling(id)) continue+ jobs.add(Job(id, FolderExportFormat.stem(s), index.files[id], index.uris[id], FolderExportFormat.document(s)))+ }+ saveIndex()+ if (jobs.isEmpty()) return+ val ours = HashMap(index.files)+ val resolver = app.contentResolver+ worker.execute {+ val outcomes = write(resolver, folder, jobs, ours)+ app.main.post { apply(outcomes, text, fromMeeting) }+ }+ }++ private fun apply(outcomes: List<Outcome>, folder: String, fromMeeting: Boolean) {+ if (index.folder != folder) return+ var stopped: Outcome.Stopped? = null+ for (o in outcomes) when (o) {+ is Outcome.Wrote -> {+ index.files[o.id] = o.name; index.uris[o.id] = o.uri+ index.pending.remove(o.id)+ index.lastFile = o.name; index.lastAt = Instant.now()+ }+ is Outcome.Unchanged -> index.pending.remove(o.id)+ is Outcome.Stopped -> stopped = o+ }+ saveIndex()+ problem = stopped?.problem; problemText = stopped?.message+ Log.d("folder export: ${outcomes.count { it is Outcome.Wrote }} written, ${outcomes.count { it is Outcome.Unchanged }} unchanged${stopped?.let { ", stopped: ${it.problem}" } ?: ""}")+ if (stopped == null) notified = false+ // A lost grant is told once after a meeting (never for 也存一份); a missing folder never.+ if (stopped?.problem == Problem.Denied && fromMeeting && !notified) { notified = true; notifyDenied() }+ app.changed()+ }++ /// On the worker. Stops at the first problem: the rest would fail the same way.+ private fun write(resolver: ContentResolver, folder: Uri, jobs: List<Job>, ours: MutableMap<String, String>): List<Outcome> {+ Saf.access(app, folder)?.let { return listOf(Outcome.Stopped(it)) }+ val out = mutableListOf<Outcome>()+ try {+ // Child queries ignore a selection on most providers: list once, match names here.+ val listing = Saf.children(resolver, folder)+ val parent = Saf.root(folder)+ for (job in jobs) {+ val mine = ours.filterKeys { it != job.id }.values.toSet()+ val name = FolderExportFormat.fileName(job.stem) { c -> c != job.old && (c in mine || c in listing) }+ // The stored URI is a hint; a path-based provider gives a renamed file a new one.+ val existing = job.old?.let { listing[it] }+ val doc: Uri+ if (existing != null && name == job.old) {+ if (Saf.read(resolver, existing) == job.text) { out.add(Outcome.Unchanged(job.id)); continue }+ Saf.write(resolver, existing, job.text)+ doc = existing+ } else if (existing != null) {+ // A new name moves the file: renamed in place, else written anew and the old one deleted.+ val renamed = try { DocumentsContract.renameDocument(resolver, existing, name) } catch (e: SecurityException) { throw e } catch (_: Exception) { null }+ if (renamed != null) {+ listing.remove(job.old); doc = renamed+ Saf.write(resolver, doc, job.text)+ } else {+ doc = Saf.create(resolver, parent, name)+ Saf.write(resolver, doc, job.text)+ try { DocumentsContract.deleteDocument(resolver, existing) } catch (e: SecurityException) { throw e } catch (_: Exception) {}+ listing.remove(job.old)+ }+ } else {+ doc = Saf.create(resolver, parent, name)+ Saf.write(resolver, doc, job.text)+ }+ // SAF may have named it otherwise (a collision it saw, an extension it added).+ val actual = Saf.displayName(resolver, doc) ?: name+ listing[actual] = doc+ ours[job.id] = actual+ out.add(Outcome.Wrote(job.id, actual, doc.toString()))+ }+ } catch (e: SecurityException) {+ out.add(Outcome.Stopped(Problem.Denied))+ } catch (e: Exception) {+ out.add(if (Saf.displayName(resolver, Saf.root(folder)) == null) Outcome.Stopped(Problem.Missing)+ else Outcome.Stopped(Problem.Failed, e.message ?: e.javaClass.simpleName))+ }+ return out+ }++ private fun saveIndex() = index.save(indexFile)++ private fun notifyDenied() {+ val nm = app.getSystemService(NotificationManager::class.java)+ nm.createNotificationChannel(NotificationChannel(CHANNEL, L("存到文件夹"), NotificationManager.IMPORTANCE_DEFAULT))+ val open = PendingIntent.getActivity(app, 20, Intent(app, SettingsActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)+ val n = Notification.Builder(app, CHANNEL)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(L("纪要没存到文件夹"))+ .setContentText(LF("知了没有权限写入 %@。点按去设置", shortPath))+ .setStyle(Notification.BigTextStyle().bigText(LF("知了没有权限写入 %@。点按去设置", shortPath)))+ .setContentIntent(open)+ .setAutoCancel(true)+ .build()+ try { nm.notify(NOTIFICATION, n); Log.d("folder export: notified denied") } catch (e: Exception) { Log.d("folder export: notification not shown ${e.javaClass.simpleName}") }+ }++ /// The debug command's view (`export state`): no meeting text, only names and counts.+ fun debugState(): Map<String, Any?> = mapOf(+ "on" to on, "folder" to settings.exportFolder, "short" to shortPath, "problem" to problem?.name, "message" to problemText,+ "checking" to checking, "vault" to vault, "files" to index.files.toSortedMap(), "pending" to index.pending.toList(),+ "unwritten" to unwritten.size, "lastFile" to index.lastFile, "lastAt" to index.lastAt?.toString(),+ "grants" to app.contentResolver.persistedUriPermissions.map { it.uri.toString() },+ )++ companion object {+ const val NOTIFICATION = 3+ private const val CHANNEL = "folder"+ }+}++/// The Storage Access Framework calls 存到文件夹 makes, on the exporter's worker thread.+object Saf {+ class Probe(val problem: FolderExporter.Problem?, val message: String? = null)++ /// The tree's own document.+ fun root(tree: Uri): Uri = DocumentsContract.buildDocumentUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree))++ /// The grant first (cheap and certain), then whether the folder still answers.+ fun access(app: CicadaApp, tree: Uri): FolderExporter.Problem? {+ val granted = app.contentResolver.persistedUriPermissions.any { it.uri == tree && it.isWritePermission }+ if (!granted) return FolderExporter.Problem.Denied+ return try {+ if (displayName(app.contentResolver, root(tree)) == null) FolderExporter.Problem.Missing else null+ } catch (_: SecurityException) { FolderExporter.Problem.Denied }+ }++ /// Writes and deletes a hidden file: the check after choosing a folder.+ fun probe(app: CicadaApp, tree: Uri): Probe {+ access(app, tree)?.let { return Probe(it) }+ val r = app.contentResolver+ return try {+ // octet-stream: a provider adds no extension to a name it has no type for.+ val doc = DocumentsContract.createDocument(r, root(tree), "application/octet-stream", ".cicada-check") ?: throw IllegalStateException("not created")+ try { DocumentsContract.deleteDocument(r, doc) } catch (_: Exception) {}+ Probe(null)+ } catch (_: SecurityException) { Probe(FolderExporter.Problem.Denied) }+ catch (e: Exception) { Probe(FolderExporter.Problem.Failed, e.message ?: e.javaClass.simpleName) }+ }++ /// The folder's files by name.+ fun children(r: ContentResolver, tree: Uri): MutableMap<String, Uri> {+ val out = HashMap<String, Uri>()+ val uri = DocumentsContract.buildChildDocumentsUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree))+ r.query(uri, arrayOf(Document.COLUMN_DOCUMENT_ID, Document.COLUMN_DISPLAY_NAME), null, null, null)?.use { c ->+ while (c.moveToNext()) {+ val id = c.getString(0) ?: continue+ val name = c.getString(1) ?: continue+ out[name] = DocumentsContract.buildDocumentUriUsingTree(tree, id)+ }+ } ?: throw java.io.FileNotFoundException("no listing")+ return out+ }++ /// Null when the provider doesn't answer: the document (or folder) is gone.+ fun displayName(r: ContentResolver, doc: Uri): String? = try {+ r.query(doc, arrayOf(Document.COLUMN_DISPLAY_NAME), null, null, null)?.use { c -> if (c.moveToFirst()) c.getString(0) else null }+ } catch (e: SecurityException) { throw e } catch (_: Exception) { null }++ fun create(r: ContentResolver, parent: Uri, name: String): Uri =+ DocumentsContract.createDocument(r, parent, "text/markdown", name) ?: throw java.io.IOException("not created")++ fun read(r: ContentResolver, doc: Uri): String? = try {+ r.openInputStream(doc)?.use { it.readBytes().toString(Charsets.UTF_8) }+ } catch (e: SecurityException) { throw e } catch (_: Exception) { null }++ /// No atomic replace in SAF, so the caller skips unchanged text. "wt" truncates; "w" only for a+ /// provider that rejects "wt" (most providers truncate on "w" too).+ fun write(r: ContentResolver, doc: Uri, text: String) {+ val bytes = text.toByteArray(Charsets.UTF_8)+ val stream = try { r.openOutputStream(doc, "wt") } catch (e: SecurityException) { throw e } catch (_: IllegalArgumentException) { null }+ ?: r.openOutputStream(doc, "w") ?: throw java.io.IOException("not writable")+ stream.use { it.write(bytes) }+ }++ /// "Documents › Cicada": the tree's display name, and its parent's from the document id when+ /// the provider uses paths (external storage: "primary:Documents/Cicada").+ fun shortPath(r: ContentResolver, tree: Uri): String? {+ val name = try { displayName(r, root(tree)) } catch (_: Exception) { null } ?: return null+ val path = DocumentsContract.getTreeDocumentId(tree).substringAfter(':', "")+ val parent = path.trimEnd('/').split('/').dropLast(1).lastOrNull()?.takeIf { it.isNotEmpty() }+ return if (parent != null) "$parent › $name" else name+ }+}diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.ktindex 434cecd..d7c8203 100644--- a/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt+++ b/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt@@ -275,7 +275,7 @@ class RecordActivity : Activity() {if (!file) releasePlayer() else if (player == null && !broken) broken = ensurePlayer() == nullval playable = file && !brokenval 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, live, s.hasAudio, playable, app.settings.recordAudio, app.store.lines(id).sumOf { it.fixes?.hashCode() ?: 0 }, app.fixes.pending(id).size).joinToString("|")+ s.voiceNames, app.settings.speakerVoices, live, s.hasAudio, playable, app.settings.recordAudio, app.store.lines(id).sumOf { it.fixes?.hashCode() ?: 0 }, app.fixes.pending(id).size, app.folderExport.stateKey(), app.folderExport.file(id), app.folderExport.isPending(id)).joinToString("|")if (key == shown) returnshown = keyval top = ui.stack(0).apply { setPadding(ui.dp(20), ui.dp(4), ui.dp(20), ui.dp(6)) }@@ -289,6 +289,8 @@ class RecordActivity : Activity() {s.sourceFile?.let { L("导入") }).joinToString(" · ")top.addView(ui.text(meta, 13f, Palette.secondary), ui.lp(top = 6))recordingNote(s, live, file, playable)?.let { top.addView(it, ui.lp(top = 6)) }+ // 存到文件夹: where its file is, or why it isn't there yet.+ if (!live) FolderExportViews.recordLine(this, ui, s)?.let { top.addView(it, ui.lp(top = 2)) }speakerChips(s)?.let { top.addView(it, ui.lp(top = 14)) }val tabLabels = listOf(L("纪要"), "${L("文字记录")} · ${LF("%lld 句", s.lines.size)}")val tabs = ui.tabs(tabLabels, tab) { tab = it; render() }diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.ktindex 89f6e76..4eea6ac 100644--- a/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt+++ b/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt@@ -35,7 +35,9 @@ class SettingsActivity : Activity() {private var builtTitle = ""// Brought back to the front by the nav, so rebuild if the language changed meanwhile.- override fun onResume() { super.onResume(); if (L("设置") != builtTitle) { recreate(); return }; unobserve = cicada.observe(::build); shown = null; build() }+ override fun onResume() { super.onResume(); if (L("设置") != builtTitle) { recreate(); return }; unobserve = cicada.observe(::build); shown = null; build()+ if (pickFolder) { pickFolder = false; FolderExportViews.pick(this) }+ }override fun onPause() { super.onPause(); unobserve?.invoke(); unobserve = null }private fun value(text: String) = ui.text(text, 15f, Palette.secondary, lines = 1)@@ -43,7 +45,7 @@ class SettingsActivity : Activity() {private fun build() {val app = cicadaval s = app.settings- val key = listOf(app.ling.keyState, app.ling.currentKey()?.takeLast(4), app.ling.aiCheck.summary, s.toJson(), app.canOverlay, Strings.language, app.updates.available?.version, app.updates.manual, app.vocabulary.terms.size).joinToString("|")+ val key = listOf(app.ling.keyState, app.ling.currentKey()?.takeLast(4), app.ling.aiCheck.summary, s.toJson(), app.canOverlay, Strings.language, app.updates.available?.version, app.updates.manual, app.vocabulary.terms.size, app.folderExport.stateKey()).joinToString("|")if (key == shown) returnshown = keypage.removeAllViews()@@ -104,6 +106,9 @@ class SettingsActivity : Activity() {"${s.silenceMinutes.toInt()}") { s.silenceMinutes = it.toDouble(); app.saveSettings() })page.addView(ui.group(endRows))+ // 会后存一份: 存到文件夹 (FolderExportViews), as the Mac's 设置 › 通用.+ FolderExportViews.section(this, ui, page)+page.addView(ui.sectionLabel(L("其他")))page.addView(ui.group(listOf(ui.listRow(L("导入录音或视频"), L("转成一场会议记录")) { startActivity(Intent(this, ImportActivity::class.java)) },@@ -115,6 +120,11 @@ class SettingsActivity : Activity() {page.addView(ui.helper("${L("知了")} $version · Android").apply { gravity = Gravity.CENTER; setPadding(0, ui.dp(20), 0, 0) })}+ @Deprecated("Deprecated in Java")+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {+ if (requestCode == FolderExportViews.PICK) { shown = null; FolderExportViews.picked(this, resultCode, data) }+ }+/// 检查更新: its answer on the right; with a new version found, tapping it downloads that.private fun updateRow(): View {val u = cicada.updates@@ -158,6 +168,9 @@ class SettingsActivity : Activity() {}companion object {+ /// Debug (`export pick`): open the folder picker once settings is in front.+ var pickFolder = false+fun paste(box: android.widget.EditText) {val clip = box.context.getSystemService(ClipboardManager::class.java).primaryClipval text = clip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.coerceToText(box.context)?.toString()?.trim()diff --git a/android/app/src/main/strings/en.lproj/Android.strings b/android/app/src/main/strings/en.lproj/Android.stringsindex 4dc5109..9d587fc 100644--- a/android/app/src/main/strings/en.lproj/Android.strings+++ b/android/app/src/main/strings/en.lproj/Android.strings@@ -225,3 +225,4 @@"例如 af_heart" = "e.g. af_heart";"最多 %lld 个,满了优先用最近的。只存在这台手机上" = "Up to %lld, recent ones first. Stored only on this phone";"点一下改写法" = "Tap to change the spelling";+"重新选" = "Choose again";diff --git a/android/app/src/main/strings/ja.lproj/Android.strings b/android/app/src/main/strings/ja.lproj/Android.stringsindex a6f8ea7..1a80643 100644--- a/android/app/src/main/strings/ja.lproj/Android.strings+++ b/android/app/src/main/strings/ja.lproj/Android.strings@@ -225,3 +225,4 @@"例如 af_heart" = "例: af_heart";"最多 %lld 个,满了优先用最近的。只存在这台手机上" = "最大 %lld 個、最近使ったものを優先。このスマホにだけ保存";"点一下改写法" = "タップして表記を変更";+"重新选" = "選び直す";diff --git a/android/app/src/main/strings/ko.lproj/Android.strings b/android/app/src/main/strings/ko.lproj/Android.stringsindex cc2a3dd..fb6ed2d 100644--- a/android/app/src/main/strings/ko.lproj/Android.strings+++ b/android/app/src/main/strings/ko.lproj/Android.strings@@ -225,3 +225,4 @@"例如 af_heart" = "예: af_heart";"最多 %lld 个,满了优先用最近的。只存在这台手机上" = "최대 %lld개, 최근 것을 우선. 이 휴대전화에만 저장";"点一下改写法" = "탭해서 표기 바꾸기";+"重新选" = "다시 선택";diff --git a/android/cli/src/main/kotlin/cicada/cli/FolderExportTests.kt b/android/cli/src/main/kotlin/cicada/cli/FolderExportTests.ktnew file mode 100644index 0000000..75181dd--- /dev/null+++ b/android/cli/src/main/kotlin/cicada/cli/FolderExportTests.kt@@ -0,0 +1,99 @@+// 存到文件夹: the Mac's FolderExportTests. The file name and frontmatter are a contract with the Mac+// and the other ports (Tests/fixtures/folder-export): the same record gives the same bytes.+package cicada.cli++import cicada.*+import java.io.File+import java.time.ZoneId++object FolderExportTests {+ val tests: List<Pair<String, () -> Unit>> = listOf(+ "folderExportFrontmatterBytes" to ::frontmatterBytes,+ "folderExportFileName" to ::fileName,+ "folderExportNames" to ::names,+ "folderExportStems" to ::stems,+ "folderExportEscapes" to ::escapes,+ "folderExportCollisions" to ::collisions,+ "folderExportNamePrecedence" to ::namePrecedence,+ "folderExportIndexRoundTrip" to ::indexRoundTrip,+ "folderExportWaitsForTheFinalNotes" to ::waitsForTheFinalNotes,+ )++ private fun check(ok: Boolean, what: String) { if (!ok) throw AssertionError(what) }+ private fun <T> equal(expected: T, actual: T, what: String) { if (expected != actual) throw AssertionError("$what: expected «$expected», got «$actual»") }++ private val fixtures get() = File(resources, "../Tests/fixtures/folder-export")+ private fun session() = Session.read(File(fixtures, "session.json").readText())!!+ private fun cases() = Json.parseObject(File(fixtures, "cases.json").readText())!!+ private fun zone() = ZoneId.of(cases()["timeZone"].str()!!)+ private fun pairs(key: String) = cases()[key].arr().map { p -> p.arr().map { it.str()!! } }++ private fun frontmatterBytes() {+ val want = File(fixtures, "frontmatter.md").readText()+ equal(want, FolderExportFormat.frontmatter(session(), zone()), "frontmatter")+ }++ private fun fileName() {+ val stem = FolderExportFormat.stem(session(), zone())+ equal(cases()["fileName"].str(), FolderExportFormat.fileName(stem) { false }, "file name")+ }++ private fun names() { for ((from, want) in pairs("names")) equal(want, FolderExportFormat.safeName(from), "safe name of «$from»") }++ private fun stems() {+ val s = session()+ for ((title, want) in pairs("stems")) { s.title = title; equal(want, FolderExportFormat.stem(s, zone()), "stem of «$title»") }+ }++ private fun escapes() { for ((from, want) in pairs("escapes")) equal(want, FolderExportFormat.quote(from), "quote of «$from»") }++ private fun collisions() {+ for (c in cases()["collisions"].arr()) {+ val o = c.obj()!!+ val taken = o["taken"].arr().map { it.str()!! }+ equal(o["want"].str(), FolderExportFormat.fileName(o["stem"].str()!!) { it in taken }, "collision of ${taken.size}")+ }+ }++ /// The name: the user's title, else the notes', else the imported file's, never the display title.+ private fun namePrecedence() {+ val s = session()+ s.renamed = false+ s.title = SessionStore.defaultTitle(s.startedAt)+ equal("产品路线评审", FolderExportFormat.name(s), "the notes' title")+ s.notes = null+ equal("", FolderExportFormat.name(s), "nothing")+ s.sourceFile = "Weekly sync.m4a"+ equal("Weekly sync", FolderExportFormat.name(s), "the file's name")+ check(FolderExportFormat.frontmatter(s).contains("source: \"file\"\nnotes: \"none\""), "an imported file without notes")+ }++ private fun indexRoundTrip() {+ val file = File(Paths.root, "FolderExport.json")+ val i = FolderExportIndex(folder = "content://com.android.externalstorage.documents/tree/primary%3ADocuments%2FCicada")+ i.files["a"] = "2026-11-06 1400 周会.md"; i.uris["a"] = "content://x/document/1"; i.pending.add("b")+ i.lastFile = "2026-11-06 1400 周会.md"; i.lastAt = java.time.Instant.parse("2026-11-06T06:00:00Z")+ i.save(file)+ val back = FolderExportIndex.load(file)+ equal(Json.write(i.toJson()), Json.write(back.toJson()), "index")+ check(FolderExportIndex.load(File(Paths.root, "none.json")).folder.isEmpty(), "no index: an empty one")+ }++ /// Settled means the final notes pass is over: it counts as running from the meeting's start+ /// until finish() is done, and says so when it ends without a key.+ private fun waitsForTheFinalNotes() {+ val store = SessionStore(loadNow = false)+ val ling = LingClient(AIKey(PlainProtector, File(Paths.root, "no-key")))+ val notes = NotesEngine(ling, store)+ val done = mutableListOf<String>()+ notes.finalDone = { done.add(it) }+ val s = store.begin()+ store.append(s.id, TranscriptLine(id = "h1-1", src = "hi", srcLang = "en"))+ notes.begin(s.id)+ check(notes.settling(s.id), "settling while the meeting runs and until finish()")+ store.end(s.id)+ notes.finish()+ check(!notes.settling(s.id), "settled after finish()")+ equal(listOf(s.id), done, "finalDone without a key")+ }+}diff --git a/android/cli/src/main/kotlin/cicada/cli/Tests.kt b/android/cli/src/main/kotlin/cicada/cli/Tests.ktindex 2dd7ba6..7c485b6 100644--- a/android/cli/src/main/kotlin/cicada/cli/Tests.kt+++ b/android/cli/src/main/kotlin/cicada/cli/Tests.kt@@ -92,7 +92,7 @@ object Tests {"notesPromptNamesTheVoices" to ::notesPromptNamesTheVoices,"aHalfSentenceJoinsOnlyTheSameVoice" to ::aHalfSentenceJoinsOnlyTheSameVoice,"slowVoiceprintsNeverHoldSubtitlesBack" to ::slowVoiceprintsNeverHoldSubtitlesBack,- ) + ProviderTests.tests + AICheckTests.tests + FixTests.tests + ShareTests.tests+ ) + ProviderTests.tests + AICheckTests.tests + FixTests.tests + ShareTests.tests + FolderExportTests.testsvar passed = 0; var failed = 0for ((name, test) in tests) {try { test(); passed++ } catch (e: Throwable) { failed++; println("FAIL $name: ${e.message ?: e.javaClass.simpleName}") }diff --git a/android/core/src/main/kotlin/cicada/FolderExport.kt b/android/core/src/main/kotlin/cicada/FolderExport.ktnew file mode 100644index 0000000..a8dc9de--- /dev/null+++ b/android/core/src/main/kotlin/cicada/FolderExport.kt@@ -0,0 +1,150 @@+package cicada++import java.io.File+import java.time.Instant+import java.time.ZoneId+import java.time.format.DateTimeFormatter+import java.util.Locale++/// 存到文件夹: the file a settled meeting becomes (docs/folder-export.md, the Mac's+/// FolderExport.swift). The name and frontmatter are a contract with the Mac and the other ports+/// (Tests/fixtures/folder-export); the body is 导出 Markdown's. The app writes it through SAF.+object FolderExportFormat {+ /// The record's own name: what the user called it, else the notes' title, else the imported+ /// file's name. Never displayTitle, which is localized and carries a date.+ fun name(s: Session): String {+ if (s.renamed ?: !s.title.startsWith("会议 ")) return s.title+ s.notes?.title?.takeIf { it.isNotEmpty() }?.let { return it }+ // Swift's deletingPathExtension: ".hidden" keeps its name.+ s.sourceFile?.let { f -> val dot = f.lastIndexOf('.'); return if (dot > 0) f.substring(0, dot) else f }+ return ""+ }++ private val banned = "/\\:*?\"<>|#^[]".codePoints().toArray().toSet()++ /// A name every system accepts and a vault can link to: no path, wildcard or link characters,+ /// at most 120 UTF-8 bytes (vaults sync between systems, so the union of their rules). By code+ /// point, so an emoji is never cut in half.+ fun safeName(name: String): String {+ val spaced = StringBuilder()+ name.codePoints().forEach { cp -> if (cp in banned || cp < 0x20) spaced.append(' ') else spaced.appendCodePoint(cp) }+ var out = trim(spaced.split(Regex("[\\s\\p{Z}]+")).filter { it.isNotEmpty() }.joinToString(" "))+ if (out.toByteArray(Charsets.UTF_8).size > 120) {+ val cut = StringBuilder()+ var bytes = 0+ for (cp in out.codePoints().toArray()) {+ bytes += String(Character.toChars(cp)).toByteArray(Charsets.UTF_8).size+ if (bytes > 120) break+ cut.appendCodePoint(cp)+ }+ out = trim(cut.toString())+ }+ return out+ }++ private fun trim(s: String) = s.trim { it == ' ' || it == '.' }++ fun stem(s: Session, zone: ZoneId = ZoneId.systemDefault()): String {+ val date = format(s.startedAt, "yyyy-MM-dd HHmm", zone)+ val safe = safeName(name(s))+ return if (safe.isEmpty()) date else "$date $safe"+ }++ /// `stem.md`, or `stem 2.md`, `stem 3.md`… when a name is taken.+ fun fileName(stem: String, taken: (String) -> Boolean): String {+ var n = 1+ while (true) {+ val name = if (n == 1) "$stem.md" else "$stem $n.md"+ if (!taken(name)) return name+ n+++ }+ }++ /// A JSON-style double-quoted string, which YAML reads as is. Not Json.write's: that escapes "/"+ /// as the Mac's JSONEncoder does, and the frontmatter keeps it.+ fun quote(s: String): String {+ val b = StringBuilder("\"")+ s.codePoints().forEach { cp ->+ when {+ cp == '\\'.code -> b.append("\\\\")+ cp == '"'.code -> b.append("\\\"")+ cp == '\n'.code -> b.append("\\n")+ cp == '\r'.code -> b.append("\\r")+ cp == '\t'.code -> b.append("\\t")+ cp < 0x20 -> b.append(String.format(Locale.ROOT, "\\u%04x", cp))+ else -> b.appendCodePoint(cp)+ }+ }+ return b.append('"').toString()+ }++ private fun byCodePoint(a: String, b: String): Int {+ val x = a.codePoints().toArray(); val y = b.codePoints().toArray()+ for (i in 0 until minOf(x.size, y.size)) if (x[i] != y[i]) return x[i].compareTo(y[i])+ return x.size.compareTo(y.size)+ }++ fun frontmatter(s: Session, zone: ZoneId = ZoneId.systemDefault()): String {+ val ended = s.endedAt ?: s.startedAt+ val languages = s.lines.map { it.srcLang }.distinct().sortedWith(::byCodePoint)+ val notes = s.notes?.let { if (it.isEmpty) "none" else if (it.final) "final" else "draft" } ?: "none"+ val minutes = maxOf(0L, (ended.toEpochMilli() - s.startedAt.toEpochMilli()) / 60_000)+ return "---\n" ++ "cicada: 1\n" ++ "id: ${quote(s.id)}\n" ++ "title: ${quote(name(s))}\n" ++ "started: ${quote(format(s.startedAt, "yyyy-MM-dd'T'HH:mm:ssxxx", zone))}\n" ++ "ended: ${quote(format(ended, "yyyy-MM-dd'T'HH:mm:ssxxx", zone))}\n" ++ "minutes: $minutes\n" ++ "languages: [${languages.joinToString(", ") { quote(it) }}]\n" ++ "source: ${quote(if (s.sourceFile == null) "meeting" else "file")}\n" ++ "notes: ${quote(notes)}\n" ++ "tags: [\"cicada\"]\n" ++ "---\n"+ }++ fun document(s: Session): String = frontmatter(s) + TranscriptExport.markdown(s)++ private fun format(at: Instant, pattern: String, zone: ZoneId) =+ DateTimeFormatter.ofPattern(pattern, Locale.ROOT).withZone(zone).format(at)+}++/// What 存到文件夹 wrote, next to the records (FolderExport.json, as on the Mac): the folder (here a+/// SAF tree URI), each record's file name, and the records still to write. `uris` is Android's own:+/// each file's document URI, a hint only (a path-based provider changes it on rename).+class FolderExportIndex(+ var folder: String = "",+ val files: MutableMap<String, String> = mutableMapOf(),+ val uris: MutableMap<String, String> = mutableMapOf(),+ val pending: MutableList<String> = mutableListOf(),+ var lastFile: String? = null,+ var lastAt: Instant? = null,+) {+ fun toJson(): Map<String, Any?> = mapOf(+ "folder" to folder, "files" to files.toSortedMap(), "uris" to uris.toSortedMap(), "pending" to pending.toList(),+ "lastFile" to lastFile, "lastAt" to lastAt?.let(Iso8601::write),+ )++ fun save(file: File) {+ try {+ val tmp = File(file.path + ".tmp")+ tmp.writeText(Json.write(toJson(), slashes = false))+ if (!tmp.renameTo(file)) { file.delete(); tmp.renameTo(file) }+ } catch (e: Exception) { Log.d("folder export: index not saved ${e.javaClass.simpleName}") }+ }++ companion object {+ fun from(o: Map<String, Any?>) = FolderExportIndex(+ folder = o["folder"].str() ?: "",+ files = strings(o["files"]), uris = strings(o["uris"]),+ pending = o["pending"].arr().mapNotNull { it.str() }.toMutableList(),+ lastFile = o["lastFile"].str(), lastAt = Iso8601.read(o["lastAt"].str()),+ )++ fun load(file: File): FolderExportIndex =+ try { if (file.isFile) Json.parseObject(file.readText())?.let(::from) else null } catch (_: Exception) { null } ?: FolderExportIndex()++ private fun strings(v: Any?): MutableMap<String, String> =+ v.obj()?.mapNotNull { (k, x) -> x.str()?.let { k to it } }?.toMap(mutableMapOf()) ?: mutableMapOf()+ }+}diff --git a/android/core/src/main/kotlin/cicada/Notes.kt b/android/core/src/main/kotlin/cicada/Notes.ktindex 0c1b219..7f6fbc6 100644--- a/android/core/src/main/kotlin/cicada/Notes.kt+++ b/android/core/src/main/kotlin/cicada/Notes.kt@@ -21,6 +21,8 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)private var sessionId: String? = nullprivate var inFlight = falseprivate var pendingFinal: String? = null+ /// The meeting whose final pass is running.+ private var finalId: String? = nullprivate var lastAttempt = 0Lprivate val listeners = mutableListOf<() -> Unit>()@@ -28,6 +30,14 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)@Volatile var status = State.Idle; private set/// The session the notes belong to (stays set after the meeting ends).@Volatile var shownId: String? = null; private set+ /// A final pass is over, whether it wrote notes or not (存到文件夹 waits for it). On the+ /// notes' worker thread.+ @Volatile var finalDone: ((String) -> Unit)? = null++ /// The final pass for this meeting is running, waiting its turn, or still to start: the+ /// meeting has ended but finish() hasn't run yet (it starts on listening's pool).+ fun settling(id: String): Boolean = synchronized(gate) { sessionId == id || finalId == id || pendingFinal == id } || generating == id+/// The language notes are written in (English name), from 纪要语言.@Volatile var language: () -> String = { "Simplified Chinese" }@@ -102,10 +112,12 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)val prior: List<NoteTerm>synchronized(gate) {if (inFlight) { if (final) pendingFinal = id; return }- session = store.get(id) ?: return- if (session.lines.isEmpty()) return- if (!ling.hasKey) { status = State.NoKey; changed(); return }+ fun over() { if (final) finalDone?.invoke(id) }+ session = store.get(id) ?: run { over(); return }+ if (session.lines.isEmpty()) { over(); return }+ if (!ling.hasKey) { status = State.NoKey; changed(); over(); return }inFlight = true+ if (final) finalId = idlastAttempt = System.currentTimeMillis()status = State.Updatingbase = if (final) MeetingNotes() else if (id == shownId) notes else session.notes ?: MeetingNotes()@@ -162,8 +174,9 @@ class NotesEngine(private val ling: LingClient, private val store: SessionStore)status = State.FailedLog.d("notes: update failed ${e.javaClass.simpleName}")} finally {- val queued = synchronized(gate) { inFlight = false; pendingFinal.also { pendingFinal = null } }+ val queued = synchronized(gate) { inFlight = false; if (final) finalId = null; pendingFinal.also { pendingFinal = null } }changed()+ if (final) finalDone?.invoke(id)if (queued != null) update(queued, final = true)}}diff --git a/android/core/src/main/kotlin/cicada/Settings.kt b/android/core/src/main/kotlin/cicada/Settings.ktindex 9fbaa29..02c871d 100644--- a/android/core/src/main/kotlin/cicada/Settings.kt+++ b/android/core/src/main/kotlin/cicada/Settings.kt@@ -55,6 +55,11 @@ class AppSettings(var fixMisheard: Boolean = true,/// 没见过的名字和专称先问我: a new name is asked about once instead of left as heard.var askNames: Boolean = true,+ /// 存到文件夹: settled meetings are also written as Markdown into `exportFolder`, a SAF tree URI+ /// (empty until one is chosen), whose short name "parent › folder" is `exportName`. Not secrets.+ var exportOn: Boolean = false,+ var exportFolder: String = "",+ var exportName: String = "",/// When GitHub Releases last answered an update check (epoch ms; UpdateChecker).var updateLastChecked: Long? = null,/// The newest version a notification was posted for, so each one is announced once.@@ -87,6 +92,7 @@ class AppSettings("source" to source, "overlay" to overlay, "silenceEnd" to silenceEnd, "silenceMinutes" to silenceMinutes,"speakerVoices" to speakerVoices, "recordAudio" to recordAudio, "speakBack" to speakBack,"fixMisheard" to fixMisheard, "askNames" to askNames,+ "exportOn" to exportOn, "exportFolder" to exportFolder, "exportName" to exportName,"updateLastChecked" to updateLastChecked, "updateNotified" to updateNotified,)@@ -125,6 +131,8 @@ class AppSettings(speakerVoices = o["speakerVoices"].bool() ?: true, recordAudio = o["recordAudio"].bool() ?: true,speakBack = o["speakBack"].bool() ?: true,fixMisheard = o["fixMisheard"].bool() ?: true, askNames = o["askNames"].bool() ?: true,+ exportOn = o["exportOn"].bool() ?: false, exportFolder = o["exportFolder"].str() ?: "",+ exportName = o["exportName"].str() ?: "",updateLastChecked = (o["updateLastChecked"] as? Number)?.toLong(), updateNotified = o["updateNotified"].str(),)}