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(linux): after each meeting, notes and transcript can be saved as Markdown into a folder you pick, such as an Obsidian vault

wquguru48a0af4c9465
diff --git a/linux/README.md b/linux/README.md
index 848ff70..5bbe913 100644
--- a/linux/README.md
+++ b/linux/README.md
@@ -55,7 +55,7 @@ linux/vm/vmctl.sh shot shot.png # 截屏(QEMU,不受 Wayland
linux/scripts/build.sh && linux/vm/push.sh # 把 build/cicada-linux 和测试工具放进虚拟机的 ~/cicada-linux
```
-在虚拟机里 `~/cicada-linux/bin/cicada --dev` 启动开发版(记录在 `~/.local/share/cicada-dev`,日志在 `~/.local/state/cicada-dev/debug.log`),再用 `scripts/cicadactl` 驱动它:`state`、`start`、`stop`、`feed <wav>`、`sample`、`view notes|subtitles`、`show records|notes|settings|onboarding`、`windows`、`quit`;在 Dock 中显示用 `dock [on|off]`(打开时会议记录窗口最小化留在 Dock 里,`windows` 的 `iconified` 看它)、`close records`(点会议记录的 ×);结束会议用 `calls zoom=Zoom|none|real`(假装会议软件在通话)、`realcalls`、`endtimes <没人说话秒数> <倒计时> <挂断宽限>|off`、`endkeep`;纪要窗用 `notes-tab notes|transcript`、`notes-search <词>`、`notes-wide on|off`、`notes-end ask|keep|end`(结束前的确认)、`notes-status failed|invalidKey|rateLimited|idle`(看出错横幅);记录用 `rename <id> [标题]`(不给标题即恢复自动标题)、`delete <id>`;还有 `onboarding-step <0-4>`、`settings-scroll <0-1>`;AI 服务检查用 `ai-check`(现在查一次)、`ai-check-sim <原因|lowBalance|off>`(每次检查都按这个原因结束,截各状态的图)、`ask settings|fix|close`(回答开始听时的对话框)、`settings-ai`、`tray-menu`(顶栏菜单的各项);只有你能修的问题(key、余额、模型、地址)在顶栏图标上加橙点,纪要窗收起时每场会议发一次通知(连不上的话持续 2 分钟后才发),`hide notes` 收起纪要窗、`problem-wait <秒>|off` 缩短这 2 分钟、`state` 的 `aiProblem` 看结果。保存会议录音用 `codecs`(这台电脑有没有 AAC 编码器 / 解码器)、`play [秒]`、`pause`、`rate`、`playstate`(播放到哪、亮着哪一句)、`settings-general`;Ubuntu 默认没有 AAC 编码器,测录音要先在虚拟机里 `sudo apt install gstreamer1.0-libav`,测完再删掉,看默认的灰开关。改正听错的词:`start` 后用 `heard <一句话>`(不用声音,当作听到的一整句,走真实的翻译 + 改词请求),`fix-state` 看每句的改法,`fix-answer yes|no`、`fix-later`、`fix-revert <句子 id>`、`fix-edit <句子 id>=<改后>[|one][|keep0]`、`fix-undo`,`fix-editor <句子 id>=<改后>` 在会议记录里打开“改这句…”,`vocab-add Morpho=莫拉`、`vocab-state`、`word-list [import <文字>|edit <词>|heard <词>=<听成>|delete <词>]` 看设置里的词表。分享成链接(`cicada/core/share.py`,设备密钥是纯 Python 的 Ed25519,`cicada/core/ed25519.py`):`share <id>[,full][,pw]`、`unshare <id>`、`share-last`、`shareSheet <id>` 打开“分享…”,`share-ui scope|days|names|pw|summary|options|go|strip|back|confirm|copy all|link|password|revoke|close|state` 操作它(`options` 即“更改”,`state` 的 `clipboard` 是剪贴板里的那条消息);虚拟机连不上 cicada.indaloop.app 时用 `https_proxy=http://10.0.2.2:7890` 启动。`scripts/smoke.sh` 一步跑完:开窗口、放一段声音、确认 monitor 听到了。
+在虚拟机里 `~/cicada-linux/bin/cicada --dev` 启动开发版(记录在 `~/.local/share/cicada-dev`,日志在 `~/.local/state/cicada-dev/debug.log`),再用 `scripts/cicadactl` 驱动它:`state`、`start`、`stop`、`feed <wav>`、`sample`、`view notes|subtitles`、`show records|notes|settings|onboarding`、`windows`、`quit`;在 Dock 中显示用 `dock [on|off]`(打开时会议记录窗口最小化留在 Dock 里,`windows` 的 `iconified` 看它)、`close records`(点会议记录的 ×);结束会议用 `calls zoom=Zoom|none|real`(假装会议软件在通话)、`realcalls`、`endtimes <没人说话秒数> <倒计时> <挂断宽限>|off`、`endkeep`;纪要窗用 `notes-tab notes|transcript`、`notes-search <词>`、`notes-wide on|off`、`notes-end ask|keep|end`(结束前的确认)、`notes-status failed|invalidKey|rateLimited|idle`(看出错横幅);记录用 `rename <id> [标题]`(不给标题即恢复自动标题)、`delete <id>`;还有 `onboarding-step <0-4>`、`settings-scroll <0-1>`;AI 服务检查用 `ai-check`(现在查一次)、`ai-check-sim <原因|lowBalance|off>`(每次检查都按这个原因结束,截各状态的图)、`ask settings|fix|close`(回答开始听时的对话框)、`settings-ai`、`tray-menu`(顶栏菜单的各项);只有你能修的问题(key、余额、模型、地址)在顶栏图标上加橙点,纪要窗收起时每场会议发一次通知(连不上的话持续 2 分钟后才发),`hide notes` 收起纪要窗、`problem-wait <秒>|off` 缩短这 2 分钟、`state` 的 `aiProblem` 看结果。保存会议录音用 `codecs`(这台电脑有没有 AAC 编码器 / 解码器)、`play [秒]`、`pause`、`rate`、`playstate`(播放到哪、亮着哪一句)、`settings-general`;Ubuntu 默认没有 AAC 编码器,测录音要先在虚拟机里 `sudo apt install gstreamer1.0-libav`,测完再删掉,看默认的灰开关。改正听错的词:`start` 后用 `heard <一句话>`(不用声音,当作听到的一整句,走真实的翻译 + 改词请求),`fix-state` 看每句的改法,`fix-answer yes|no`、`fix-later`、`fix-revert <句子 id>`、`fix-edit <句子 id>=<改后>[|one][|keep0]`、`fix-undo`,`fix-editor <句子 id>=<改后>` 在会议记录里打开“改这句…”,`vocab-add Morpho=莫拉`、`vocab-state`、`word-list [import <文字>|edit <词>|heard <词>=<听成>|delete <词>]` 看设置里的词表。分享成链接(`cicada/core/share.py`,设备密钥是纯 Python 的 Ed25519,`cicada/core/ed25519.py`):`share <id>[,full][,pw]`、`unshare <id>`、`share-last`、`shareSheet <id>` 打开“分享…”,`share-ui scope|days|names|pw|summary|options|go|strip|back|confirm|copy all|link|password|revoke|close|state` 操作它(`options` 即“更改”,`state` 的 `clipboard` 是剪贴板里的那条消息);虚拟机连不上 cicada.indaloop.app 时用 `https_proxy=http://10.0.2.2:7890` 启动。存到文件夹(`cicada/core/folder_export.py`,会后把会议存成 Markdown 到选的文件夹,索引在记录旁的 `FolderExport.json`):`export-folder <路径>|off|on`(选文件夹并当场检查能不能写)、`export-state`(文件夹、问题、索引、还没存的记录)、`export-all`(也存一份)、`export-retry`、`export-choose`(打开“存到哪里”);测没权限用 `chmod a-w` 那个文件夹,测找不到就把它的上一级挪走。`scripts/smoke.sh` 一步跑完:开窗口、放一段声音、确认 monitor 听到了。
焦点:`bin/focus_test.sh` 开一个最大化的“会议 app”(`focus_probe.py`),用 `click.py`(uinput,真实指针)点纪要窗和“字幕”链接,再在 Mac 上 `linux/vm/vmctl.sh type ok`;`/tmp/focus-probe.log` 里不能出现 `active=False`,最后一行应是 `text=…ok`。xdotool 只到 XWayland,测不了这个。
diff --git a/linux/cicada/app/debug.py b/linux/cicada/app/debug.py
index 3455016..6d1fbf9 100644
--- a/linux/cicada/app/debug.py
+++ b/linux/cicada/app/debug.py
@@ -24,7 +24,10 @@ per connection, one JSON line back. Never in release builds.
settings-general (设置 at 通用)
share <record id>[,full][,pw] | unshare <record id> | share-last (how the last ended) | shareSheet <record id>|""
share-ui scope notes|full | days 7|30|365 | names|pw|summary on|off | options (更改) | go | strip | back | confirm
- | copy all|link|password | revoke | close | state"""
+ | copy all|link|password | revoke | close | state
+ export-folder <path>|off|on (存到文件夹: choose a folder as 存到这里 does, and its check) |
+ export-state (folder, problem, index, the records not written yet) | export-all (也存一份) | export-retry |
+ export-choose (open 存到哪里, as 更改… does; answer it with the dialog itself)"""
from __future__ import annotations
import os
@@ -129,6 +132,37 @@ def updates_notified():
return updates.notified()
+def _export(app, cmd: str, arg: str) -> dict:
+ """存到文件夹. Waits for the exporter's worker (it never waits for the main loop), so the reply
+ says what happened."""
+ ex = app.folder_export
+ if cmd == "export-folder":
+ if arg == "off":
+ ex.turn_off()
+ elif arg == "on" and ex.folder:
+ ex.choose(ex.folder)
+ elif arg:
+ ex.choose(arg)
+ else:
+ return {"ok": False, "error": "export-folder <path>|off|on"}
+ ex.wait()
+ return {"ok": True, **ex.state()}
+ if cmd == "export-all":
+ ex.write_all()
+ ex.wait()
+ return {"ok": True, **ex.state()}
+ if cmd == "export-retry":
+ ex.retry()
+ return {"ok": True}
+ if cmd == "export-choose":
+ app.show_settings(general=True)
+ GLib.idle_add(lambda: app.settings_window.folder_card._choose() and False)
+ return {"ok": True}
+ if cmd == "export-state":
+ return {"ok": True, **ex.state()}
+ return {"ok": False, "error": "unknown command"}
+
+
def command(app, line: str) -> dict:
parts = line.split(" ", 1)
cmd, arg = parts[0], (parts[1] if len(parts) > 1 else "")
@@ -366,6 +400,8 @@ def command(app, line: str) -> dict:
"bars": w._bars is not None and w._bars.get_mapped() if w is not None else None,
"bar": w.bottom.get_children() != [] if w is not None else None,
"line": next((i for i, (_k, r) in enumerate(w._rows) if r is hl), None) if hl is not None else None}
+ if cmd.startswith("export-"):
+ return _export(app, cmd, arg)
if cmd == "settings-general":
app.show_settings(general=True)
return {"ok": True}
@@ -429,6 +465,8 @@ def command(app, line: str) -> dict:
"shown": session_store.display_title(s) if s else None}
if cmd == "delete":
app.store.delete(arg)
+ if app.store.get(arg) is None:
+ app.folder_export.deleted(arg)
return {"ok": True, "exists": app.store.get(arg) is not None, "live": app.store.live}
if cmd == "notes-end":
# The notes window's 结束: `ask`, then `keep` (继续记录) or `end` (结束会议).
diff --git a/linux/cicada/app/folder_export_view.py b/linux/cicada/app/folder_export_view.py
new file mode 100644
index 0000000..7cb98f3
--- /dev/null
+++ b/linux/cicada/app/folder_export_view.py
@@ -0,0 +1,258 @@
+"""存到文件夹 on screen (the Mac's FolderExportViews.swift): 设置 › 会后存一份's card, the 存到哪里 dialog
+and the record's line under its title. The work is core/folder_export.py's.
+
+Linux has no privacy prompt (the .deb isn't sandboxed): a folder Cicada can't write is its
+permissions, so the Mac's 去系统设置 and "macOS 可能会问…" have no counterpart here."""
+from __future__ import annotations
+
+import os
+
+from gi.repository import Gio, GLib, Gtk, Pango
+
+from ..core import folder_export as fx
+from ..core import session_store
+from ..core.strings import L, LF
+from . import ui
+
+
+def open_folder(path: str) -> None:
+ """Never creates it: under a drive that isn't mounted that would be a stray folder."""
+ if not os.path.isdir(path):
+ return
+ try:
+ Gio.AppInfo.launch_default_for_uri(Gio.File.new_for_path(path).get_uri(), None)
+ except GLib.Error:
+ pass
+
+
+def documents_dir() -> str:
+ """GLib's XDG documents folder; unset, it answers the home folder: then xdg-user-dir, ~/Documents."""
+ d = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DOCUMENTS)
+ if d and os.path.normpath(d) != os.path.normpath(os.path.expanduser("~")):
+ return d
+ return fx.documents_dir()
+
+
+class FolderExportCard:
+ """设置 › 会后存一份. Rebuilt from a state key (as WordList is), so the window's show_all never brings
+ back a row that shouldn't show."""
+
+ def __init__(self, app, group, window):
+ self.app = app
+ self.window = window
+ self.box = ui.vbox(8)
+ self._key = None
+ self.widget = group(L("会后存一份"), self.box)
+ self.refresh()
+ # Opened again: a vault opened in Obsidian since may now hold the folder.
+ window.connect("show", lambda *_: (setattr(self, "_vault_for", None), self.refresh()))
+
+ def refresh(self) -> None:
+ ex = self.app.folder_export
+ folder = ex.folder
+ idx = ex.index
+ unwritten = len(ex.unwritten()) if ex.on else 0
+ key = (ex.on, folder, ex.checking, ex.problem, ex.problem_message, len(idx.pending), unwritten,
+ idx.lastFile, idx.lastAt, bool(folder) and os.path.isdir(folder), self._vault(folder))
+ if key == self._key:
+ return
+ self._key = key
+ ui.clear(self.box)
+ sw = Gtk.Switch()
+ sw.set_valign(Gtk.Align.CENTER)
+ sw.set_active(ex.on)
+ sw.connect("notify::active", self._toggled) # after set_active: only the user's clicks
+ rows = [ui.prow(L("存到文件夹"), sw, L("纪要和文字记录存成 Markdown;文件夹同步到哪,内容就到哪"))]
+ if ex.on and folder:
+ short = fx.short_path(folder)
+ if ex.checking:
+ spin = Gtk.Spinner()
+ spin.start()
+ rows.append(ui.panel(ui.pad(ui.hbox(8, spin, ui.text(LF("正在确认能写入 %@…", short), 12, "secondary", wrap=False)), 12, 14), "prow"))
+ elif ex.problem is not None:
+ rows.append(ui.panel(ui.pad(self._problem(ex, short), 8, 10), "prow"))
+ controls = ui.hbox(8)
+ if key[-1]:
+ tag = ui.text(L("Obsidian 库"), 11, "", wrap=False, ellipsize=False)
+ ui.pad(tag, 1, 6) # a margin: GTK 3 ignores CSS padding on an EventBox
+ t = ui.panel(tag, "foldertag")
+ t.set_valign(Gtk.Align.CENTER)
+ controls.pack_start(t, False, False, 0)
+ opener = ui.soft_button(L("打开"), lambda: open_folder(folder))
+ opener.set_sensitive(key[-2]) # nothing to open while the folder is gone
+ controls.pack_start(opener, False, False, 0)
+ controls.pack_start(ui.soft_button(L("更改…"), self._choose), False, False, 0)
+ sub = ui.text(short, 11, "tertiary", wrap=False)
+ sub.set_ellipsize(Pango.EllipsizeMode.MIDDLE)
+ sub.set_tooltip_text(folder)
+ rows.append(ui.prow(L("位置"), controls, subtitle_widget=sub))
+ if unwritten > 0:
+ rows.append(ui.prow(L("以前的会议"), ui.soft_button(L("也存一份"), ex.write_all), LF("还有 %lld 场没存", unwritten)))
+ self.box.pack_start(ui.boxed(rows), False, False, 0)
+ if ex.on and idx.lastFile and idx.lastAt:
+ when = session_store._local_date(idx.lastAt, L("M月d日 HH:mm"))
+ last = ui.text(LF("上次存于 %@ · %@", when, idx.lastFile), 12, "tertiary", wrap=False)
+ last.set_ellipsize(Pango.EllipsizeMode.MIDDLE)
+ self.box.pack_start(ui.pad(last, 0, 0, 0, 4), False, False, 0)
+ self.box.show_all()
+
+ def _vault(self, folder):
+ """Obsidian 库 or not, read once per folder: refresh runs on every change, meetings included."""
+ if not folder:
+ return None
+ if getattr(self, "_vault_for", None) != folder:
+ self._vault_for, self._vault_is = folder, fx.vault_of(folder)
+ return self._vault_is
+
+ def _problem(self, ex, short: str) -> Gtk.Widget:
+ waiting = len(ex.index.pending)
+ if ex.problem == fx.DENIED:
+ title = LF("没有权限写入 %@", short)
+ # Linux asks no one: the folder's own permissions are what to change.
+ detail = LF("%lld 场会议没存上,允许后自动补存", waiting) if waiting else L("改一下这个文件夹的权限,或换个文件夹")
+ elif ex.problem == fx.MISSING:
+ title, detail = LF("找不到 %@", short), L("接上或换个文件夹后自动补存")
+ else:
+ title, detail = L("没存上"), ex.problem_message
+ box = ui.vbox(2, ui.text(title, 13, "ink", bold=True, width_chars=50), ui.text(detail, 12, "secondary", width_chars=50))
+ return ui.panel(ui.pad(box, 10, 12), "folderproblem", "denied" if ex.problem == fx.DENIED else "")
+
+ def _toggled(self, sw, _p) -> None:
+ ex = self.app.folder_export
+ if not sw.get_active():
+ ex.turn_off()
+ elif ex.folder:
+ ex.choose(ex.folder)
+ else:
+ # Not inside the switch's own signal: the dialog's refresh replaces the switch.
+ GLib.idle_add(lambda: self._choose() and False)
+
+ def _choose(self) -> None:
+ picked = choose_folder(self.window, self.app.folder_export.folder)
+ if picked:
+ self.app.folder_export.choose(picked)
+ else:
+ self._key = None # the switch flipped on for a dialog that was cancelled: back off
+ self.refresh()
+
+
+def choose_folder(parent, current: str | None) -> str | None:
+ """存到哪里: an Obsidian vault first (a new Cicada folder in it), then Documents › Cicada, or any
+ folder through the system's folder dialog."""
+ options = [(LF("Obsidian 库「%@」", os.path.basename(v)), L("在库里新建 Cicada 文件夹"), os.path.join(v, "Cicada"))
+ for v in fx.all_vaults()[:3]]
+ docs = documents_dir()
+ options.append((os.path.basename(docs) + " › Cicada", None, os.path.join(docs, "Cicada")))
+ options.append((L("其他文件夹…"), None, None))
+ d = Gtk.Dialog(transient_for=parent, modal=True)
+ d.set_title(L("存到哪里"))
+ d.set_resizable(False)
+ # The app's flat bar with only ×, not Yaru's dark one repeating the heading (the Mac's is a sheet).
+ bar = Gtk.HeaderBar()
+ bar.set_show_close_button(True)
+ bar.set_decoration_layout(":close")
+ bar.set_custom_title(Gtk.Box()) # the heading below says it once
+ ui.classes(bar, "cicada")
+ d.set_titlebar(bar)
+ ui.classes(d, "sheet")
+ area = d.get_content_area()
+ ui.classes(area, "sheet")
+ body = ui.vbox(14, ui.text(L("存到哪里"), 15, "heading", bold=True, wrap=False))
+ ui.pad(body, 0, 20, 20, 20) # the bar above is the top margin
+ body.set_size_request(380, -1)
+ picks = ui.vbox(8)
+ body.pack_start(picks, False, False, 0)
+ state = {"pick": 0}
+ buttons = []
+
+ def draw():
+ for i, (b, title, mark) in enumerate(buttons):
+ on = i == state["pick"]
+ ui.classes(b, "picked") if on else b.get_style_context().remove_class("picked")
+ mark.set_from_icon_name("radio-checked-symbolic" if on else "radio-symbolic", Gtk.IconSize.BUTTON)
+ title.cicada_format = (13, title.cicada_format[1], on)
+ ui.retext(title, options[i][0])
+ for i, (title, detail, _path) in enumerate(options):
+ b = Gtk.Button()
+ b.set_can_focus(False)
+ ui.classes(b, "folderoption")
+ mark = ui.icon("radio-symbolic", 13)
+ mark.set_valign(Gtk.Align.START)
+ t = ui.text(title, 13, "ink", wrap=False)
+ col = ui.vbox(2, t)
+ if detail:
+ col.pack_start(ui.text(detail, 12, "secondary", wrap=False), False, False, 0)
+ row = ui.hbox(10, mark, col)
+ b.add(ui.pad(row, 10, 12))
+ b.connect("clicked", lambda _b, i=i: (state.update(pick=i), draw()))
+ buttons.append((b, t, mark))
+ picks.pack_start(b, False, False, 0)
+ draw()
+ actions = ui.hbox(8)
+ actions.set_halign(Gtk.Align.END)
+ actions.pack_start(ui.soft_button(L("取消"), lambda: d.response(Gtk.ResponseType.CANCEL)), False, False, 0)
+ actions.pack_start(ui.soft_button(L("存到这里"), lambda: d.response(Gtk.ResponseType.OK), dark=True), False, False, 0)
+ body.pack_start(actions, False, False, 0)
+ area.add(body)
+ d.show_all()
+ ok = d.run() == Gtk.ResponseType.OK
+ d.destroy()
+ if not ok:
+ return None
+ path = options[state["pick"]][2]
+ if path:
+ return path
+ chooser = Gtk.FileChooserDialog(title=L("会后把纪要和文字记录存成 Markdown 到这里"), transient_for=parent,
+ action=Gtk.FileChooserAction.SELECT_FOLDER)
+ chooser.add_buttons(L("取消"), Gtk.ResponseType.CANCEL, L("存到这里"), Gtk.ResponseType.ACCEPT)
+ chooser.set_create_folders(True)
+ start = current if current and os.path.isdir(current) else docs if os.path.isdir(docs) else os.path.expanduser("~")
+ chooser.set_current_folder(start)
+ path = chooser.get_filename() if chooser.run() == Gtk.ResponseType.ACCEPT else None
+ chooser.destroy()
+ return path
+
+
+def line_key(app, s):
+ """What the record's line says, so it is rebuilt only when that changes."""
+ ex = app.folder_export
+ if not (ex.on and ex.folder and ex.ready(s)):
+ return None
+ pending = ex.is_pending(s.id)
+ return (ex.folder, ex.file(s.id), pending, pending and ex.problem is not None)
+
+
+def record_line(app, s, show_in_folder):
+ """Under the record's title: where its file is, or why it isn't there yet. None: nothing to say."""
+ key = line_key(app, s)
+ if key is None:
+ return None
+ folder, path, pending, problem = key
+ short = fx.short_path(folder)
+ row = ui.hbox(4)
+
+ def link(label, action):
+ b = Gtk.Button()
+ b.add(ui.text(label, 12, "link", wrap=False, ellipsize=False))
+ b.set_relief(Gtk.ReliefStyle.NONE)
+ ui.classes(b, "timelink")
+ b.connect("clicked", lambda *_: action())
+ return b
+
+ def folder_icon():
+ i = ui.icon("folder-symbolic", 11)
+ ui.classes(i, "tertiary")
+ return i
+ if path and not pending:
+ row.pack_start(folder_icon(), False, False, 0)
+ row.pack_start(ui.text(LF("已存到 %@ ·", short), 12, "tertiary", wrap=False, ellipsize=False), False, False, 0)
+ row.pack_start(link(L("在文件夹中显示"), lambda: show_in_folder(path)), False, False, 0)
+ elif pending and problem:
+ row.pack_start(ui.text(L("没存到文件夹 ·"), 12, "tertiary", wrap=False, ellipsize=False), False, False, 0)
+ row.pack_start(link(L("去设置"), lambda: app.show_settings(general=True)), False, False, 0)
+ elif pending:
+ row.pack_start(folder_icon(), False, False, 0)
+ row.pack_start(ui.text(LF("整理好后存到 %@", short), 12, "tertiary", wrap=False, ellipsize=False), False, False, 0)
+ else:
+ return None
+ return row
diff --git a/linux/cicada/app/main.py b/linux/cicada/app/main.py
index 4067147..0472cc6 100644
--- a/linux/cicada/app/main.py
+++ b/linux/cicada/app/main.py
@@ -122,6 +122,15 @@ class Controller:
self.store.on_change(lambda _id: self.changed())
self.store.on_words(self._words)
self.ling.on_change(self.changed)
+ # 存到文件夹 (设置 › 通用): written once a record is settled, rewritten when it changes.
+ from ..core.folder_export import FolderExporter
+ self.folder_export = FolderExporter(self.store, self.settings)
+ self.folder_export.settling = self.notes.settling
+ self.folder_export.voices = lambda: self.settings.speakerVoices
+ self.folder_export.on_change(self.changed)
+ self.folder_export.on_denied = lambda: GLib.idle_add(lambda: self._notify_folder_denied() and False)
+ self.store.on_save(self.folder_export.saved)
+ self.notes.final_done = self.folder_export.settled
self.notes_window = None
self.share_dialog = None # 分享… (share_dialog.py), one at a time
self.records_window = None
@@ -202,6 +211,19 @@ class Controller:
self._notified = False
Log.d("problem: withdrawn")
+ def _notify_folder_denied(self) -> None:
+ """Once after a meeting, until a write works again (folder_export decides when): its own id,
+ so check_problem's withdraw never takes it away."""
+ from ..core.folder_export import short_path
+ folder = self.folder_export.folder
+ if not folder:
+ return
+ n = Gio.Notification.new(L("纪要没存到文件夹"))
+ n.set_body(LF("知了没有权限写入 %@。点按去设置", short_path(folder)))
+ n.set_default_action("app.folder-settings")
+ self.application.send_notification("folder-export", n)
+ Log.d("folder export: notified denied")
+
def launch(self, speak: bool = False, background: bool = False) -> None:
ui.install_css()
lang = strings.language
@@ -251,6 +273,7 @@ class Controller:
self.records_window.toasts.show(reopened)
self.updates.start()
self.keep_in_dock()
+ self.folder_export.retry() # meetings that waited (a folder that wasn't there, or the app quit)
def changed(self) -> None:
"""Engine threads call this: one coalesced refresh on the main loop."""
@@ -273,6 +296,7 @@ class Controller:
if self.settings_window is not None:
self.settings_window.refresh_version()
self.settings_window.word_list.refresh()
+ self.settings_window.folder_card.refresh()
self.check_problem()
return False
GLib.idle_add(run)
@@ -292,6 +316,8 @@ class Controller:
from .records_window import RecordsWindow
self.records_window = RecordsWindow(self)
self.application.add_window(self.records_window)
+ # Coming forward: a folder fixed meanwhile (the Mac's didBecomeActive).
+ self.records_window.connect("focus-in-event", lambda *_: self.folder_export.retry() or False)
return self.records_window
def show_records(self) -> None:
@@ -973,6 +999,8 @@ class Controller:
def run():
sid = self.listen.session_id
self.listen.stop(ended_at)
+ if sid and self.store.get(sid) is not None:
+ self.folder_export.ended(sid)
if self.echo.on:
self.echo.remove() # the speakers are the default output again
if sid and self.settings.speakerVoices:
@@ -1082,7 +1110,10 @@ class Controller:
if self.echo.on:
self.echo.remove()
if self.listen.listening:
+ sid = self.listen.session_id
self.listen.stop()
+ if sid and self.store.get(sid) is not None:
+ self.folder_export.ended(sid) # kept as waiting: written at the next launch
self.store.flush()
GLib.idle_add(lambda: self.application.quit() and False)
threading.Thread(target=run, daemon=True).start()
@@ -1109,6 +1140,8 @@ class App(Gtk.Application):
# The update notification's click and its 更新说明 button; a problem's 打开设置.
for name, action in (("install-update", lambda: self.controller.updates.install()),
("ai-settings", lambda: self.controller.show_settings(ai=True)),
+ # 纪要没存到文件夹: 设置 › 通用, where the row says what to do.
+ ("folder-settings", lambda: self.controller.show_settings(general=True)),
("update-notes", lambda: self.controller.updates.open_notes())):
a = Gio.SimpleAction.new(name, None)
a.connect("activate", lambda _a, _p, f=action: f())
diff --git a/linux/cicada/app/records_window.py b/linux/cicada/app/records_window.py
index a9e2d79..8341cd8 100644
--- a/linux/cicada/app/records_window.py
+++ b/linux/cicada/app/records_window.py
@@ -754,6 +754,13 @@ class RecordsWindow(Gtk.Window):
left.pack_start(self.title_label, False, False, 0)
self.meta_label = ui.text(self._meta(s, live), 12, "tertiary", wrap=False)
left.pack_start(self.meta_label, False, False, 0)
+ # 存到文件夹: where this record's file is, or why it isn't there yet (not while it's live).
+ self.export_slot = ui.hbox(0)
+ self.export_slot.set_margin_top(5)
+ self.export_slot.set_no_show_all(True)
+ self._export_key = False
+ left.pack_start(self.export_slot, False, False, 0)
+ self._fill_export_line(s, live)
top.pack_start(left, True, True, 0)
actions = ui.hbox(8)
actions.set_valign(Gtk.Align.START)
@@ -785,6 +792,19 @@ class RecordsWindow(Gtk.Window):
bar.show_all()
GLib.idle_add(lambda: (self.right.get_vadjustment().set_value(keep), self._pin()) and False)
+ def _fill_export_line(self, s, live) -> None:
+ from . import folder_export_view
+ key = None if live else folder_export_view.line_key(self.app, s)
+ if key == self._export_key:
+ return
+ self._export_key = key
+ ui.clear(self.export_slot)
+ line = folder_export_view.record_line(self.app, s, show_in_folder) if key is not None else None
+ if line is not None:
+ self.export_slot.pack_start(line, False, False, 0)
+ line.show_all()
+ self.export_slot.set_visible(line is not None)
+
def _meta(self, s, live) -> str:
langs = ""
if s.lines:
@@ -816,6 +836,7 @@ class RecordsWindow(Gtk.Window):
ui.retext(self.title_label, session_store.display_title(s))
ui.retext(self.pinned_title, session_store.display_title(s))
ui.retext(self.meta_label, self._meta(s, live))
+ self._fill_export_line(s, live)
state = self._notes_state(s, live)
if state != self._notes_key:
self._notes_key = state
@@ -1888,6 +1909,7 @@ class RecordsWindow(Gtk.Window):
sid, self.pending_delete = self.pending_delete, None
if sid:
self.app.store.delete(sid)
+ self.app.folder_export.deleted(sid) # its file in the folder stays
def show_in_folder(path: str) -> None:
diff --git a/linux/cicada/app/settings_window.py b/linux/cicada/app/settings_window.py
index 6847a1c..c0a28c8 100644
--- a/linux/cicada/app/settings_window.py
+++ b/linux/cicada/app/settings_window.py
@@ -216,6 +216,11 @@ class SettingsWindow(Gtk.Window):
# 通用, the Mac's records section: what each meeting keeps.
self.general = self._group(L("通用"), ui.boxed([self._record_row(), self._voices_row()]))
page.pack_start(self.general, False, False, 0)
+ # 会后存一份 (存到文件夹), under 通用 as on the Mac.
+ from .folder_export_view import FolderExportCard
+ self.folder_card = FolderExportCard(app, self._group, self)
+ page.pack_start(self.folder_card.widget, False, False, 0)
+ self.connect("show", lambda *_: app.folder_export.retry()) # a folder fixed meanwhile
room_group, room_combos = self._room_group()
page.pack_start(room_group, False, False, 0)
diff --git a/linux/cicada/app/ui.py b/linux/cicada/app/ui.py
index e06b0d4..318bc91 100644
--- a/linux/cicada/app/ui.py
+++ b/linux/cicada/app/ui.py
@@ -174,6 +174,17 @@ button.iconbtn.on { background-color: #F3F4F6; color: #15171C; }
.placetag { border-radius: 4px; border: 1px solid #E4E6EA; }
.placetag.room { background-color: #F2F3F5; border-color: #F2F3F5; }
.placetag label { color: #5A5F6B; }
+/* Save to folder (folder_export_view.py): the Obsidian vault tag, a problem in the card (accent-pale
+ when the folder refuses, ground grey otherwise), and the save-where choices (ink when picked). */
+.foldertag { border-radius: 4px; background-color: #F2F3F5; }
+.foldertag label { color: #5A5F6B; }
+.folderproblem { background-color: #F3F4F6; border-radius: 9px; }
+.folderproblem.denied { background-color: #FDEEE8; }
+button.folderoption { background-image: none; background-color: #FFFFFF; border: 1px solid #E4E6EA; box-shadow: none; border-radius: 9px; padding: 0; }
+button.folderoption:hover { background-color: #F6F7F9; }
+button.folderoption.picked, button.folderoption.picked:hover { background-color: #FFFFFF; border: 1.5px solid #15171C; }
+button.folderoption image { color: #6B7080; }
+button.folderoption.picked image { color: #15171C; }
.metag { border-radius: 4px; border: 1px solid rgba(232,85,43,0.45); }
.metag label { color: #B33A14; }
.badge { background-color: #FDEEE8; border-radius: 5px; padding: 0 6px; color: #B33A14; }
@@ -298,6 +309,8 @@ button.fixlink label { color: #B33A14; }
.fixbanner { background-color: #FEF6F2; border: 1px solid #FBE0D5; border-radius: 12px; }
button.softbtn { background-image: none; background-color: #ECEDF0; border: none; box-shadow: none; border-radius: 7px; padding: 4px 14px; color: #5A5F6B; }
button.softbtn:hover { background-color: #E2E4E8; }
+button.softbtn:disabled { background-color: #F3F4F6; color: #A3A7B1; }
+button.softbtn:disabled label { color: #A3A7B1; }
.fixeditor { border: 1px solid #15171C; border-radius: 8px; background-color: #FFFFFF; }
.fixeditor text { background-color: #FFFFFF; color: #15171C; }
.heardchip { background-color: #F2F3F5; border-radius: 5px; }
diff --git a/linux/cicada/core/folder_export.py b/linux/cicada/core/folder_export.py
new file mode 100644
index 0000000..7b1e186
--- /dev/null
+++ b/linux/cicada/core/folder_export.py
@@ -0,0 +1,613 @@
+"""存到文件夹: a settled meeting written as one Markdown file into a folder the user chose
+(docs/folder-export.md, the Mac's FolderExport.swift). The file name and frontmatter are a contract
+with the Mac and the other ports (Tests/fixtures/folder-export); the body is 导出…'s Markdown.
+
+The exporter keeps an index beside the records (FolderExport.json): the folder, each record's file
+and the records still to write. Every write runs on one worker thread, in order: rendering, writing
+and updating the index, so two flushes never race over the same file."""
+from __future__ import annotations
+
+import errno
+import json
+import os
+import secrets
+import subprocess
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from datetime import datetime, timedelta
+
+from . import jsonfmt, session_store
+from .models import iso_read, iso_write, now
+from .support import Log, Paths
+
+DENIED = "denied" # the folder won't let Cicada write (its permissions)
+MISSING = "missing" # the folder, or the drive it was on, is gone
+FAILED = "failed" # anything else; `problem_message` says what
+
+PROBE = ".cicada-check"
+
+# Path, wildcard and link characters some system or vault refuses (vaults sync between systems,
+# so the union of their rules).
+_BANNED = set('/\\:*?"<>|#^[]')
+
+
+# The format
+
+def name(s) -> str:
+ """The record's own name: what the user called it, else the notes' title, else the imported
+ file's name. Never display_title, which is localized and carries a date."""
+ renamed = s.renamed if s.renamed is not None else not s.title.startswith("会议 ")
+ if renamed:
+ return s.title
+ if s.notes is not None and s.notes.title:
+ return s.notes.title
+ if s.sourceFile:
+ return os.path.splitext(s.sourceFile)[0]
+ return ""
+
+
+def _trim(s: str) -> str:
+ return s.strip(" .")
+
+
+def safe_name(n: str) -> str:
+ """At most 120 UTF-8 bytes, cut at a code point (the spec's cut; Python's stdlib has no
+ grapheme clusters, and the Mac cuts at scalars too)."""
+ spaced = "".join(" " if c in _BANNED or ord(c) < 0x20 else c for c in n)
+ out = _trim(" ".join(spaced.split()))
+ if len(out.encode("utf-8")) > 120:
+ cut, size = [], 0
+ for c in out:
+ size += len(c.encode("utf-8"))
+ if size > 120:
+ break
+ cut.append(c)
+ out = _trim("".join(cut))
+ return out
+
+
+def _local(at: datetime, tz=None) -> datetime:
+ return at.astimezone(tz) if tz is not None else at.astimezone()
+
+
+def _offset(at: datetime) -> str:
+ """+08:00, +00:00 for UTC (never Z)."""
+ off = at.utcoffset() or timedelta(0)
+ minutes = int(off.total_seconds()) // 60
+ sign = "-" if minutes < 0 else "+"
+ minutes = abs(minutes)
+ return "%s%02d:%02d" % (sign, minutes // 60, minutes % 60)
+
+
+def _stamp(at: datetime, tz=None) -> str:
+ l = _local(at, tz)
+ return l.strftime("%Y-%m-%dT%H:%M:%S") + _offset(l)
+
+
+def stem(s, tz=None) -> str:
+ date = _local(s.startedAt, tz).strftime("%Y-%m-%d %H%M")
+ safe = safe_name(name(s))
+ return "%s %s" % (date, safe) if safe else date
+
+
+def file_name(st: str, taken) -> str:
+ """`stem.md`, or `stem 2.md`, `stem 3.md`… while `taken(name)` says that one is."""
+ n = 1
+ while True:
+ candidate = "%s.md" % st if n == 1 else "%s %d.md" % (st, n)
+ if not taken(candidate):
+ return candidate
+ n += 1
+
+
+def quote(s: str) -> str:
+ """A JSON-style double-quoted string, which YAML reads as is. Not json.dumps: it writes \\b and
+ \\f, where the contract wants \\u0008 and \\u000c."""
+ out = ['"']
+ for c in s:
+ if c == "\\":
+ out.append("\\\\")
+ elif c == '"':
+ out.append('\\"')
+ elif c == "\n":
+ out.append("\\n")
+ elif c == "\r":
+ out.append("\\r")
+ elif c == "\t":
+ out.append("\\t")
+ elif ord(c) < 0x20:
+ out.append("\\u%04x" % ord(c))
+ else:
+ out.append(c)
+ out.append('"')
+ return "".join(out)
+
+
+def frontmatter(s, tz=None) -> str:
+ ended = s.endedAt or s.startedAt
+ languages = sorted({l.srcLang for l in s.lines}) # str order is code point order
+ notes = "none" if s.notes is None or s.notes.is_empty else ("final" if s.notes.final else "draft")
+ minutes = max(0, int((ended - s.startedAt).total_seconds() // 60))
+ return "".join([
+ "---\n",
+ "cicada: 1\n",
+ "id: %s\n" % quote(s.id),
+ "title: %s\n" % quote(name(s)),
+ "started: %s\n" % quote(_stamp(s.startedAt, tz)),
+ "ended: %s\n" % quote(_stamp(ended, tz)),
+ "minutes: %d\n" % minutes,
+ "languages: [%s]\n" % ", ".join(quote(x) for x in languages),
+ "source: %s\n" % quote("meeting" if s.sourceFile is None else "file"),
+ "notes: %s\n" % quote(notes),
+ 'tags: ["cicada"]\n',
+ "---\n",
+ ])
+
+
+def document(s, voices: bool = False) -> str:
+ """The frontmatter, then exactly what 导出… writes."""
+ return frontmatter(s) + session_store.markdown(s, voices=voices)
+
+
+# Where to put it
+
+def obsidian_configs() -> list:
+ """Obsidian's obsidian.json: the .deb / AppImage one, then the Flatpak's."""
+ config = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")
+ return [os.path.join(config, "obsidian", "obsidian.json"),
+ os.path.expanduser("~/.var/app/md.obsidian.Obsidian/config/obsidian/obsidian.json")]
+
+
+def obsidian_vaults(text: str, exists=os.path.isdir) -> list:
+ """Obsidian's vaults (its obsidian.json), the most recently opened first; only ones that exist."""
+ try:
+ root = json.loads(text)
+ except (ValueError, TypeError):
+ return []
+ vaults = root.get("vaults") if isinstance(root, dict) else None
+ if not isinstance(vaults, dict):
+ return []
+ found = []
+ for v in vaults.values():
+ path = v.get("path") if isinstance(v, dict) else None
+ if not isinstance(path, str) or not exists(path):
+ continue
+ ts = v.get("ts")
+ found.append((path, ts if isinstance(ts, (int, float)) and not isinstance(ts, bool) else 0))
+ found.sort(key=lambda p: p[1], reverse=True)
+ return [p for p, _ in found]
+
+
+def all_vaults() -> list:
+ out = []
+ for f in obsidian_configs():
+ try:
+ with open(f, encoding="utf-8") as h:
+ text = h.read()
+ except OSError:
+ continue
+ out += [v for v in obsidian_vaults(text) if v not in out]
+ return out
+
+
+def vault_of(folder: str, vaults=None) -> str | None:
+ """The Obsidian vault the folder is in (or is), if any."""
+ for v in all_vaults() if vaults is None else vaults:
+ v = v.rstrip("/") or "/"
+ if folder == v or folder.startswith(v + "/"):
+ return v
+ return None
+
+
+def documents_dir() -> str:
+ """The XDG documents folder (xdg-user-dir DOCUMENTS), else ~/Documents. The app asks GLib first."""
+ home = os.path.expanduser("~")
+ try:
+ out = subprocess.run(["xdg-user-dir", "DOCUMENTS"], capture_output=True, text=True, timeout=2).stdout.strip()
+ # Unset, it answers the home folder itself: not a documents folder.
+ if out and os.path.normpath(out) != os.path.normpath(home):
+ return out
+ except (OSError, subprocess.SubprocessError):
+ pass
+ return os.path.join(home, "Documents")
+
+
+def default_folder(vaults=None, documents: str | None = None) -> str:
+ """The suggestion: the most recently opened Obsidian vault's Cicada folder, else Documents › Cicada."""
+ vaults = all_vaults() if vaults is None else vaults
+ if vaults:
+ return os.path.join(vaults[0], "Cicada")
+ return os.path.join(documents or documents_dir(), "Cicada")
+
+
+def short_path(folder: str) -> str:
+ """"工作笔记 › Cicada": the folder and the one it is in."""
+ folder = os.path.normpath(folder)
+ parent = os.path.dirname(folder)
+ return "%s › %s" % (os.path.basename(parent) or parent, os.path.basename(folder) or folder)
+
+
+# Writing (off the main loop)
+
+def _classify(e: BaseException, folder: str) -> tuple:
+ if isinstance(e, PermissionError) or getattr(e, "errno", None) in (errno.EACCES, errno.EPERM):
+ return DENIED, ""
+ if not os.path.isdir(folder):
+ return MISSING, ""
+ return FAILED, (getattr(e, "strerror", None) or str(e) or type(e).__name__)
+
+
+def ensure(folder: str) -> tuple | None:
+ """The folder exists, or is made when only it is missing: never a drive that isn't mounted, so
+ only the last folder, and only when its parent is there."""
+ if os.path.exists(folder):
+ return None if os.path.isdir(folder) else (MISSING, "")
+ if not os.path.isdir(os.path.dirname(os.path.normpath(folder))):
+ return MISSING, ""
+ try:
+ os.mkdir(folder)
+ except FileExistsError:
+ pass
+ except OSError as e:
+ return _classify(e, folder)
+ return None
+
+
+def probe(folder: str) -> tuple | None:
+ """Writes and removes a hidden file: the check after choosing a folder."""
+ p = ensure(folder)
+ if p is not None:
+ return p
+ path = os.path.join(folder, PROBE)
+ try:
+ with open(path, "wb"):
+ pass
+ os.remove(path)
+ return None
+ except OSError as e:
+ return _classify(e, folder)
+
+
+def write_atomic(path: str, data: bytes) -> None:
+ """A temporary file in the same folder, then renamed over: a vault or sync client never sees half
+ a file. Hidden, so a vault doesn't list it meanwhile; the umask's mode, like any saved file."""
+ folder = os.path.dirname(path)
+ tmp = os.path.join(folder, ".cicada-%s.tmp" % secrets.token_hex(4))
+ try:
+ with open(tmp, "xb") as f:
+ f.write(data)
+ os.replace(tmp, path)
+ except BaseException:
+ try:
+ os.remove(tmp)
+ except OSError:
+ pass
+ raise
+
+
+def write_jobs(jobs: list, folder: str, ours: dict) -> list:
+ """jobs: (id, stem, old name, bytes). Outcomes: ("wrote", id, name), ("unchanged", id) or
+ ("stopped", problem, message). Stops at the first problem: the rest would fail the same way."""
+ p = ensure(folder)
+ if p is not None:
+ return [("stopped",) + p]
+ ours = dict(ours)
+ out = []
+ for sid, st, old, data in jobs:
+ mine = {n for k, n in ours.items() if k != sid}
+
+ def taken(candidate, old=old, mine=mine):
+ if candidate == old:
+ return False
+ return candidate in mine or os.path.lexists(os.path.join(folder, candidate))
+ n = file_name(st, taken)
+ path = os.path.join(folder, n)
+ if n == old:
+ try:
+ with open(path, "rb") as f:
+ if f.read() == data:
+ out.append(("unchanged", sid))
+ continue
+ except OSError:
+ pass
+ try:
+ write_atomic(path, data)
+ except Exception as e: # noqa: BLE001 - every failure is a problem shown, never a dead worker
+ out.append(("stopped",) + _classify(e, folder))
+ return out
+ # Renamed: the old file goes, only the one Cicada wrote.
+ if old and old != n:
+ try:
+ os.remove(os.path.join(folder, old))
+ except OSError:
+ pass
+ ours[sid] = n
+ out.append(("wrote", sid, n))
+ return out
+
+
+class Index:
+ """FolderExport.json: the Mac's keys, written the way its JSONEncoder writes them."""
+
+ def __init__(self, folder: str = "", files=None, pending=None, lastFile=None, lastAt=None):
+ self.folder = folder
+ self.files = dict(files or {}) # record id → the file name Cicada wrote
+ self.pending = list(pending or []) # records waiting to be written
+ self.lastFile = lastFile
+ self.lastAt = lastAt
+
+ def to_json(self) -> dict:
+ o = {"folder": self.folder, "files": self.files, "pending": self.pending}
+ if self.lastFile is not None:
+ o["lastFile"] = self.lastFile
+ if self.lastAt is not None:
+ o["lastAt"] = iso_write(self.lastAt)
+ return o
+
+ @staticmethod
+ def read(text: str) -> "Index":
+ o = jsonfmt.parse_object(text) or {}
+ files = o.get("files") if isinstance(o.get("files"), dict) else {}
+ pending = o.get("pending") if isinstance(o.get("pending"), list) else []
+ return Index(folder=o.get("folder") if isinstance(o.get("folder"), str) else "",
+ files={k: v for k, v in files.items() if isinstance(v, str)},
+ pending=[x for x in pending if isinstance(x, str)],
+ lastFile=o.get("lastFile") if isinstance(o.get("lastFile"), str) else None,
+ lastAt=iso_read(o.get("lastAt") if isinstance(o.get("lastAt"), str) else None))
+
+
+def index_path() -> str:
+ """Beside the records' folder, as the Mac keeps it beside Sessions."""
+ return os.path.join(Paths.data(), "FolderExport.json")
+
+
+class FolderExporter:
+ """Writes settled meetings into the chosen folder. Triggers come from any thread; the work runs
+ on one worker. `on_change` listeners fire on the worker (the app hops to its main loop);
+ `on_denied` is the one notification after a meeting, until a write works again."""
+
+ def __init__(self, store, settings, index_file: str | None = None, delay: float = 2.0):
+ self.store = store
+ self.settings = settings
+ self.index_file = index_file or index_path()
+ self.delay = delay
+ self.settling = lambda sid: False # the meeting's final notes pass is running or waiting
+ self.voices = lambda: False # 说话人识别 on: the body names voices, as 导出… does
+ self.on_denied = None
+ self.problem = None # None, DENIED, MISSING or FAILED
+ self.problem_message = ""
+ self.checking = False # checking a newly chosen folder
+ self._gate = threading.RLock()
+ self._work = ThreadPoolExecutor(max_workers=1, thread_name_prefix="FolderExport")
+ self._timer = None
+ self._notified = False
+ self._listeners = []
+ self.index = Index()
+ try:
+ with open(self.index_file, encoding="utf-8") as f:
+ self.index = Index.read(f.read())
+ except OSError:
+ pass
+
+ def on_change(self, listener) -> None:
+ self._listeners.append(listener)
+
+ def _changed(self) -> None:
+ for l in list(self._listeners):
+ l()
+
+ @property
+ def on(self) -> bool:
+ return bool(self.settings.exportOn and self.settings.exportFolder)
+
+ @property
+ def folder(self) -> str | None:
+ return self.settings.exportFolder or None
+
+ def file(self, sid: str) -> str | None:
+ with self._gate:
+ if not self.on or self.index.folder != self.settings.exportFolder:
+ return None
+ n = self.index.files.get(sid)
+ return os.path.join(self.settings.exportFolder, n) if n else None
+
+ def is_pending(self, sid: str) -> bool:
+ with self._gate:
+ return self.on and sid in self.index.pending
+
+ def ready(self, s) -> bool:
+ """Ended, not being imported, with something said, and not the live meeting."""
+ return s.endedAt is not None and not s.importing and bool(s.lines) and s.id != self.store.live
+
+ def unwritten(self) -> list:
+ """Settled records not written to this folder yet (以前的会议)."""
+ with self._gate:
+ files, pending = set(self.index.files), set(self.index.pending)
+ return [s for s in self.store.all() if self.ready(s) and s.id not in files and s.id not in pending]
+
+ # Triggers
+
+ def ended(self, sid: str) -> None:
+ """A meeting ended: written once it is settled."""
+ if not self.on:
+ return
+ with self._gate:
+ if sid not in self.index.pending:
+ self.index.pending.append(sid)
+ self._save()
+ self._schedule()
+
+ def saved(self, sid: str) -> None:
+ """A record was saved: rewritten if it was written, written if it is waiting."""
+ if not self.on:
+ return
+ with self._gate:
+ if sid not in self.index.files and sid not in self.index.pending:
+ return
+ if sid not in self.index.pending:
+ self.index.pending.append(sid)
+ self._schedule()
+
+ def settled(self, sid: str) -> None:
+ """The meeting's final notes pass is over, done or not."""
+ with self._gate:
+ waiting = self.on and sid in self.index.pending
+ if waiting:
+ self._schedule()
+
+ def write_all(self) -> None:
+ """也存一份: every settled record not written yet. Never a notification."""
+ if not self.on:
+ return
+ ids = [s.id for s in self.unwritten()]
+ with self._gate:
+ self.index.pending += [i for i in ids if i not in self.index.pending]
+ self._save()
+ self._submit(False)
+
+ def retry(self) -> None:
+ """At launch and when a window comes forward: what is still waiting."""
+ with self._gate:
+ waiting = self.on and bool(self.index.pending)
+ if waiting:
+ self._schedule(0.5, from_meeting=False)
+
+ def deleted(self, sid: str) -> None:
+ """The record went; its file stays."""
+ with self._gate:
+ self.index.files.pop(sid, None)
+ if sid in self.index.pending:
+ self.index.pending.remove(sid)
+ self._save()
+
+ # Choosing the folder
+
+ def choose(self, folder: str) -> None:
+ """A new folder (or the same one after a fix): a new index for a new folder, and a check that
+ it can be written now, while settings is open, rather than when a meeting ends."""
+ folder = os.path.normpath(os.path.expanduser(folder))
+ self.settings.exportFolder = folder
+ self.settings.exportOn = True
+ self.settings.save()
+ with self._gate:
+ if self.index.folder != folder:
+ self.index = Index(folder=folder)
+ self._save()
+ self.checking = True
+ self.problem, self.problem_message = None, ""
+ self._changed()
+
+ def check():
+ result = probe(folder)
+ with self._gate:
+ self.checking = False
+ self.problem, self.problem_message = result or (None, "")
+ if result is None:
+ self._notified = False
+ Log.d("folder export: check %s" % (result[0] if result else "ok"))
+ self._changed()
+ if result is None:
+ self.retry()
+ self._work.submit(check)
+
+ def turn_off(self) -> None:
+ self.settings.exportOn = False
+ self.settings.save()
+ with self._gate:
+ self.problem, self.problem_message = None, ""
+ self._changed()
+
+ # Writing
+
+ def _schedule(self, delay: float | None = None, from_meeting: bool = True) -> None:
+ with self._gate:
+ if self._timer is not None:
+ self._timer.cancel()
+ t = threading.Timer(self.delay if delay is None else delay, self._submit, (from_meeting,))
+ t.daemon = True
+ t.from_meeting = from_meeting
+ self._timer = t
+ t.start()
+
+ def _submit(self, from_meeting: bool) -> None:
+ self._work.submit(self._flush, from_meeting)
+
+ def wait(self) -> None:
+ """Until every write asked for so far is done (tests, the debug commands)."""
+ with self._gate:
+ t, self._timer = self._timer, None
+ if t is not None and t.is_alive():
+ t.cancel()
+ self._submit(t.from_meeting)
+ self._work.submit(lambda: None).result()
+
+ def _flush(self, from_meeting: bool) -> None:
+ try:
+ self._flush_now(from_meeting)
+ except Exception as e: # noqa: BLE001 - keep the worker alive for the next try
+ Log.d("folder export: flush failed %s" % type(e).__name__)
+
+ def _flush_now(self, from_meeting: bool) -> None:
+ if not self.on:
+ return
+ folder = self.settings.exportFolder
+ jobs = []
+ with self._gate:
+ if self.index.folder != folder:
+ self.index = Index(folder=folder, pending=self.index.pending)
+ for sid in list(self.index.pending):
+ s = self.store.snapshot(sid)
+ if s is None:
+ self.index.pending.remove(sid)
+ continue
+ if not self.ready(s) or self.settling(sid):
+ continue
+ try:
+ jobs.append((sid, stem(s), self.index.files.get(sid), document(s, self.voices()).encode("utf-8")))
+ except Exception as e: # noqa: BLE001 - one record that won't render must not hold up the rest
+ Log.d("folder export: %s not rendered %s" % (sid, type(e).__name__))
+ self._save()
+ ours = dict(self.index.files)
+ if not jobs:
+ return
+ outcomes = write_jobs(jobs, folder, ours)
+ stopped = None
+ with self._gate:
+ if self.index.folder != folder:
+ return # another folder was chosen meanwhile
+ for o in outcomes:
+ if o[0] == "wrote":
+ self.index.files[o[1]] = o[2]
+ if o[1] in self.index.pending:
+ self.index.pending.remove(o[1])
+ self.index.lastFile, self.index.lastAt = o[2], now()
+ elif o[0] == "unchanged":
+ if o[1] in self.index.pending:
+ self.index.pending.remove(o[1])
+ else:
+ stopped = o
+ self._save()
+ self.problem, self.problem_message = (stopped[1], stopped[2]) if stopped else (None, "")
+ notify = False
+ if stopped is None:
+ self._notified = False
+ elif stopped[1] == DENIED and from_meeting and not self._notified:
+ self._notified = notify = True
+ Log.d("folder export: %d written, %s" % (sum(1 for o in outcomes if o[0] == "wrote"), stopped[1] if stopped else "ok"))
+ self._changed()
+ if notify and self.on_denied is not None:
+ self.on_denied()
+
+ def _save(self) -> None:
+ """Under the gate."""
+ try:
+ os.makedirs(os.path.dirname(self.index_file), exist_ok=True)
+ write_atomic(self.index_file, jsonfmt.write(self.index.to_json()).encode("utf-8"))
+ except OSError as e:
+ Log.d("folder export: index not saved %s" % type(e).__name__)
+
+ def state(self) -> dict:
+ """For the debug socket."""
+ with self._gate:
+ return {"on": self.on, "folder": self.folder, "problem": self.problem, "message": self.problem_message,
+ "checking": self.checking, "index": self.index.to_json(), "unwritten": [s.id for s in self.unwritten()]}
diff --git a/linux/cicada/core/notes.py b/linux/cicada/core/notes.py
index b801fd6..ce78be1 100644
--- a/linux/cicada/core/notes.py
+++ b/linux/cicada/core/notes.py
@@ -45,6 +45,24 @@ class NotesEngine:
self.shown_id = None # the session the notes belong to (stays set after the meeting ends)
self.language = lambda sid: "Simplified Chinese" # a meeting's notes language (English name), from 纪要语言
self.working_id = None # the record being written now, for a "正在整理纪要…" next to it
+ # Final passes asked for and not over yet (queued in a pool, running or waiting their turn),
+ # and the call when one is over, notes written or not (存到文件夹 waits for it).
+ self._finals: list = []
+ self.final_done = None
+
+ def settling(self, sid: str) -> bool:
+ """The meeting's final pass is still to come, running or waiting: also while the meeting is
+ still this engine's own, before listening's pool gets to finish()."""
+ with self._gate:
+ return sid == self._session_id or sid in self._finals
+
+ def _final_over(self, sid: str) -> None:
+ with self._gate:
+ if sid in self._finals:
+ self._finals.remove(sid)
+ done = sid not in self._finals
+ if done and self.final_done is not None:
+ self.final_done(sid)
def on_change(self, listener) -> None:
self._listeners.append(listener)
@@ -90,6 +108,8 @@ class NotesEngine:
self._stop_ticker()
sid = self._session_id
self._session_id = None
+ if sid is not None:
+ self._finals.append(sid)
if sid is not None:
self._update(sid, final=True)
@@ -112,6 +132,8 @@ class NotesEngine:
def generate(self, sid: str) -> None:
"""Notes for a finished meeting that has none (runs in the background)."""
+ with self._gate:
+ self._finals.append(sid)
self._work.submit(self._update, sid, True)
def _sync_key(self) -> None:
@@ -151,25 +173,34 @@ class NotesEngine:
self._work.submit(self._update, sid, False)
def _update(self, sid: str, final: bool, fresh: bool = False) -> None:
+ over = None # a final pass that ends here without running
+ start = False
with self._gate:
if self._in_flight:
if final:
- self._pending_final = sid
+ # One waiting slot: the pass it held won't run, so that one is over.
+ over, self._pending_final = self._pending_final, sid
elif fresh:
self._pending_fresh = sid # after the round in the old language
- return
- session = self.store.get(sid)
- if session is None or not session.lines:
- return
- if not self.ling.has_key:
- self.status = NO_KEY
- self._changed()
- return
- self._in_flight = True
- self.working_id = sid
- self._last_attempt = time.time()
- self.status = UPDATING
- base = MeetingNotes() if final or fresh else (self.notes if sid == self.shown_id else (session.notes or MeetingNotes()))
+ else:
+ session = self.store.get(sid)
+ if session is None or not session.lines:
+ over = sid if final else None
+ elif not self.ling.has_key:
+ self.status = NO_KEY
+ over = sid if final else None
+ self._changed()
+ else:
+ start = True
+ self._in_flight = True
+ self.working_id = sid
+ self._last_attempt = time.time()
+ self.status = UPDATING
+ base = MeetingNotes() if final or fresh else (self.notes if sid == self.shown_id else (session.notes or MeetingNotes()))
+ if over is not None:
+ self._final_over(over)
+ if not start:
+ return
self._changed()
try:
lines = self.store.lines(sid)
@@ -233,6 +264,8 @@ class NotesEngine:
queued, again = self._pending_final, self._pending_fresh
self._pending_final = self._pending_fresh = None
self._changed()
+ if final:
+ self._final_over(sid)
if queued is not None:
self._update(queued, final=True)
elif again is not None:
diff --git a/linux/cicada/core/session_store.py b/linux/cicada/core/session_store.py
index d0e841e..620a1fe 100644
--- a/linux/cicada/core/session_store.py
+++ b/linux/cicada/core/session_store.py
@@ -21,6 +21,7 @@ class SessionStore:
self._timer = None
self._listeners = []
self._word_listeners = []
+ self._save_listeners = []
self.live: str | None = None # the meeting being listened to (the Mac's liveID)
self._load()
@@ -32,6 +33,11 @@ class SessionStore:
or a half sentence that grew. What 结束会议 counts as someone speaking (MeetingEndWatch.heard)."""
self._word_listeners.append(listener)
+ def on_save(self, listener) -> None:
+ """`listener(sid)` after a record was written to disk (存到文件夹 follows its changes). Fires on
+ the thread that saved it."""
+ self._save_listeners.append(listener)
+
def _words(self, sid: str) -> None:
for l in list(getattr(self, "_word_listeners", [])):
l(sid)
@@ -90,6 +96,12 @@ class SessionStore:
with self._gate:
return self._sessions.get(sid)
+ def snapshot(self, sid: str) -> Session | None:
+ """A copy of a record no other thread changes while it is read (a file being written from it)."""
+ with self._gate:
+ s = self._sessions.get(sid)
+ return Session.read(s.write()) if s else None
+
def lines(self, sid: str) -> list:
"""A copy of a record's lines, safe to read while listening adds to them."""
with self._gate:
@@ -338,6 +350,9 @@ class SessionStore:
os.replace(tmp, os.path.join(folder, "session.json"))
except OSError as e:
Log.d("store: save failed %s" % type(e).__name__)
+ continue
+ for l in list(self._save_listeners):
+ l(sid)
def default_title(at: datetime) -> str:
diff --git a/linux/cicada/core/settings.py b/linux/cicada/core/settings.py
index 21dbbef..d685946 100644
--- a/linux/cicada/core/settings.py
+++ b/linux/cicada/core/settings.py
@@ -47,6 +47,10 @@ class AppSettings:
# 同声传译: what I say is interpreted and spoken into 知了 麦克风 (the Mac's speakEnabled etc.).
# 保存会议录音 (the Mac's recordAudio): system.m4a beside session.json, when GStreamer has an AAC encoder.
"recordAudio": True,
+ # 存到文件夹 (the Mac's keys): settled meetings also written as Markdown into exportFolder (a
+ # path; "" until one is chosen). See folder_export.py.
+ "exportOn": False,
+ "exportFolder": "",
# 会中改正听错的词 (the Mac's keys): finished sentences carry the word list to the AI service, which
# points out misheard words (correction.py); askNames: a new name is asked about once.
"fixMisheard": True,
diff --git a/linux/scripts/cicadactl b/linux/scripts/cicadactl
index ee0bc78..cf0913c 100755
--- a/linux/scripts/cicadactl
+++ b/linux/scripts/cicadactl
@@ -9,6 +9,7 @@
fix-edit <line>=<text>[|one][|keep0] | fix-editor <line>=<text> | vocab-add <word>=<heard>[|…] | vocab-state
word-list [import <text>|edit <word>|heard <word>=<form>|delete <word>] (改正听错的词, debug.py › _fixes)
share <id>[,full][,pw] | unshare <id> | share-last | shareSheet <id>|"" | share-ui <action> (分享…, debug.py › _share)
+ export-folder <path>|off|on | export-state | export-all | export-retry | export-choose (存到文件夹, debug.py › _export)
Run it inside the Linux session (linux/vm/vmctl.sh ssh does that for the test VM)."""
import os
import socket
diff --git a/linux/strings/en.lproj/Linux.strings b/linux/strings/en.lproj/Linux.strings
index 446f918..348362b 100644
--- a/linux/strings/en.lproj/Linux.strings
+++ b/linux/strings/en.lproj/Linux.strings
@@ -210,3 +210,4 @@
"每句多发一次文字请求" = "One more text request per sentence";
/* 在 Dock 中显示: the top bar, not a menu bar */
"关掉后只在顶栏,打开窗口时才出现" = "Off: top bar only, in the Dock just while a window is open";
+"改一下这个文件夹的权限,或换个文件夹" = "Change this folder's permissions, or pick another folder";
diff --git a/linux/strings/ja.lproj/Linux.strings b/linux/strings/ja.lproj/Linux.strings
index 4b7e9e1..c3116b1 100644
--- a/linux/strings/ja.lproj/Linux.strings
+++ b/linux/strings/ja.lproj/Linux.strings
@@ -210,3 +210,4 @@
"每句多发一次文字请求" = "1 文ごとにテキストのリクエストが 1 回増えます";
/* 在 Dock 中显示 */
"关掉后只在顶栏,打开窗口时才出现" = "オフ:トップバーのみ。ウインドウを開いている間だけ Dock に表示";
+"改一下这个文件夹的权限,或换个文件夹" = "このフォルダのアクセス権を変更するか、別のフォルダを選んでください";
diff --git a/linux/strings/ko.lproj/Linux.strings b/linux/strings/ko.lproj/Linux.strings
index 3f133e4..1dc7318 100644
--- a/linux/strings/ko.lproj/Linux.strings
+++ b/linux/strings/ko.lproj/Linux.strings
@@ -210,3 +210,4 @@
"每句多发一次文字请求" = "문장마다 텍스트 요청이 한 번 더 감";
/* 在 Dock 中显示 */
"关掉后只在顶栏,打开窗口时才出现" = "끄면 상단 바에만 있고, 창을 열 때만 Dock에 나타납니다";
+"改一下这个文件夹的权限,或换个文件夹" = "이 폴더의 권한을 바꾸거나 다른 폴더를 고르세요";
diff --git a/linux/tests/test_core.py b/linux/tests/test_core.py
index 69d6a2f..21bb0b9 100644
--- a/linux/tests/test_core.py
+++ b/linux/tests/test_core.py
@@ -568,6 +568,26 @@ class Notes(Base):
notes._sync_key()
self.assertEqual(notesmod.IDLE, notes.status)
+ def test_final_pass_settles(self):
+ """存到文件夹 waits while the final pass is to come or running, and hears when it is over, with
+ notes or without (no lines, a failed reply)."""
+ store = SessionStore()
+ ling = client(Fake(lambda body: reply("not json")))
+ notes = NotesEngine(ling, store)
+ done = []
+ notes.final_done = done.append
+ s = store.begin()
+ store.append(s.id, TranscriptLine(id="h1-1", t=0, src="x", srcLang="en", dstLang="zh-CN"))
+ notes.begin(s.id)
+ self.assertTrue(notes.settling(s.id), "still the meeting's: finish() hasn't run yet")
+ store.end(s.id)
+ notes.finish()
+ self.assertFalse(notes.settling(s.id))
+ self.assertEqual([s.id], done)
+ notes.generate("nothing-here")
+ notes._work.shutdown(wait=True)
+ self.assertEqual([s.id, "nothing-here"], done)
+
def test_unreachable_is_the_notes_own_and_clears_when_the_service_answers(self):
# NotesWindow.swift › banner: only the notes' own network failure says "can't reach", it ends
# when anything reaches the service again, and a record opened later doesn't inherit it.
diff --git a/linux/tests/test_folder_export.py b/linux/tests/test_folder_export.py
new file mode 100644
index 0000000..198c3c1
--- /dev/null
+++ b/linux/tests/test_folder_export.py
@@ -0,0 +1,292 @@
+"""存到文件夹: the file name and frontmatter are a contract with the Mac and the other ports
+(Tests/fixtures/folder-export), then the exporter against a folder in a temporary directory."""
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import stat
+import sys
+import tempfile
+import unittest
+from datetime import timedelta
+from zoneinfo import ZoneInfo
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.dirname(HERE))
+REPO = os.path.dirname(os.path.dirname(HERE))
+FIXTURES = os.path.join(REPO, "Tests", "fixtures", "folder-export")
+
+from cicada.core import folder_export as fx, strings # noqa: E402
+from cicada.core.models import Session # noqa: E402
+from cicada.core.session_store import SessionStore, default_title # noqa: E402
+from cicada.core.settings import AppSettings # noqa: E402
+from cicada.core.support import Paths # noqa: E402
+
+
+def read(name: str) -> str:
+ with open(os.path.join(FIXTURES, name), encoding="utf-8", newline="") as f:
+ return f.read()
+
+
+def cases() -> dict:
+ return json.loads(read("cases.json"))
+
+
+def session() -> Session:
+ return Session.read(read("session.json"))
+
+
+class FormatTests(unittest.TestCase):
+ def test_frontmatter_bytes(self):
+ tz = ZoneInfo(cases()["timeZone"])
+ self.assertEqual(read("frontmatter.md"), fx.frontmatter(session(), tz))
+
+ def test_file_name(self):
+ c = cases()
+ st = fx.stem(session(), ZoneInfo(c["timeZone"]))
+ self.assertEqual(c["fileName"], fx.file_name(st, lambda _n: False))
+
+ def test_names(self):
+ for given, want in cases()["names"]:
+ self.assertEqual(want, fx.safe_name(given), given)
+
+ def test_stems(self):
+ c = cases()
+ s = session()
+ for title, want in c["stems"]:
+ s.title = title
+ self.assertEqual(want, fx.stem(s, ZoneInfo(c["timeZone"])))
+
+ def test_escapes(self):
+ for given, want in cases()["escapes"]:
+ self.assertEqual(want, fx.quote(given), given)
+ # Short forms only for \n \r \t; json.dumps would write \b and \f.
+ self.assertEqual('"\\u0008\\u000c\\u001f"', fx.quote("\b\f\x1f"))
+
+ def test_collisions(self):
+ for c in cases()["collisions"]:
+ self.assertEqual(c["want"], fx.file_name(c["stem"], lambda n, t=c["taken"]: n in t))
+
+ def test_name_precedence(self):
+ """The user's title, else the notes', else the imported file's; never the display title."""
+ s = session()
+ s.renamed = False
+ s.title = default_title(s.startedAt)
+ self.assertEqual("产品路线评审", fx.name(s))
+ s.notes = None
+ self.assertEqual("", fx.name(s))
+ s.sourceFile = "Weekly sync.m4a"
+ self.assertEqual("Weekly sync", fx.name(s))
+ self.assertIn('source: "file"\nnotes: "none"', fx.frontmatter(s))
+ # An older record (no `renamed`): any title but the default one is the user's.
+ s.renamed = None
+ s.title = "周会"
+ self.assertEqual("周会", fx.name(s))
+
+ def test_utc_offset_and_draft(self):
+ s = session()
+ s.notes.final = False
+ text = fx.frontmatter(s, ZoneInfo("UTC"))
+ self.assertIn('started: "2026-11-06T06:00:00+00:00"', text)
+ self.assertIn('notes: "draft"', text)
+
+ def test_obsidian_vaults(self):
+ text = '{"vaults":{"a":{"path":"/v/old","ts":1},"b":{"path":"/v/new","ts":5,"open":true},"c":{"path":"/gone","ts":9}}}'
+ self.assertEqual(["/v/new", "/v/old"], fx.obsidian_vaults(text, lambda p: p != "/gone"))
+ self.assertEqual([], fx.obsidian_vaults("not json"))
+ self.assertEqual("/v/new/Cicada", fx.default_folder(["/v/new"]))
+ self.assertEqual("/docs/Cicada", fx.default_folder([], "/docs"))
+ self.assertEqual("/v/new", fx.vault_of("/v/new/Cicada", ["/v/new"]))
+ self.assertIsNone(fx.vault_of("/v/newer", ["/v/new"]))
+
+ def test_short_path(self):
+ self.assertEqual("工作笔记 › Cicada", fx.short_path("/home/me/工作笔记/Cicada/"))
+
+
+class ExporterTests(unittest.TestCase):
+ def setUp(self):
+ strings.load("zh-Hans", [os.path.join(REPO, "Resources")])
+ self.home = tempfile.mkdtemp()
+ Paths.home_override = self.home
+ self.folder = os.path.join(self.home, "vault", "Cicada")
+ os.makedirs(os.path.dirname(self.folder))
+ self.store = SessionStore()
+ self.settings = AppSettings()
+ self.settings.save = lambda: None
+ self.ex = self.exporter()
+ self.denied = 0
+
+ def tearDown(self):
+ Paths.home_override = None
+ for root, dirs, _files in os.walk(self.home):
+ for d in dirs:
+ os.chmod(os.path.join(root, d), 0o700)
+ shutil.rmtree(self.home, ignore_errors=True)
+
+ def exporter(self):
+ ex = fx.FolderExporter(self.store, self.settings, delay=0.01)
+ ex.on_denied = lambda: setattr(self, "denied", self.denied + 1)
+ return ex
+
+ def add(self, sid="20261106-140000", title="产品路线评审", minutes=0) -> Session:
+ s = session()
+ s.id = sid
+ s.title = title
+ s.startedAt = s.startedAt + timedelta(minutes=minutes)
+ s.endedAt = s.startedAt + timedelta(minutes=48)
+ self.store.import_session(s)
+ return s
+
+ def files(self) -> list:
+ return sorted(os.listdir(self.folder))
+
+ def test_written_rewritten_moved(self):
+ self.ex.choose(self.folder)
+ self.ex.wait()
+ self.assertIsNone(self.ex.problem)
+ self.add()
+ self.ex.ended("20261106-140000")
+ self.ex.wait()
+ name = self.ex.index.files["20261106-140000"]
+ self.assertTrue(name.endswith(" 产品路线评审.md"))
+ self.assertEqual([name], self.files())
+ with open(os.path.join(self.folder, name), encoding="utf-8") as f:
+ text = f.read()
+ self.assertTrue(text.startswith('---\ncicada: 1\nid: "20261106-140000"\n'))
+ self.assertIn("\n---\n# 产品路线评审\n", text)
+ self.assertEqual([], self.ex.index.pending)
+ self.assertEqual(name, self.ex.index.lastFile)
+ # Unchanged: not written again.
+ mtime = os.stat(os.path.join(self.folder, name)).st_mtime_ns
+ self.ex.saved("20261106-140000")
+ self.ex.wait()
+ self.assertEqual(mtime, os.stat(os.path.join(self.folder, name)).st_mtime_ns)
+ # Renamed: the file moves.
+ self.store.rename("20261106-140000", "路线")
+ self.store.flush()
+ self.ex.saved("20261106-140000")
+ self.ex.wait()
+ self.assertEqual([name.replace("产品路线评审", "路线")], self.files())
+ # Deleted in Cicada: the file stays.
+ self.ex.deleted("20261106-140000")
+ self.assertEqual(1, len(self.files()))
+ # The index survives a restart.
+ self.assertEqual(self.ex.index.folder, self.exporter().index.folder)
+
+ def test_never_overwrites_a_foreign_file(self):
+ self.ex.choose(self.folder)
+ self.ex.wait()
+ s = self.add()
+ mine = fx.stem(s) + ".md"
+ with open(os.path.join(self.folder, mine), "w") as f:
+ f.write("someone's")
+ self.ex.ended(s.id)
+ self.ex.wait()
+ self.assertEqual(fx.stem(s) + " 2.md", self.ex.index.files[s.id])
+ with open(os.path.join(self.folder, mine)) as f:
+ self.assertEqual("someone's", f.read())
+
+ def test_waits_for_the_final_notes(self):
+ self.ex.choose(self.folder)
+ self.ex.wait()
+ s = self.add()
+ busy = {s.id}
+ self.ex.settling = lambda sid: sid in busy
+ self.ex.ended(s.id)
+ self.ex.wait()
+ self.assertEqual([s.id], self.ex.index.pending)
+ self.assertEqual([], self.files())
+ busy.clear()
+ self.ex.settled(s.id)
+ self.ex.wait()
+ self.assertEqual([], self.ex.index.pending)
+ self.assertEqual(1, len(self.files()))
+
+ def test_write_all_and_new_folder(self):
+ self.add("20261106-140000", "一")
+ self.add("20261106-150000", "二", minutes=60)
+ self.ex.choose(self.folder)
+ self.ex.wait()
+ self.assertEqual(2, len(self.ex.unwritten()))
+ self.ex.write_all()
+ self.ex.wait()
+ self.assertEqual(2, len(self.files()))
+ self.assertEqual([], self.ex.unwritten())
+ other = os.path.join(self.home, "other")
+ self.ex.choose(other)
+ self.ex.wait()
+ self.assertEqual({}, self.ex.index.files)
+ self.assertEqual(2, len(self.ex.unwritten()))
+ self.assertEqual(2, len(self.files())) # the old folder's files stay
+
+ def test_missing_then_back(self):
+ self.ex.choose(self.folder)
+ self.ex.wait()
+ s = self.add()
+ shutil.rmtree(os.path.dirname(self.folder)) # the drive went
+ self.ex.ended(s.id)
+ self.ex.wait()
+ self.assertEqual(fx.MISSING, self.ex.problem)
+ self.assertEqual([s.id], self.ex.index.pending)
+ self.assertEqual(0, self.denied)
+ os.makedirs(os.path.dirname(self.folder)) # back: only the last folder is made again
+ self.ex.retry()
+ self.ex.wait()
+ self.assertIsNone(self.ex.problem)
+ self.assertEqual(1, len(self.files()))
+
+ @unittest.skipIf(hasattr(os, "geteuid") and os.geteuid() == 0, "root writes anywhere")
+ def test_denied_notifies_once(self):
+ self.ex.choose(self.folder)
+ self.ex.wait()
+ self.add("20261106-140000", "一")
+ self.add("20261106-150000", "二", minutes=60)
+ os.chmod(self.folder, stat.S_IRUSR | stat.S_IXUSR)
+ self.ex.write_all()
+ self.ex.wait()
+ self.assertEqual(fx.DENIED, self.ex.problem)
+ self.assertEqual(0, self.denied) # never for 也存一份
+ self.ex.ended("20261106-140000")
+ self.ex.wait()
+ self.ex.ended("20261106-150000")
+ self.ex.wait()
+ self.assertEqual(1, self.denied)
+ self.assertEqual(2, len(self.ex.index.pending))
+ os.chmod(self.folder, 0o700)
+ self.ex.retry()
+ self.ex.wait()
+ self.assertIsNone(self.ex.problem)
+ self.assertEqual(2, len(self.files()))
+
+ def test_a_record_that_fails_to_render_holds_up_nothing(self):
+ self.ex.choose(self.folder)
+ self.ex.wait()
+ self.add("20261106-140000", "一")
+ self.add("20261106-150000", "二", minutes=60)
+ real = fx.document
+
+ def document(s, voices=False):
+ if s.id == "20261106-140000":
+ raise ValueError("bad record")
+ return real(s, voices)
+ fx.document = document
+ try:
+ for _ in range(2):
+ self.ex.write_all()
+ self.ex.wait()
+ finally:
+ fx.document = real
+ self.assertEqual(1, len(self.files()), "the good one, once")
+ self.assertEqual(["20261106-140000"], self.ex.index.pending)
+
+ def test_off_writes_nothing(self):
+ s = self.add()
+ self.ex.ended(s.id)
+ self.ex.wait()
+ self.assertEqual([], self.ex.index.pending)
+ self.assertFalse(os.path.exists(self.folder))
+
+
+if __name__ == "__main__":
+ unittest.main()