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

wqugurubd1ccb604103
diff --git a/windows/README.md b/windows/README.md
index 560698c..293fca0 100644
--- a/windows/README.md
+++ b/windows/README.md
@@ -7,6 +7,7 @@ Cicada 的 Windows 版:把电脑播放的声音变成双语字幕和实时纪
- 改正听错的词:和 Mac 版同样的规则和提示词(读音相近才直接改,拼音用 `src/Cicada.Core/Data/pinyin.tsv`,由 Apple 的 ICU/CLDR 汉字转拼音一次生成;新名字先问;词表 `vocabulary.json` 和 Mac 同格式)。Ming 一次给出原文和译文,没有单独的文字翻译请求可搭,所以开着时每句话会多发一次文字请求。没有声音也能试:`cicadactl silentlisten zh-CN`,再 `heard <一句话>`。
- 纪要、记录格式、提示词、多语言文案都和 Mac 版一致;文案的英日韩翻译直接用 `Resources/*.lproj/Localizable.strings`,Windows 独有的在 `src/Cicada/Strings/`。
- 新版本:启动时和每 4 小时查一次 GitHub Releases(`UpdateChecker`),只认带 Windows 安装包的发布;有新版本时托盘图标出现红点、每个版本发一次通知(正在听时等会议结束),托盘面板和设置 › 关于也会提示。点“安装”由知了自己下载这台电脑对应架构的 `Cicada-<版本>-Windows-x64.exe` / `-ARM64.exe`(1.1.0 只认 `Cicada-Setup.exe` 这两个旧名字,发布时一并附上)、对照 `checksums.txt` 校验后安装并重新打开,不经过浏览器,所以 SmartScreen 不拦。开发版只在设了 `CICADA_UPDATE_FEED` 或用 `updatefeed` 调试命令时才查。
+- 存到文件夹:设置 › 隐私与启动 › 会后存一份。会议整理好后存成一个 Markdown 文件(文件名和开头的 frontmatter 和 Mac 版一样,`Tests/fixtures/folder-export` 是约定),默认放在最近打开的 Obsidian 库里的 `Cicada` 文件夹,没有就是 文档\Cicada;记了哪些写在记录旁边的 `FolderExport.json`。写入先写同一文件夹里的临时文件再改名。写不进去时(Defender 的受控文件夹访问,或文件夹本身的权限)设置里和会议记录里各有一行;文件夹在文档、桌面等受保护的位置时多一个“打开 Windows 安全中心”,这时 Windows 自己会发通知,知了不再发,其他位置会后发一次。调试:`cicadactl export folder <路径>`、`export all`、`export`(状态)。
- 分享:会议记录里的“分享…”把纪要(或纪要和双语全文)变成 cicada.indaloop.app 上的链接,分享文档和 Mac 版逐字节相同;上传前服务器检查有没有密钥等敏感内容。设备密钥是 Ed25519(.NET 没有自带,`Cicada.Core/Ed25519.cs` 按 RFC 8032 实现,用 RFC 的测试向量验证),它和每个链接的管理令牌、密码都用 DPAPI 封存在 `share-device.json` 和 `Shares\` 里,不进会议记录、导出和日志。
## 目录
diff --git a/windows/scripts/cicadactl.ps1 b/windows/scripts/cicadactl.ps1
index 8fdfe5a..e3d1881 100644
--- a/windows/scripts/cicadactl.ps1
+++ b/windows/scripts/cicadactl.ps1
@@ -6,6 +6,7 @@
# 改正听错的词: silentlisten zh-CN | heard <text> | fixstate | fixanswer yes|no | fixlater | fixrevert <line> | fixedit <line>=<text>[|one][|keep0] | fixundo | vocabadd Morpho=莫拉 | vocabstate (… @<id> for another meeting)
# 分享…: share "<id>[,full][,pw]" | unshare <id> | sharesheet "<id>[,full][,pw][,names][,30|365][,go]" | sharesheet leaveout | sharesheet | shareinfo <id>
# (quote anything with a comma: PowerShell would make it a list)
+# 存到文件夹: export [state] | export on | off | folder C:\Notes\Cicada | choose (the 存到哪里 dialog) | all (也存一份) | retry (state › export too); rename <id> <title>
param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Command)
$pipe = New-Object System.IO.Pipes.NamedPipeClientStream(".", "cicada-dev", [System.IO.Pipes.PipeDirection]::InOut)
$pipe.Connect(3000)
diff --git a/windows/src/Cicada.Core/FolderExport.cs b/windows/src/Cicada.Core/FolderExport.cs
new file mode 100644
index 0000000..32b4d14
--- /dev/null
+++ b/windows/src/Cicada.Core/FolderExport.cs
@@ -0,0 +1,580 @@
+using System.Globalization;
+using System.Text;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+
+namespace Cicada;
+
+/// 存到文件夹: 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.
+public static class 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.
+ public static string Name(Session s)
+ {
+ if (s.Renamed ?? !s.Title.StartsWith("会议 ", StringComparison.Ordinal)) return s.Title;
+ if (s.Notes?.Title is { Length: > 0 } t) return t;
+ if (s.SourceFile is { } file) return Path.GetFileNameWithoutExtension(file);
+ return "";
+ }
+
+ /// 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).
+ public static string SafeName(string name)
+ {
+ var spaced = new StringBuilder();
+ foreach (var r in name.EnumerateRunes())
+ spaced.Append(r.Value < 0x20 || (r.IsAscii && "/\\:*?\"<>|#^[]".Contains((char)r.Value)) ? " " : r.ToString());
+ // Runs of whitespace (any Unicode space, as Swift's isWhitespace) become one space.
+ var joined = new StringBuilder();
+ bool space = false;
+ foreach (var r in spaced.ToString().EnumerateRunes())
+ {
+ if (Rune.IsWhiteSpace(r)) { space = true; continue; }
+ if (space && joined.Length > 0) joined.Append(' ');
+ space = false;
+ joined.Append(r.ToString());
+ }
+ var output = Trim(joined.ToString());
+ if (Encoding.UTF8.GetByteCount(output) > 120)
+ {
+ var cut = new StringBuilder();
+ int bytes = 0;
+ foreach (var r in output.EnumerateRunes())
+ {
+ bytes += r.Utf8SequenceLength;
+ if (bytes > 120) break;
+ cut.Append(r.ToString());
+ }
+ output = Trim(cut.ToString());
+ }
+ return output;
+ }
+
+ static string Trim(string s) => s.Trim(' ', '.');
+
+ public static string Stem(Session s, TimeZoneInfo? zone = null)
+ {
+ var date = Local(s.StartedAt, zone).ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture);
+ var safe = SafeName(Name(s));
+ return safe.Length == 0 ? date : $"{date} {safe}";
+ }
+
+ /// `stem.md`, or `stem 2.md`, `stem 3.md`… when a name is taken.
+ public static string FileName(string stem, Func<string, bool> taken)
+ {
+ for (int n = 1; ; n++)
+ {
+ var name = n == 1 ? $"{stem}.md" : $"{stem} {n}.md";
+ if (!taken(name)) return name;
+ }
+ }
+
+ /// A JSON-style double-quoted string, which YAML reads as is.
+ public static string Quote(string s)
+ {
+ var b = new StringBuilder("\"");
+ foreach (var c in s)
+ {
+ switch (c)
+ {
+ case '\\': b.Append("\\\\"); break;
+ case '"': b.Append("\\\""); break;
+ case '\n': b.Append("\\n"); break;
+ case '\r': b.Append("\\r"); break;
+ case '\t': b.Append("\\t"); break;
+ case < ' ': b.Append($"\\u{(int)c:x4}"); break;
+ default: b.Append(c); break;
+ }
+ }
+ return b.Append('"').ToString();
+ }
+
+ /// Joined with "\n" whatever the system: the bytes are the contract.
+ public static string Frontmatter(Session s, TimeZoneInfo? zone = null)
+ {
+ var ended = s.EndedAt ?? s.StartedAt;
+ // Language codes are ASCII, where ordinal order is code point order.
+ var languages = s.Lines.Select(l => l.SrcLang).Distinct().OrderBy(x => x, StringComparer.Ordinal);
+ var notes = s.Notes is not { IsEmpty: false } n ? "none" : n.Final ? "final" : "draft";
+ string[] lines =
+ [
+ "---",
+ "cicada: 1",
+ $"id: {Quote(s.Id)}",
+ $"title: {Quote(Name(s))}",
+ $"started: {Quote(Time(s.StartedAt, zone))}",
+ $"ended: {Quote(Time(ended, zone))}",
+ $"minutes: {Math.Max(0, (long)Math.Floor((ended - s.StartedAt).TotalSeconds / 60))}",
+ $"languages: [{string.Join(", ", languages.Select(Quote))}]",
+ $"source: {Quote(s.SourceFile is null ? "meeting" : "file")}",
+ $"notes: {Quote(notes)}",
+ "tags: [\"cicada\"]",
+ "---",
+ ];
+ return string.Join("\n", lines) + "\n";
+ }
+
+ public static string Document(Session s) => Frontmatter(s) + SessionStore.Markdown(s);
+
+ static DateTimeOffset Local(DateTimeOffset at, TimeZoneInfo? zone) => TimeZoneInfo.ConvertTime(at, zone ?? TimeZoneInfo.Local);
+
+ /// Local time with its offset ("+08:00", "+00:00" for UTC, never "Z"), whole seconds.
+ static string Time(DateTimeOffset at, TimeZoneInfo? zone) => Local(at, zone).ToString("yyyy-MM-dd'T'HH:mm:sszzz", CultureInfo.InvariantCulture);
+
+ // MARK: Paths (split on both separators: the tests run on the Mac, the app on Windows)
+
+ static readonly char[] Separators = ['\\', '/'];
+
+ /// The same folder or one inside it, ignoring case as Windows does.
+ public static bool Under(string path, string root)
+ {
+ var p = path.TrimEnd(Separators);
+ var r = root.TrimEnd(Separators);
+ if (r.Length == 0) return false;
+ if (string.Equals(p, r, StringComparison.OrdinalIgnoreCase)) return true;
+ return p.Length > r.Length && p.StartsWith(r, StringComparison.OrdinalIgnoreCase) && Separators.Contains(p[r.Length]);
+ }
+
+ /// The folder a path is in ("D:" for a drive's top folder), or null at the top.
+ public static string? Parent(string path)
+ {
+ var p = path.TrimEnd(Separators);
+ int i = p.LastIndexOfAny(Separators);
+ if (i <= 0) return null;
+ var parent = p[..i];
+ return parent.EndsWith(':') ? parent + p[i] : parent;
+ }
+
+ public static string LastName(string path)
+ {
+ var p = path.TrimEnd(Separators);
+ int i = p.LastIndexOfAny(Separators);
+ return i < 0 ? p : p[(i + 1)..];
+ }
+
+ /// "工作笔记 › Cicada": the folder and the one it is in, by `name` (Explorer's names in the app).
+ public static string ShortPath(string folder, Func<string, string?>? name = null)
+ {
+ string Named(string p) => name?.Invoke(p) is { Length: > 0 } n ? n : LastName(p) is { Length: > 0 } l ? l : p;
+ return Parent(folder) is { } parent ? $"{Named(parent)} › {Named(folder)}" : Named(folder);
+ }
+
+ // MARK: Obsidian
+
+ /// Obsidian's vaults (its `obsidian.json`), the most recently opened first; only ones that exist.
+ public static List<string> ObsidianVaults(string json, Func<string, bool>? exists = null)
+ {
+ exists ??= Directory.Exists;
+ try
+ {
+ if (JsonNode.Parse(json)?["vaults"] is not JsonObject vaults) return [];
+ return vaults
+ .Select(v => (Path: v.Value?["path"]?.GetValueKind() == System.Text.Json.JsonValueKind.String ? (string?)v.Value["path"] : null,
+ Ts: v.Value?["ts"]?.GetValueKind() == System.Text.Json.JsonValueKind.Number ? (double)v.Value["ts"]! : 0))
+ .Where(v => v.Path is not null && exists(v.Path))
+ .OrderByDescending(v => v.Ts)
+ .Select(v => v.Path!)
+ .ToList();
+ }
+ catch (Exception) { return []; }
+ }
+
+ /// %APPDATA%\obsidian\obsidian.json.
+ public static List<string> ObsidianVaults()
+ {
+ var file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "obsidian", "obsidian.json");
+ try { return File.Exists(file) ? ObsidianVaults(File.ReadAllText(file)) : []; }
+ catch (Exception) { return []; }
+ }
+
+ public static string? Vault(string folder, IEnumerable<string>? vaults = null) => (vaults ?? ObsidianVaults()).FirstOrDefault(v => Under(folder, v));
+
+ /// Documents\Cicada (Documents may be OneDrive's; that syncs, which is the point).
+ public static string DocumentsFolder => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Cicada");
+
+ /// The suggestion: a Cicada folder in the most recently opened vault, else Documents\Cicada.
+ public static string DefaultFolder() => ObsidianVaults().FirstOrDefault() is { } v ? Path.Combine(v, "Cicada") : DocumentsFolder;
+
+ // MARK: Controlled folder access
+
+ /// The folders Defender's 受控文件夹访问 protects by default (when it is on).
+ public static List<string> ProtectedRoots()
+ {
+ Environment.SpecialFolder[] known =
+ [
+ Environment.SpecialFolder.MyDocuments, Environment.SpecialFolder.MyPictures, Environment.SpecialFolder.MyVideos,
+ Environment.SpecialFolder.MyMusic, Environment.SpecialFolder.DesktopDirectory, Environment.SpecialFolder.Favorites,
+ Environment.SpecialFolder.CommonDocuments, Environment.SpecialFolder.CommonPictures, Environment.SpecialFolder.CommonVideos,
+ Environment.SpecialFolder.CommonMusic, Environment.SpecialFolder.CommonDesktopDirectory,
+ ];
+ return known.Select(Environment.GetFolderPath).Where(p => p.Length > 0).Distinct().ToList();
+ }
+
+ /// Inside a folder controlled folder access protects: an access-denied error there is most likely
+ /// it, which Windows announces itself and Windows 安全中心 can allow. Elsewhere it is plain
+ /// file permissions. (The error is the same either way; this is the best guess there is.)
+ public static bool Protected(string folder, IEnumerable<string>? roots = null) => (roots ?? ProtectedRoots()).Any(r => Under(folder, r));
+}
+
+/// Writes settled meetings into the chosen folder and keeps the index of what it wrote. State
+/// belongs to the UI thread (`Post`, as the Mac's main actor): the records are rendered there, and
+/// the files are written one at a time, in order, on one background worker.
+public sealed class FolderExporter
+{
+ public enum Kind { Denied, Missing, Failed }
+
+ /// Denied: no permission (controlled folder access, or the folder's own permissions).
+ /// Missing: the folder, or the drive it was on, is gone.
+ public sealed record Problem(Kind Kind, string? Message = null);
+
+ public sealed class Index
+ {
+ [JsonPropertyName("folder")] public string Folder { get; set; } = "";
+ /// Record id → the file name Cicada wrote.
+ [JsonPropertyName("files")] public Dictionary<string, string> Files { get; set; } = [];
+ /// Records waiting to be written.
+ [JsonPropertyName("pending")] public List<string> Pending { get; set; } = [];
+ [JsonPropertyName("lastFile")] public string? LastFile { get; set; }
+ [JsonPropertyName("lastAt")] public DateTimeOffset? LastAt { get; set; }
+ }
+
+ readonly SessionStore store;
+ readonly AppSettings settings;
+ readonly string indexPath;
+ readonly Timer timer;
+ bool scheduledFromMeeting;
+ /// The one worker: each job starts when the one before it ends.
+ Task worker = Task.CompletedTask;
+ readonly object workerGate = new();
+ /// A flush is out on the worker: another waits for it (`again`), or a record still pending
+ /// would be rendered twice and its second copy find the first's file "taken".
+ bool writing, again, againFromMeeting;
+ /// Told about this problem already (cleared once a write works).
+ bool notified;
+
+ public Index State { get; private set; } = new();
+ public Problem? Trouble { get; private set; }
+ /// Checking a newly chosen folder.
+ public bool Checking { get; private set; }
+
+ /// Runs on the UI thread (the app's dispatcher; inline in tests).
+ public Action<Action> Post { get; set; } = a => a();
+ /// The meeting being listened to: never written while it runs.
+ public Func<string?> LiveId { get; set; } = () => null;
+ /// The meeting's final notes pass is running or waiting.
+ public Func<string, bool> Settling { get; set; } = _ => false;
+ /// Denied after a meeting, outside the folders controlled folder access protects (inside them
+ /// Windows shows its own notification): the app's one notification.
+ public Action? NotifyDenied { get; set; }
+ /// How long a change waits for the next before writing (2 s; tests shorten it).
+ public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(2);
+ public event Action? Changed;
+
+ public FolderExporter(SessionStore store, AppSettings settings, string? indexPath = null)
+ {
+ this.store = store;
+ this.settings = settings;
+ this.indexPath = indexPath ?? Path.Combine(Paths.Root, "FolderExport.json");
+ timer = new Timer(_ => { var m = scheduledFromMeeting; Post(() => Flush(m)); }, null, Timeout.Infinite, Timeout.Infinite);
+ try { if (File.Exists(this.indexPath) && Json.Read<Index>(File.ReadAllText(this.indexPath)) is { } i) State = i; }
+ catch (Exception e) { Log.Debug($"folder export: index unreadable ({e.GetType().Name})"); }
+ }
+
+ public bool On => settings.ExportOn && settings.ExportFolder.Length > 0;
+ public string? Folder => settings.ExportFolder.Length == 0 ? null : settings.ExportFolder;
+
+ public string? FileFor(string id) =>
+ On && State.Folder == settings.ExportFolder && State.Files.TryGetValue(id, out var name) ? Path.Combine(settings.ExportFolder, name) : null;
+
+ public bool IsPending(string id) => On && State.Pending.Contains(id);
+
+ /// Ended, not being imported, with something said.
+ public bool Ready(Session s) => s.EndedAt is not null && s.Importing != true && s.Lines.Count > 0 && s.Id != LiveId();
+
+ /// Settled records not written to this folder yet.
+ public List<Session> Unwritten => store.All().Where(s => Ready(s) && !State.Files.ContainsKey(s.Id) && !State.Pending.Contains(s.Id)).ToList();
+
+ // MARK: Triggers
+
+ /// A meeting ended: write it once it is settled.
+ public void Ended(string id)
+ {
+ if (!On) return;
+ if (!State.Pending.Contains(id)) State.Pending.Add(id);
+ SaveIndex();
+ Schedule();
+ }
+
+ /// A record was saved: rewrite it if it was written, or write it if it is waiting.
+ public void Saved(string id)
+ {
+ if (!On || !(State.Files.ContainsKey(id) || State.Pending.Contains(id))) return;
+ if (!State.Pending.Contains(id)) State.Pending.Add(id);
+ Schedule();
+ }
+
+ /// The final notes pass for a meeting is over (written, failed, no key, nothing to do).
+ public void Settled(string id) { if (On && State.Pending.Contains(id)) Schedule(); }
+
+ /// 也存一份: every settled record not written yet. Never notifies.
+ public void WriteAll()
+ {
+ if (!On) return;
+ State.Pending.AddRange(Unwritten.Select(s => s.Id));
+ SaveIndex();
+ Flush(fromMeeting: false);
+ }
+
+ /// At launch and when the app comes forward: try what is still waiting.
+ public void Retry()
+ {
+ if (!On || State.Pending.Count == 0) return;
+ Schedule(TimeSpan.FromMilliseconds(500), fromMeeting: false);
+ }
+
+ /// The record was deleted in Cicada; its file stays.
+ public void Deleted(string id)
+ {
+ State.Files.Remove(id);
+ State.Pending.Remove(id);
+ SaveIndex();
+ Changed?.Invoke();
+ }
+
+ // MARK: Choosing the folder
+
+ /// A new folder (or the same one again after a fix): start its index, and write a file there at
+ /// once so a problem shows while settings is open, not when a meeting ends.
+ public void Choose(string folder)
+ {
+ settings.ExportFolder = folder;
+ settings.ExportOn = true;
+ settings.Save();
+ if (State.Folder != folder) State = new Index { Folder = folder };
+ SaveIndex();
+ Checking = true;
+ Trouble = null;
+ Changed?.Invoke();
+ Enqueue(() =>
+ {
+ var result = Probe(folder);
+ Post(() =>
+ {
+ Checking = false;
+ Trouble = result;
+ if (result is null) { notified = false; Retry(); }
+ Log.Debug($"folder export: chosen → {result?.Kind.ToString() ?? "ok"}");
+ Changed?.Invoke();
+ });
+ });
+ }
+
+ public void TurnOff()
+ {
+ settings.ExportOn = false;
+ settings.Save();
+ Trouble = null;
+ Changed?.Invoke();
+ }
+
+ // MARK: Writing
+
+ void Schedule(TimeSpan? after = null, bool fromMeeting = true)
+ {
+ scheduledFromMeeting = fromMeeting;
+ timer.Change(after ?? Delay, Timeout.InfiniteTimeSpan);
+ }
+
+ void Enqueue(Action work)
+ {
+ lock (workerGate) worker = worker.ContinueWith(_ => work(), TaskScheduler.Default);
+ }
+
+ /// Tests: until nothing is waiting on the worker.
+ public async Task Idle()
+ {
+ while (true)
+ {
+ Task w;
+ lock (workerGate) w = worker;
+ await w;
+ lock (workerGate) if (w == worker && !writing) return;
+ }
+ }
+
+ sealed record Job(string Id, string Stem, string? Old, string Text);
+
+ abstract record Outcome
+ {
+ public sealed record Wrote(string Id, string Name) : Outcome;
+ public sealed record Unchanged(string Id) : Outcome;
+ public sealed record Stopped(Problem Problem) : Outcome;
+ }
+
+ /// Renders what is settled here, on the UI thread; writes it on the worker.
+ void Flush(bool fromMeeting)
+ {
+ if (!On || Folder is not { } folder) return;
+ if (writing) { again = true; againFromMeeting |= fromMeeting; return; }
+ if (State.Folder != folder) State = new Index { Folder = folder, Pending = State.Pending };
+ var jobs = new List<Job>();
+ foreach (var id in State.Pending.ToList())
+ {
+ if (store.Get(id) is not { } s) { State.Pending.Remove(id); continue; }
+ if (!Ready(s) || Settling(id)) continue;
+ jobs.Add(new Job(id, FolderExportFormat.Stem(s), State.Files.GetValueOrDefault(id), FolderExportFormat.Document(s)));
+ }
+ SaveIndex();
+ if (jobs.Count == 0) return;
+ writing = true;
+ var ours = new Dictionary<string, string>(State.Files);
+ Enqueue(() =>
+ {
+ var outcomes = Write(jobs, folder, ours);
+ Post(() => Apply(outcomes, folder, fromMeeting));
+ });
+ }
+
+ void Apply(List<Outcome> outcomes, string folder, bool fromMeeting)
+ {
+ writing = false;
+ if (State.Folder == folder)
+ {
+ Problem? stopped = null;
+ foreach (var o in outcomes)
+ {
+ switch (o)
+ {
+ case Outcome.Wrote w:
+ State.Files[w.Id] = w.Name;
+ State.Pending.Remove(w.Id);
+ State.LastFile = w.Name;
+ State.LastAt = DateTimeOffset.Now;
+ break;
+ case Outcome.Unchanged u: State.Pending.Remove(u.Id); break;
+ case Outcome.Stopped p: stopped = p.Problem; break;
+ }
+ }
+ SaveIndex();
+ Trouble = stopped;
+ Log.Debug($"folder export: {outcomes.Count(o => o is Outcome.Wrote)} written, {outcomes.Count(o => o is Outcome.Unchanged)} unchanged{(stopped is null ? "" : $", stopped: {stopped.Kind}")}");
+ if (stopped is null) notified = false;
+ // Told once the meeting has settled (its Settled flush comes back here): the tray shows one
+ // notification at a time, and 纪要整理好了 a second later would replace this one.
+ if (stopped?.Kind == Kind.Denied && fromMeeting && !notified && !State.Pending.Any(Settling))
+ {
+ notified = true;
+ if (FolderExportFormat.Protected(folder)) Log.Debug("folder export: denied in a protected folder, Windows says so itself");
+ else NotifyDenied?.Invoke();
+ }
+ Changed?.Invoke();
+ }
+ if (again)
+ {
+ var m = againFromMeeting;
+ again = againFromMeeting = false;
+ Flush(m);
+ }
+ }
+
+ static bool Same(string? a, string? b) => a is not null && b is not null && string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
+
+ /// On the worker. Stops at the first problem: the rest would fail the same way.
+ static List<Outcome> Write(List<Job> jobs, string folder, Dictionary<string, string> ours)
+ {
+ if (Ensure(folder) is { } p) return [new Outcome.Stopped(p)];
+ var output = new List<Outcome>();
+ foreach (var job in jobs)
+ {
+ // Windows names ignore case: "周会.md" and "周会.MD" are one file.
+ var mine = new HashSet<string>(ours.Where(o => o.Key != job.Id).Select(o => o.Value), StringComparer.OrdinalIgnoreCase);
+ var name = FolderExportFormat.FileName(job.Stem, candidate =>
+ {
+ if (Same(candidate, job.Old)) return false;
+ var at = Path.Combine(folder, candidate);
+ return mine.Contains(candidate) || File.Exists(at) || Directory.Exists(at);
+ });
+ var path = Path.Combine(folder, name);
+ if (Same(name, job.Old))
+ {
+ try { if (File.Exists(path) && File.ReadAllText(path) == job.Text) { output.Add(new Outcome.Unchanged(job.Id)); continue; } }
+ catch (Exception) { } // unreadable: written again below, which says what is wrong
+ }
+ try { WriteAtomically(path, job.Text); }
+ catch (Exception e)
+ {
+ output.Add(new Outcome.Stopped(Classify(e, folder)));
+ return output;
+ }
+ // Renamed: the old file goes, only if it is the one Cicada wrote.
+ if (job.Old is { } old && !Same(old, name)) try { File.Delete(Path.Combine(folder, old)); } catch (Exception) { }
+ ours[job.Id] = name;
+ output.Add(new Outcome.Wrote(job.Id, name));
+ }
+ return output;
+ }
+
+ /// A hidden temporary file in the same folder, then moved over the old one: a vault or a sync
+ /// client never sees half a file.
+ static void WriteAtomically(string path, string text)
+ {
+ var tmp = Path.Combine(Path.GetDirectoryName(path)!, $".cicada-{Guid.NewGuid():N}.tmp");
+ try
+ {
+ File.WriteAllText(tmp, text, new UTF8Encoding(false));
+ File.Move(tmp, path, overwrite: true);
+ }
+ catch
+ {
+ try { File.Delete(tmp); } catch (Exception) { }
+ throw;
+ }
+ }
+
+ /// The folder exists, or is made when only it is missing (never on a drive that isn't there).
+ static Problem? Ensure(string folder)
+ {
+ if (Directory.Exists(folder)) return null;
+ if (File.Exists(folder) || FolderExportFormat.Parent(folder) is not { } parent || !Directory.Exists(parent)) return new Problem(Kind.Missing);
+ try { Directory.CreateDirectory(folder); return null; }
+ catch (Exception e) { return Classify(e, folder); }
+ }
+
+ /// Writes and removes a hidden file: the check after choosing a folder.
+ public static Problem? Probe(string folder)
+ {
+ if (Ensure(folder) is { } p) return p;
+ var file = Path.Combine(folder, ".cicada-check");
+ try
+ {
+ File.WriteAllBytes(file, []);
+ try { File.Delete(file); } catch (Exception) { }
+ return null;
+ }
+ catch (Exception e) { return Classify(e, folder); }
+ }
+
+ /// Access denied is the same error whether controlled folder access or the folder's permissions
+ /// said no. A file held open by a sync client is an IOException: just "not saved", tried again.
+ static Problem Classify(Exception e, string folder)
+ {
+ if (e is UnauthorizedAccessException) return new Problem(Kind.Denied);
+ if (e is DirectoryNotFoundException or DriveNotFoundException || !Directory.Exists(folder)) return new Problem(Kind.Missing);
+ return new Problem(Kind.Failed, e.Message);
+ }
+
+ void SaveIndex()
+ {
+ try
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(indexPath)!);
+ var tmp = indexPath + ".tmp";
+ File.WriteAllText(tmp, Json.Write(State), new UTF8Encoding(false));
+ File.Move(tmp, indexPath, overwrite: true);
+ }
+ catch (Exception e) { Log.Debug($"folder export: index not saved ({e.GetType().Name})"); }
+ }
+}
diff --git a/windows/src/Cicada.Core/Notes.cs b/windows/src/Cicada.Core/Notes.cs
index b4dc0d9..e7e8154 100644
--- a/windows/src/Cicada.Core/Notes.cs
+++ b/windows/src/Cicada.Core/Notes.cs
@@ -81,6 +81,13 @@ public sealed class NotesEngine
/// page says so and the button waits, as a long meeting's notes take half a minute and more.
public string? GeneratingId { get; private set; }
+ /// The meeting whose final pass is running now (from 结束 or 生成纪要).
+ string? finalId;
+ /// A final pass is over, whether it wrote notes or not (存到文件夹 waits for it).
+ public event Action<string>? FinalDone;
+ /// The final pass for this meeting is running or waiting its turn.
+ public bool Settling(string id) { lock (gate) return finalId == id || pendingFinal == id; }
+
/// Notes for a finished meeting that has none.
public async Task Generate(string id)
{
@@ -124,9 +131,10 @@ public sealed class NotesEngine
{
if (inFlight) { if (final) pendingFinal = id; return; }
session = store.Get(id);
- if (session is null || session.Lines.Count == 0) return;
- if (!ling.HasKey) { Status = State.NoKey; Changed?.Invoke(); return; }
+ if (session is null || session.Lines.Count == 0) { if (final) FinalDone?.Invoke(id); return; }
+ if (!ling.HasKey) { Status = State.NoKey; Changed?.Invoke(); if (final) FinalDone?.Invoke(id); return; }
inFlight = true;
+ if (final) finalId = id;
lastAttempt = DateTime.UtcNow;
Status = State.Updating;
baseNotes = final ? new MeetingNotes() : (id == ShownId ? Notes : session.Notes ?? new MeetingNotes());
@@ -192,8 +200,9 @@ public sealed class NotesEngine
finally
{
string? queued;
- lock (gate) { inFlight = false; queued = pendingFinal; pendingFinal = null; }
+ lock (gate) { inFlight = false; if (final) finalId = null; queued = pendingFinal; pendingFinal = null; }
Changed?.Invoke();
+ if (final) FinalDone?.Invoke(id);
if (queued is not null) await Update(queued, final: true);
}
}
diff --git a/windows/src/Cicada.Core/SessionStore.cs b/windows/src/Cicada.Core/SessionStore.cs
index d9714d2..3ed20b6 100644
--- a/windows/src/Cicada.Core/SessionStore.cs
+++ b/windows/src/Cicada.Core/SessionStore.cs
@@ -16,6 +16,8 @@ public sealed class SessionStore
/// The moment recognised words land in a record: a new line (theirs or mine) or a half sentence
/// that grew. What 结束会议 counts as someone speaking (MeetingEndWatch.Heard).
public event Action<string>? Words;
+ /// A record was written to disk (存到文件夹 follows its changes); on the saving thread.
+ public event Action<string>? Saved;
/// The app's audio encoder (Media Foundation); null where there is none (the Mac CLI, tests
/// that don't set one): meetings are then kept without a recording.
public IAudioFiles? Audio { get; set; }
@@ -244,6 +246,7 @@ public sealed class SessionStore
var tmp = FileOf(id) + ".tmp";
File.WriteAllText(tmp, json, new UTF8Encoding(false));
File.Move(tmp, FileOf(id), overwrite: true);
+ Saved?.Invoke(id);
}
catch (Exception e) { Log.Debug($"store: save failed {e.GetType().Name}"); }
}
diff --git a/windows/src/Cicada.Core/Settings.cs b/windows/src/Cicada.Core/Settings.cs
index 85ad271..d12310f 100644
--- a/windows/src/Cicada.Core/Settings.cs
+++ b/windows/src/Cicada.Core/Settings.cs
@@ -54,6 +54,10 @@ public sealed class AppSettings
[JsonPropertyName("subtitleSize")] public int SubtitleSize { get; set; } = 24;
/// 保存会议录音 (the Mac's key): keep what was heard as system.m4a in the meeting's folder.
[JsonPropertyName("recordAudio")] public bool RecordAudio { get; set; } = true;
+ /// 存到文件夹 (the Mac's keys): settled meetings are also written as Markdown into exportFolder
+ /// (a path; empty until one is chosen). FolderExport.cs.
+ [JsonPropertyName("exportOn")] public bool ExportOn { get; set; }
+ [JsonPropertyName("exportFolder")] public string ExportFolder { get; set; } = "";
/// 说话人识别: tell the other side's voices apart (on by default, as on the Mac).
[JsonPropertyName("speakerVoices")] public bool SpeakerVoices { get; set; } = true;
/// 会中改正听错的词 (the Mac's key): finished sentences carry the word list to the AI service,
diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.cs
index f88cc6d..b401613 100644
--- a/windows/src/Cicada/App.cs
+++ b/windows/src/Cicada/App.cs
@@ -61,6 +61,8 @@ sealed class Controller
public readonly UpdateChecker Updates;
public readonly Vocabulary Vocabulary;
public readonly LiveFixes Fixes;
+ /// 存到文件夹 (设置 › 隐私与启动): settled meetings written as Markdown into a folder.
+ public readonly FolderExporter FolderExport;
/// 分享…: the share service, its device key and the links made (sealed files, never the record).
public readonly ShareClient Sharing = new(new DpapiProtector(), "windows", Version);
/// Dev (`silentlisten`): the language `heard` lines are in.
@@ -151,6 +153,18 @@ sealed class Controller
Notes.Changed += Changed;
Store.Changed += _ => Changed();
Store.Words += id => Dispatch.BeginInvoke(() => HeardWords(id));
+ // 存到文件夹: written once a record is settled, rewritten when it changes. Its state is the
+ // dispatcher's, as the Mac's is the main actor's.
+ FolderExport = new FolderExporter(Store, Settings)
+ {
+ Post = a => Dispatch.BeginInvoke(a),
+ LiveId = () => Listen.Listening ? Listen.SessionId : null,
+ Settling = Notes.Settling,
+ NotifyDenied = NotifyFolderDenied,
+ };
+ FolderExport.Changed += () => { Changed(); Dispatch.BeginInvoke(() => settingsWindow?.ExportChanged()); };
+ Store.Saved += id => Dispatch.BeginInvoke(() => FolderExport.Saved(id));
+ Notes.FinalDone += id => Dispatch.BeginInvoke(() => FolderExport.Settled(id));
Updates = new UpdateChecker(Settings.UpdateLastChecked, at => Dispatch.BeginInvoke(() => { Settings.UpdateLastChecked = at; Settings.Save(); })) { Current = Version };
Updates.Changed += UpdatesChanged;
}
@@ -178,6 +192,10 @@ sealed class Controller
Log.Debug($"audio: speakers {Endpoints.Default(Endpoints.Flow.Render)?.Name ?? "none"}, mic {Endpoints.Microphone()?.Name ?? "none"}, cable {(Endpoints.Cable() is null ? "absent" : "present")}");
DebugServer.Start(this);
WatchNetwork();
+ // 存到文件夹: what is still waiting, now and whenever Cicada comes forward (a folder fixed
+ // in Windows 安全中心 meanwhile).
+ FolderExport.Retry();
+ application.Activated += (_, _) => FolderExport.Retry();
// A dev build isn't what a release replaces: it checks only when pointed at a test feed.
UpdateChecker.CleanDownloads();
if (!Paths.Dev || Environment.GetEnvironmentVariable("CICADA_UPDATE_FEED") is { Length: > 0 }) { checksUpdates = true; Updates.Start(); }
@@ -385,6 +403,21 @@ sealed class Controller
menu.IsOpen = true;
}
+ /// 存到文件夹 couldn't write after a meeting (not inside a folder controlled folder access
+ /// protects: Windows says that itself). Once until a write works again.
+ void NotifyFolderDenied()
+ {
+ if (FolderExport.Folder is not { } folder) return;
+ Toast(L("纪要没存到文件夹"), LF("知了没有权限写入 %@。点按去设置", FolderExportUi.ShortPath(folder)), ShowFolderSettings);
+ }
+
+ /// 设置 › 隐私与启动, where 会后存一份 says what is wrong.
+ public void ShowFolderSettings()
+ {
+ ShowSettings();
+ SettingsPage("privacy");
+ }
+
/// A Windows notification from the tray icon; a click on it runs `clicked`.
public void Toast(string title, string body, Action? clicked = null)
{
@@ -642,6 +675,7 @@ sealed class Controller
await StopRoomSide();
roomSources.Clear();
await Listen.Stop(endedAt);
+ if (id is not null) FolderExport.Ended(id);
Changed();
NotifyUpdate(); // held while the meeting was on
if (id is not null) _ = TellWhenNotesReady(id);
@@ -1300,6 +1334,21 @@ sealed class Controller
}
/// For the debug pipe: what a test needs to see (never meeting text).
+ /// 存到文件夹 for the debug pipe (paths and file names, never meeting text).
+ public JsonObject ExportState()
+ {
+ var ex = FolderExport;
+ return new JsonObject
+ {
+ ["on"] = ex.On, ["folder"] = ex.Folder, ["short"] = ex.Folder is { } f ? FolderExportUi.ShortPath(f) : null,
+ ["checking"] = ex.Checking, ["problem"] = ex.Trouble?.Kind.ToString(), ["message"] = ex.Trouble?.Message,
+ ["protected"] = ex.Folder is { } pf && FolderExportFormat.Protected(pf), ["vault"] = ex.Folder is { } vf ? FolderExportFormat.Vault(vf) : null,
+ ["files"] = new JsonObject(ex.State.Files.Select(kv => KeyValuePair.Create(kv.Key, (JsonNode?)kv.Value))),
+ ["pending"] = new JsonArray(ex.State.Pending.Select(id => (JsonNode?)id).ToArray()),
+ ["unwritten"] = ex.Unwritten.Count, ["lastFile"] = ex.State.LastFile, ["lastAt"] = ex.State.LastAt?.ToString("o"),
+ };
+ }
+
public JsonObject State() => new()
{
["listening"] = Listen.Listening,
@@ -1340,6 +1389,7 @@ sealed class Controller
["roomMusic"] = Listen.Echo?.Gate.PlayingMusic,
["room"] = Listen.Room,
["recordAudio"] = Settings.RecordAudio,
+ ["export"] = ExportState(),
["hasAudio"] = Listen.SessionId is { } aid && Store.Get(aid) is { } a ? a.HasAudio : null,
["player"] = mainWindow?.PlayerState(),
};
@@ -1485,8 +1535,27 @@ static class DebugServer
case "record": _ = app.RecordCable(arg); break;
// 回放: "open <id> [transcript]", "play <seconds>|toggle|speed|follow|row <i>" (follow: 回到正在播放; row: a line
// clicked), "recordaudio on|off".
+ case "rename": { var p = arg.Split(' ', 2); app.Store.Rename(p[0], p.Length > 1 ? p[1] : ""); break; } // rename <id> <title> ("" back to automatic)
case "open": { var p = arg.Split(' '); app.OpenRecord(p[0], p.Length > 1 ? p[1] : "notes"); break; }
case "play": app.Play(arg); break;
+ // 存到文件夹: export [state] | on | off | folder <path> | choose | all | retry
+ case "export":
+ {
+ var p = arg.Split(' ', 2);
+ switch (p[0])
+ {
+ case "on": if (app.FolderExport.Folder is { } f) app.FolderExport.Choose(f); else app.FolderExport.Choose(FolderExportFormat.DefaultFolder()); break;
+ case "off": app.FolderExport.TurnOff(); break;
+ case "folder" when p.Length > 1: app.FolderExport.Choose(p[1].Trim().Trim('"')); break;
+ case "choose": // modal: shown after the reply, or the pipe would wait for it
+ app.ShowFolderSettings();
+ app.Dispatcher().BeginInvoke(() => { if (FolderExportUi.Choose(app.OpenSettings, app.FolderExport.Folder) is { } picked) app.FolderExport.Choose(picked); });
+ break;
+ case "all": app.FolderExport.WriteAll(); break;
+ case "retry": app.FolderExport.Retry(); break;
+ }
+ return app.ExportState();
+ }
case "recordaudio": app.Settings.RecordAudio = arg == "on"; app.Settings.Save(); app.SettingsChanged(); break;
// 保存会议录音 on its own: "aacencode <wav>|<out.aac>", "aacrewrap <in.aac>|<out.m4a>[|<seconds>]".
case "aacencode":
diff --git a/windows/src/Cicada/Dialogs.cs b/windows/src/Cicada/Dialogs.cs
index 9737250..4ae7a2f 100644
--- a/windows/src/Cicada/Dialogs.cs
+++ b/windows/src/Cicada/Dialogs.cs
@@ -45,6 +45,36 @@ static class Dialogs
return Show(owner, title, content, ok, danger: false, box);
}
+ /// One of a few options, each a bordered row (the Mac's FolderChoice): its index, or null when
+ /// cancelled. The first is chosen to start with.
+ public static int? Pick(Window? owner, string title, IReadOnlyList<(string Title, string? Detail)> options, string ok)
+ {
+ int pick = 0;
+ var list = new StackPanel();
+ var rows = new List<Border>();
+ void Restyle()
+ {
+ for (int i = 0; i < rows.Count; i++)
+ {
+ rows[i].BorderBrush = i == pick ? Palette.Ink : Palette.Line;
+ rows[i].BorderThickness = new Thickness(i == pick ? 1.5 : 1);
+ }
+ }
+ for (int i = 0; i < options.Count; i++)
+ {
+ var index = i;
+ var text = options[i].Detail is { } d ? Ui.Stack(2, Ui.Text(options[i].Title, 13, Palette.Ink), Ui.Helper(d)) : Ui.Stack(2, Ui.Text(options[i].Title, 13, Palette.Ink));
+ var row = new Border { CornerRadius = new CornerRadius(9), Padding = new Thickness(12, 10, 12, 10), Margin = new Thickness(0, 0, 0, 8), Background = Palette.Surface, Cursor = Cursors.Hand, Child = text };
+ // Down, and handled: the dialog drags itself on a press, which would swallow the release.
+ row.MouseLeftButtonDown += (_, e) => { pick = index; Restyle(); e.Handled = true; };
+ System.Windows.Automation.AutomationProperties.SetName(row, options[i].Title);
+ rows.Add(row);
+ list.Children.Add(row);
+ }
+ Restyle();
+ return Show(owner, title, list, ok, danger: false, null) is null ? null : pick;
+ }
+
static string? Show(Window? owner, string title, FrameworkElement content, string ok, bool danger, TextBox? field, bool single = false, Button? secondary = null, Func<Task<bool>>? work = null)
{
string? result = null;
diff --git a/windows/src/Cicada/FolderExportViews.cs b/windows/src/Cicada/FolderExportViews.cs
new file mode 100644
index 0000000..71fb908
--- /dev/null
+++ b/windows/src/Cicada/FolderExportViews.cs
@@ -0,0 +1,184 @@
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Media;
+using static Cicada.Strings;
+
+namespace Cicada.App;
+
+/// 存到文件夹 (FolderExport.cs): the folder as Explorer names it, the choice of folder, and the
+/// record's line under its title. As the Mac's FolderExportViews.swift.
+static class FolderExportUi
+{
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ struct FileInfo
+ {
+ public IntPtr Icon; public int IconIndex; public uint Attributes;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string DisplayName;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string TypeName;
+ }
+ [DllImport("shell32.dll", CharSet = CharSet.Unicode)] static extern IntPtr SHGetFileInfo(string path, uint attributes, ref FileInfo info, uint size, uint flags);
+ const uint DisplayNameFlag = 0x200;
+
+ /// Explorer's name for a folder ("文档" for Documents, "Windows (C:)" for a drive); null when it
+ /// isn't there.
+ static string? ShellName(string path)
+ {
+ var info = new FileInfo();
+ return SHGetFileInfo(path, 0, ref info, (uint)Marshal.SizeOf<FileInfo>(), DisplayNameFlag) != IntPtr.Zero && info.DisplayName is { Length: > 0 } n ? n : null;
+ }
+
+ /// "文档 › Cicada".
+ public static string ShortPath(string folder) => FolderExportFormat.ShortPath(folder, ShellName);
+
+ /// Not SettingsWindow.OpenFolder: that makes the folder, and on a drive that's gone it would throw.
+ public static void Open(string folder)
+ {
+ if (!Directory.Exists(folder)) return;
+ Process.Start(new ProcessStartInfo("explorer.exe", $"\"{folder}\"") { UseShellExecute = true });
+ }
+
+ public static void Reveal(string file)
+ {
+ if (File.Exists(file)) Process.Start(new ProcessStartInfo("explorer.exe", $"/select,\"{file}\"") { UseShellExecute = true });
+ else if (Path.GetDirectoryName(file) is { } dir) Open(dir);
+ }
+
+ /// Windows 安全中心 › 勒索软件防护, where controlled folder access lets an app through.
+ public static void OpenSecurity()
+ {
+ try { Process.Start(new ProcessStartInfo("windowsdefender://ransomwareprotection") { UseShellExecute = true }); }
+ catch (Exception e) { Log.Debug($"folder export: security page not opened {e.GetType().Name}"); }
+ }
+
+ /// 存到哪里: an Obsidian vault first (a new Cicada folder in it), then 文档 › Cicada, or any folder.
+ public static string? Choose(Window? owner, string? current)
+ {
+ var options = new List<(string Title, string? Detail, string? Path)>();
+ foreach (var v in FolderExportFormat.ObsidianVaults().Take(3))
+ options.Add((LF("Obsidian 库「%@」", FolderExportFormat.LastName(v)), L("在库里新建 Cicada 文件夹"), Path.Combine(v, "Cicada")));
+ var documents = FolderExportFormat.DocumentsFolder;
+ options.Add((ShortPath(documents), null, documents));
+ options.Add((L("其他文件夹…"), null, null));
+ if (Dialogs.Pick(owner, L("存到哪里"), options.Select(o => (o.Title, o.Detail)).ToList(), L("存到这里")) is not { } i) return null;
+ if (options[i].Path is { } chosen) return chosen;
+ var dialog = new Microsoft.Win32.OpenFolderDialog { Title = L("会后把纪要和文字记录存成 Markdown 到这里") };
+ var start = current is not null && Directory.Exists(current) ? current : Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
+ if (Directory.Exists(start)) dialog.InitialDirectory = start;
+ return dialog.ShowDialog(owner) == true ? dialog.FolderName : null;
+ }
+
+ /// The record's line under its title: where its file is, or why it isn't there yet. Null when
+ /// there is nothing to say.
+ public static FrameworkElement? Line(Controller app, Session s)
+ {
+ var ex = app.FolderExport;
+ if (!ex.On || ex.Folder is not { } folder || !ex.Ready(s)) return null;
+ var pending = ex.IsPending(s.Id);
+ FrameworkElement Grey(string text) => Ui.Text(text, 12, Palette.Tertiary, wrap: false);
+ FrameworkElement line;
+ if (ex.FileFor(s.Id) is { } file && !pending)
+ line = Ui.Row(4, Grey(LF("已存到 %@ ·", ShortPath(folder))), Ui.LinkText(L("在文件资源管理器中显示"), () => Reveal(file), 12));
+ else if (pending && ex.Trouble is not null)
+ line = Ui.Row(4, Grey(L("没存到文件夹 ·")), Ui.LinkText(L("去设置"), app.ShowFolderSettings, 12));
+ else if (pending)
+ line = Grey(LF("整理好后存到 %@", ShortPath(folder)));
+ else return null;
+ line.Margin = new Thickness(0, 8, 0, 0);
+ return line;
+ }
+
+ /// What the line shows, for MainWindow's PageKey.
+ public static string Key(Controller app, string id) =>
+ $"{app.FolderExport.On}|{app.FolderExport.FileFor(id)}|{app.FolderExport.IsPending(id)}|{app.FolderExport.Trouble?.Kind}";
+}
+
+/// 设置 › 隐私与启动 › 会后存一份 (the Mac has it in 通用, under the records' location, which on
+/// Windows is this page).
+sealed partial class SettingsWindow
+{
+ IEnumerable<FrameworkElement> ExportCards()
+ {
+ var ex = app.FolderExport;
+ yield return Label(L("会后存一份"));
+ var cards = new List<FrameworkElement>
+ {
+ Card(null, L("存到文件夹"), L("纪要和文字记录存成 Markdown;文件夹同步到哪,内容就到哪"), Ui.Switch(ex.On, ToggleExport, L("存到文件夹"))),
+ };
+ if (ex.On && ex.Folder is { } folder)
+ {
+ var shortPath = FolderExportUi.ShortPath(folder);
+ if (ex.Checking) cards.Add(Card(null, LF("正在确认能写入 %@…", shortPath), null, new Border()));
+ else if (ex.Trouble is { } problem) cards.Add(ProblemRow(problem, folder, shortPath));
+ // Ui.Row spaces only the children it is given.
+ var place = new List<UIElement>();
+ if (FolderExportFormat.Vault(folder) is not null) place.Add(Ui.Badge(L("Obsidian 库")));
+ place.Add(Ui.Button(L("打开"), () => FolderExportUi.Open(folder), height: 32));
+ place.Add(Ui.Button(L("更改…"), ChooseExportFolder, height: 32));
+ cards.Add(Card(null, L("位置"), shortPath, Ui.Row(8, [.. place])));
+ var left = ex.Unwritten.Count;
+ if (left > 0) cards.Add(Card(null, L("以前的会议"), LF("还有 %lld 场没存", left), Ui.Button(L("也存一份"), ex.WriteAll, height: 32)));
+ }
+ yield return Group([.. cards]);
+ if (ex.On && ex.State.LastFile is { } name && ex.State.LastAt is { } at)
+ {
+ var local = at.ToLocalTime();
+ var last = Ui.Text(LF("上次存于 %@ · %@", local.ToString(L("M月d日 HH:mm"), Strings.Culture), name), 12, Palette.Tertiary, wrap: false);
+ last.TextTrimming = TextTrimming.CharacterEllipsis;
+ // Section sets each part's margin: the indent goes on a wrapper.
+ yield return new Border { Padding = new Thickness(6, 0, 0, 0), Child = last };
+ }
+ }
+
+ /// Access denied looks the same whoever said no; inside the folders controlled folder access
+ /// protects, Windows 安全中心 is the likely fix.
+ FrameworkElement ProblemRow(FolderExporter.Problem problem, string folder, string shortPath)
+ {
+ var waiting = app.FolderExport.State.Pending.Count;
+ var shielded = FolderExportFormat.Protected(folder);
+ var (title, detail) = problem.Kind switch
+ {
+ FolderExporter.Kind.Denied => (LF("没有权限写入 %@", shortPath),
+ waiting > 0 ? LF("%lld 场会议没存上,允许后自动补存", waiting)
+ : shielded ? L("在 Windows 安全中心里允许知了,或换个文件夹") : L("换个文件夹,或在它的属性里允许写入")),
+ FolderExporter.Kind.Missing => (LF("找不到 %@", shortPath), L("接上或换个文件夹后自动补存")),
+ _ => (L("没存上"), problem.Message ?? ""),
+ };
+ var text = Ui.Stack(2, Ui.Text(title, 13, Palette.Ink, FontWeights.SemiBold), Ui.Helper(detail));
+ var dock = new DockPanel();
+ if (problem.Kind == FolderExporter.Kind.Denied && shielded)
+ {
+ var open = Ui.Button(L("打开 Windows 安全中心"), FolderExportUi.OpenSecurity, height: 32);
+ open.Margin = new Thickness(12, 0, 0, 0);
+ open.VerticalAlignment = VerticalAlignment.Center;
+ DockPanel.SetDock(open, Dock.Right);
+ dock.Children.Add(open);
+ }
+ dock.Children.Add(text);
+ return new Border
+ {
+ Background = problem.Kind == FolderExporter.Kind.Denied ? Palette.AccentPale : Palette.Mica,
+ CornerRadius = new CornerRadius(9), Padding = new Thickness(12, 10, 12, 10), Margin = new Thickness(0, 8, 0, 8), Child = dock,
+ };
+ }
+
+ void ToggleExport(bool on)
+ {
+ var ex = app.FolderExport;
+ if (!on) ex.TurnOff();
+ else if (ex.Folder is { } folder) ex.Choose(folder);
+ else ChooseExportFolder();
+ Render();
+ }
+
+ void ChooseExportFolder()
+ {
+ if (FolderExportUi.Choose(this, app.FolderExport.Folder) is { } folder) app.FolderExport.Choose(folder);
+ Render();
+ }
+
+ /// The exporter's state changed: only 隐私与启动 shows it.
+ public void ExportChanged() { if (current == "privacy") Render(); }
+}
diff --git a/windows/src/Cicada/MainWindow.cs b/windows/src/Cicada/MainWindow.cs
index 1dc7ee8..22d0c92 100644
--- a/windows/src/Cicada/MainWindow.cs
+++ b/windows/src/Cicada/MainWindow.cs
@@ -391,7 +391,7 @@ sealed class MainWindow : Window
/// What the open page shows; a store change that leaves it the same doesn't redraw it.
string? PageKey() => selected is not null && app.Store.Get(selected) is { } cur
- ? $"{selected}|{tab}|{SessionStore.DisplayTitle(cur)}|{cur.Lines.Count}|{cur.Notes?.Covered}|{cur.Notes?.Final}|{app.Listen.Listening}|{app.Notes.GeneratingId == selected}|{cur.HasAudio}|{Recording.Playable(cur)}|{app.Settings.RecordAudio}|{FixKey(cur)}|{cur.Lines.Sum(l => l.Dst?.Length ?? 0)}"
+ ? $"{selected}|{tab}|{SessionStore.DisplayTitle(cur)}|{cur.Lines.Count}|{cur.Notes?.Covered}|{cur.Notes?.Final}|{app.Listen.Listening}|{app.Notes.GeneratingId == selected}|{cur.HasAudio}|{Recording.Playable(cur)}|{app.Settings.RecordAudio}|{FixKey(cur)}|{cur.Lines.Sum(l => l.Dst?.Length ?? 0)}|{FolderExportUi.Key(app, selected)}"
: null;
void ShowDetail()
@@ -424,6 +424,8 @@ sealed class MainWindow : Window
titleRow.Children.Add(reset);
}
top.Children.Add(titleRow);
+ // 存到文件夹: where its file is, or why it isn't there yet.
+ if (!live && FolderExportUi.Line(app, s) is { } exported) top.Children.Add(exported);
if (PlayerArea(s, live) is { } audio) top.Children.Add(audio);
// Under the page, not in its header: the controls stay while the transcript scrolls.
var footer = player is not null ? PlayerFooter() : null;
@@ -1176,6 +1178,7 @@ sealed class MainWindow : Window
{
ClosePlayer(); // it holds the recording open
app.Store.Delete(s.Id);
+ app.FolderExport.Deleted(s.Id); // its file in the folder stays
}
}
}
diff --git a/windows/src/Cicada/SettingsWindow.cs b/windows/src/Cicada/SettingsWindow.cs
index 688081b..182182b 100644
--- a/windows/src/Cicada/SettingsWindow.cs
+++ b/windows/src/Cicada/SettingsWindow.cs
@@ -79,12 +79,13 @@ sealed partial class SettingsWindow : Window
Card(Icons.Keyboard, L("开始或结束"), app.HotkeyRegistered ? L("在任何程序里都能按") : L("这个快捷键被别的程序占用了"), Keys(Hotkey.Label))));
Section(page, "speak", L("同声传译"), SpeakCards().ToArray());
Section(page, "end", L("结束会议"), EndCards());
- Section(page, "privacy", L("隐私与启动"), Group(
+ Section(page, "privacy", L("隐私与启动"), [Group(
Card(Icons.Eye, L("共享屏幕时让对方看到"), L("关着时,截图和屏幕共享里看不到纪要和字幕"), Ui.Switch(app.Settings.ShowInCapture, app.SetShowInCapture, L("共享屏幕时让对方看到"))),
Card(Icons.List, L("说话人识别"), L("按声音标出说话人 1、2…,只在这台电脑上处理"), Ui.Switch(app.Settings.SpeakerVoices, v => { app.Settings.SpeakerVoices = v; Save(); }, L("说话人识别"))),
Card(Icons.Wave, L("保存会议录音"), L("只存在这台电脑上"), Ui.Switch(app.Settings.RecordAudio, v => { app.Settings.RecordAudio = v; Save(); }, L("保存会议录音"))),
Card(Icons.Power, L("开机时启动知了"), null, Ui.Switch(AutoStart.Enabled, v => AutoStart.Enabled = v, L("开机时启动知了"))),
- Card(Icons.Folder, L("会议记录存放位置"), $"{Paths.Sessions} · {L("和 Mac 版格式相同")}", Ui.Button(L("打开文件夹"), () => OpenFolder(Paths.Sessions), height: 32))));
+ Card(Icons.Folder, L("会议记录存放位置"), $"{Paths.Sessions} · {L("和 Mac 版格式相同")}", Ui.Button(L("打开文件夹"), () => OpenFolder(Paths.Sessions), height: 32))),
+ .. ExportCards()]);
// 卸载 as in Settings › Apps, with the same confirmation; only an installed copy offers it.
FrameworkElement[] about =
[
diff --git a/windows/src/Cicada/Strings/en.lproj/Windows.strings b/windows/src/Cicada/Strings/en.lproj/Windows.strings
index bbc30d1..d940b5a 100644
--- a/windows/src/Cicada/Strings/en.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/en.lproj/Windows.strings
@@ -359,3 +359,8 @@
"Windows 把输出改成了 CABLE Input,点此恢复" = "Windows switched audio output to CABLE Input. Click to restore.";
"自动恢复失败" = "Couldn't restore audio";
"请去 Windows 声音设置,把输出设备改回你的耳机或扬声器" = "Go to Windows Sound settings and switch the output device back to your headphones or speakers.";
+/* 存到文件夹 on Windows: controlled folder access instead of macOS privacy settings, File Explorer instead of Finder. */
+"打开 Windows 安全中心" = "Open Windows Security";
+"在 Windows 安全中心里允许知了,或换个文件夹" = "Allow Cicada in Windows Security, or pick another folder";
+"换个文件夹,或在它的属性里允许写入" = "Pick another folder, or allow writing in its Properties";
+"在文件资源管理器中显示" = "Show in File Explorer";
diff --git a/windows/src/Cicada/Strings/ja.lproj/Windows.strings b/windows/src/Cicada/Strings/ja.lproj/Windows.strings
index 78919c1..1098860 100644
--- a/windows/src/Cicada/Strings/ja.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/ja.lproj/Windows.strings
@@ -359,3 +359,8 @@
"Windows 把输出改成了 CABLE Input,点此恢复" = "Windows が音声出力を CABLE Input に変更しました。クリックして元に戻します。";
"自动恢复失败" = "自動復元に失敗しました";
"请去 Windows 声音设置,把输出设备改回你的耳机或扬声器" = "Windows の「サウンド設定」を開き、出力デバイスをお使いのヘッドホンやスピーカーに戻してください。";
+/* 存到文件夹 on Windows: controlled folder access instead of macOS privacy settings, File Explorer instead of Finder. */
+"打开 Windows 安全中心" = "Windows セキュリティを開く";
+"在 Windows 安全中心里允许知了,或换个文件夹" = "Windows セキュリティで Cicada を許可するか、別のフォルダを選んでください";
+"换个文件夹,或在它的属性里允许写入" = "別のフォルダを選ぶか、フォルダのプロパティで書き込みを許可してください";
+"在文件资源管理器中显示" = "エクスプローラーで表示";
diff --git a/windows/src/Cicada/Strings/ko.lproj/Windows.strings b/windows/src/Cicada/Strings/ko.lproj/Windows.strings
index 97d0398..14b0357 100644
--- a/windows/src/Cicada/Strings/ko.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/ko.lproj/Windows.strings
@@ -359,3 +359,8 @@
"Windows 把输出改成了 CABLE Input,点此恢复" = "Windows에서 출력이 CABLE Input으로 변경되었습니다. 클릭하여 복구하세요.";
"自动恢复失败" = "자동 복구 실패";
"请去 Windows 声音设置,把输出设备改回你的耳机或扬声器" = "Windows 소리 설정에서 출력 장치를 사용 중인 헤드폰이나 스피커로 다시 변경해 주세요.";
+/* 存到文件夹 on Windows: controlled folder access instead of macOS privacy settings, File Explorer instead of Finder. */
+"打开 Windows 安全中心" = "Windows 보안 열기";
+"在 Windows 安全中心里允许知了,或换个文件夹" = "Windows 보안에서 Cicada를 허용하거나 다른 폴더를 고르세요";
+"换个文件夹,或在它的属性里允许写入" = "다른 폴더를 고르거나 폴더 속성에서 쓰기를 허용하세요";
+"在文件资源管理器中显示" = "파일 탐색기에서 보기";
diff --git a/windows/tests/Cicada.Tests/Cicada.Tests.csproj b/windows/tests/Cicada.Tests/Cicada.Tests.csproj
index 8825ad8..d5aa651 100644
--- a/windows/tests/Cicada.Tests/Cicada.Tests.csproj
+++ b/windows/tests/Cicada.Tests/Cicada.Tests.csproj
@@ -11,6 +11,8 @@
<None Include="Fixtures/**" CopyToOutputDirectory="PreserveNewest" />
<!-- The share document contract, shared with the Mac and the server (Tests/fixtures/share). -->
<None Include="../../../Tests/fixtures/share/**" LinkBase="Fixtures/share" CopyToOutputDirectory="PreserveNewest" />
+ <!-- 存到文件夹's file name and frontmatter, shared with the Mac and the other ports. -->
+ <None Include="../../../Tests/fixtures/folder-export/**" LinkBase="Fixtures/folder-export" CopyToOutputDirectory="PreserveNewest" />
<ProjectReference Include="../../src/Cicada.Core/Cicada.Core.csproj" />
</ItemGroup>
</Project>
diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.cs
index 609e7b8..e6fa832 100644
--- a/windows/tests/Cicada.Tests/Program.cs
+++ b/windows/tests/Cicada.Tests/Program.cs
@@ -3649,6 +3649,137 @@ static class Tests
Equal(2, server.Seen.Count(x => x == "POST /api/v1/devices"), "the device file is reused");
}
+ // MARK: 存到文件夹 (Tests/fixtures/folder-export is the contract, as in the Mac's FolderExportTests)
+
+ static string FolderFixture(string name) => File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "folder-export", name));
+ static Session FolderSession() => Json.Read<Session>(FolderFixture("session.json"))!;
+ static JsonNode FolderCases() => JsonNode.Parse(FolderFixture("cases.json"))!;
+ static TimeZoneInfo FolderZone() => TimeZoneInfo.FindSystemTimeZoneById((string)FolderCases()["timeZone"]!);
+ static IEnumerable<(string, string)> Pairs(string key) => FolderCases()[key]!.AsArray().Select(p => ((string)p![0]!, (string)p[1]!));
+
+ public static void FolderExportFrontmatterBytes()
+ {
+ var got = FolderExportFormat.Frontmatter(FolderSession(), FolderZone());
+ Equal(FolderFixture("frontmatter.md"), got, "frontmatter bytes");
+ Check(!got.Contains('\r'), "\\n line ends on Windows too");
+ }
+
+ public static void FolderExportFileName()
+ {
+ var stem = FolderExportFormat.Stem(FolderSession(), FolderZone());
+ Equal((string)FolderCases()["fileName"]!, FolderExportFormat.FileName(stem, _ => false), "file name");
+ }
+
+ public static void FolderExportNames()
+ {
+ foreach (var (name, want) in Pairs("names")) Equal(want, FolderExportFormat.SafeName(name), $"safe name of «{name}»");
+ foreach (var (title, want) in Pairs("stems"))
+ {
+ var s = FolderSession();
+ s.Title = title;
+ Equal(want, FolderExportFormat.Stem(s, FolderZone()), $"stem of «{title}»");
+ }
+ foreach (var (text, want) in Pairs("escapes")) Equal(want, FolderExportFormat.Quote(text), $"quote of «{text}»");
+ foreach (var c in FolderCases()["collisions"]!.AsArray())
+ {
+ var taken = c!["taken"]!.AsArray().Select(t => (string)t!).ToList();
+ Equal((string)c["want"]!, FolderExportFormat.FileName((string)c["stem"]!, taken.Contains), $"collision with {taken.Count} taken");
+ }
+ }
+
+ /// The name: the user's title, else the notes', else the imported file's, never the display title.
+ public static void FolderExportNamePrecedence()
+ {
+ var s = FolderSession();
+ 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");
+ s.Renamed = null;
+ s.Title = "会议 11月6日 14:00";
+ Equal("Weekly sync", FolderExportFormat.Name(s), "an older record's default title isn't a name");
+ }
+
+ public static void FolderExportPaths()
+ {
+ var json = """{"vaults":{"a":{"path":"C:\\v\\old","ts":1},"b":{"path":"C:\\v\\new","ts":5,"open":true},"c":{"path":"D:\\gone","ts":9}}}""";
+ var vaults = FolderExportFormat.ObsidianVaults(json, p => p != @"D:\gone");
+ Equal(@"C:\v\new|C:\v\old", string.Join("|", vaults), "newest first, only ones that exist");
+ Equal(0, FolderExportFormat.ObsidianVaults("not json").Count, "unreadable");
+ Equal(@"C:\v\new", FolderExportFormat.Vault(@"c:\V\New\Cicada", vaults), "inside a vault, ignoring case");
+ Equal(null, FolderExportFormat.Vault(@"C:\v\newer\Cicada", vaults), "a neighbour isn't inside");
+ Equal("Documents › Cicada", FolderExportFormat.ShortPath(@"C:\Users\a\Documents\Cicada\"), "parent › folder");
+ Equal("D: › Cicada", FolderExportFormat.ShortPath(@"D:\Cicada"), "a drive's top folder");
+ Equal("文档 › Cicada", FolderExportFormat.ShortPath(@"C:\Users\a\Documents\Cicada", p => p.EndsWith("Documents") ? "文档" : null), "Explorer's names");
+ Equal(@"D:\", FolderExportFormat.Parent(@"D:\Cicada"), "the drive is the parent");
+ string[] roots = [@"C:\Users\a\OneDrive\Documents", @"C:\Users\a\Desktop"];
+ Check(FolderExportFormat.Protected(@"C:\Users\a\OneDrive\Documents\Cicada", roots), "Documents is protected");
+ Check(!FolderExportFormat.Protected(@"C:\Users\a\Notes\Cicada", roots), "elsewhere isn't");
+ }
+
+ public static async Task FolderExportWrites()
+ {
+ var dir = Path.Combine(Path.GetTempPath(), "cicada-export-" + Guid.NewGuid().ToString("N"));
+ var folder = Path.Combine(dir, "Cicada");
+ Directory.CreateDirectory(dir);
+ try
+ {
+ var store = new SessionStore();
+ var s = store.Begin(new DateTimeOffset(2026, 11, 6, 14, 0, 0, TimeSpan.Zero));
+ store.Append(s.Id, new TranscriptLine { Id = "l1", Src = "Hello", SrcLang = "en", Dst = "你好", DstLang = "zh", T = 3 });
+ store.End(s.Id, s.StartedAt.AddMinutes(30));
+ store.Rename(s.Id, "周会");
+ var settings = new AppSettings();
+ var index = Path.Combine(dir, "FolderExport.json");
+ var ex = new FolderExporter(store, settings, index) { Delay = TimeSpan.FromMilliseconds(20) };
+ var stem = FolderExportFormat.Stem(store.Get(s.Id)!);
+ // A file Cicada didn't write is never overwritten.
+ Directory.CreateDirectory(folder);
+ File.WriteAllText(Path.Combine(folder, stem + ".md"), "mine");
+ ex.Choose(folder);
+ await ex.Idle();
+ Equal(null, ex.Trouble, "the folder can be written");
+ Check(ex.Unwritten.Any(x => x.Id == s.Id), "an earlier meeting waits for 也存一份");
+ ex.WriteAll();
+ await ex.Idle();
+ Equal(stem + " 2.md", Path.GetFileName(ex.FileFor(s.Id)), "the taken name gets 2");
+ Equal("mine", File.ReadAllText(Path.Combine(folder, stem + ".md")), "the user's file stays");
+ var text = File.ReadAllText(ex.FileFor(s.Id)!);
+ Check(text.StartsWith("---\ncicada: 1\n") && text.Contains("title: \"周会\""), "frontmatter, then the body");
+ Check(!Directory.GetFiles(folder, ".cicada*").Any(), "no temporary or check file left");
+ Check(Json.Read<FolderExporter.Index>(File.ReadAllText(index))!.Files.ContainsKey(s.Id), "the index keeps it");
+ // A new name moves the file.
+ store.Rename(s.Id, "周会改");
+ store.Flush();
+ ex.Saved(s.Id);
+ await Task.Delay(200);
+ await ex.Idle();
+ var moved = ex.FileFor(s.Id)!;
+ Check(Path.GetFileName(moved).EndsWith("周会改.md"), "renamed: " + Path.GetFileName(moved));
+ Check(!File.Exists(Path.Combine(folder, stem + " 2.md")), "the old file went");
+ // Unchanged content isn't written again.
+ var at = File.GetLastWriteTimeUtc(moved);
+ ex.Saved(s.Id);
+ await Task.Delay(200);
+ await ex.Idle();
+ Equal(at, File.GetLastWriteTimeUtc(moved), "unchanged");
+ // Deleting the record leaves its file.
+ ex.Deleted(s.Id);
+ Check(File.Exists(moved), "the file stays");
+ store.Delete(s.Id);
+ // A folder whose parent is gone isn't made.
+ ex.Choose(Path.Combine(dir, "gone", "Cicada"));
+ await ex.Idle();
+ Equal(FolderExporter.Kind.Missing, ex.Trouble?.Kind, "missing");
+ Check(!Directory.Exists(Path.Combine(dir, "gone")), "nothing made");
+ }
+ finally { try { Directory.Delete(dir, true); } catch { } }
+ }
+
// MARK: the talk key (#22: keyboards without right Ctrl)
public static void TalkKeyChoices()