知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
chore(windows): add the Windows app (tray, notes window, subtitle bar, records, settings, onboarding) and its CI
wquguru731be4a652a7
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.ymlnew file mode 100644index 0000000..bd42d54--- /dev/null+++ b/.github/workflows/windows.yml@@ -0,0 +1,36 @@+name: windows++# The Windows app (windows/): unit tests on a real Windows runner, then the x64 and ARM64 builds+# as artifacts. Runners have no sound card, so listening itself is tested in a VM or on a PC.+on:+ push:+ branches: [main]+ paths: ["windows/**", "Resources/**/Localizable.strings", ".github/workflows/windows.yml"]+ pull_request:+ paths: ["windows/**", "Resources/**/Localizable.strings", ".github/workflows/windows.yml"]+ workflow_dispatch:++jobs:+ build:+ runs-on: windows-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-dotnet@v4+ with:+ dotnet-version: "10.0.x"+ - name: Unit tests+ run: |+ dotnet build windows/tests/Cicada.Tests -o windows/build/tests+ windows/build/tests/Cicada.Tests.exe+ - name: Translations+ run: python windows/scripts/strings.py+ - name: Build+ shell: bash+ run: |+ for rid in win-x64 win-arm64; do+ dotnet publish windows/src/Cicada -c Release -r $rid -o windows/build/Cicada-$rid+ done+ - uses: actions/upload-artifact@v4+ with:+ name: Cicada-windows+ path: windows/build/Cicada-win-*diff --git a/docs/windows-plan.md b/docs/windows-plan.mdindex adc0a36..5b6c047 100644--- a/docs/windows-plan.md+++ b/docs/windows-plan.md@@ -1,6 +1,6 @@# 知了 Windows 版技术方案-状态:草案(2026-11-03)。先做“听”:系统声音 → 实时翻译字幕 → 会议纪要 → 双语记录。“说”(同传进会议)放到后面。+状态:M1、M2 的代码已写完(2026-11-03),引擎在 Mac 上测过,界面和抓声音等虚拟机验证。代码和命令见 [windows/README.md](../windows/README.md)。还没做(M3):录音、安装包、签名、自动更新。先做“听”:系统声音 → 实时翻译字幕 → 会议纪要 → 双语记录。“说”(同传进会议)放到后面。## 范围diff --git a/windows/README.md b/windows/README.mdnew file mode 100644index 0000000..6b6f9eb--- /dev/null+++ b/windows/README.md@@ -0,0 +1,44 @@+# 知了 Windows 版++Cicada 的 Windows 版,目前只做“听”:把电脑播放的声音变成双语字幕和实时纪要,存成和 Mac 版同一格式的会议记录。方案和取舍见 [docs/windows-plan.md](../docs/windows-plan.md)。++- 抓声音:WASAPI 进程回环,排除知了自己(Windows 10 2004 起)。+- 识别:Ming(`Ming-3.0-audio-flash`)分段识别,一次请求同时返回语言、原文和译文;需要 Ling key。+- 纪要、记录格式、提示词、多语言文案都和 Mac 版一致;文案的英日韩翻译直接用 `Resources/*.lproj/Localizable.strings`,Windows 独有的在 `src/Cicada/Strings/`。++## 目录++| 路径 | 内容 |+|---|---|+| `src/Cicada.Core` | 不依赖界面的引擎(`net10.0`,Mac 上也能编译、运行、测试) |+| `src/Cicada` | Windows 应用:托盘、纪要窗 / 字幕条、会议记录、设置、引导(WPF,代码写界面,不用 XAML) |+| `src/Cicada.Cli` | 在 Mac 上用 WAV 文件跑完整流程、检查会议记录 |+| `tests/Cicada.Tests` | 单元测试(控制台程序,不用测试框架) |+| `spike/` | M0 验证:`ming_asr.py`、`LoopbackProbe` |++## 命令(在 Mac 上)++```bash+scripts/install-dotnet.sh # 一次:.NET 10 SDK 装到 ~/.dotnet,不用 sudo+scripts/test.sh # 单元测试+scripts/build.sh # 开发版:build/Cicada-win-x64/、build/Cicada-win-arm64/+RELEASE=1 scripts/build.sh # 发布版+python3 scripts/strings.py # 查缺翻译的文案(--write 追加 TODO)+```++不依赖 Windows 的验证:++```bash+DOTNET_ROOT=~/.dotnet build/cli/cicada-cli listen spike/clips/en.wav --target zh-CN --notes # 真实调用 Ming 和 Ling+DOTNET_ROOT=~/.dotnet build/cli/cicada-cli roundtrip ~/Library/Application\ Support/LiveSubs/Sessions/*/session.json+```++先 `scripts/dotnet.sh build src/Cicada.Cli -o build/cli` 编译命令行工具;它读 Mac 版的 key 文件,不打印 key。++## 在 Windows 里验证++1. 把 `build/Cicada-win-arm64`(ARM 虚拟机)或 `build/Cicada-win-x64`(x64 电脑)拷过去。+2. 先跑抓声音验证:`spike/LoopbackProbe` 编译出的 `LoopbackProbe.exe`,一次默认、一次 `--include-self`,前者应显示 `absent`,后者 `PRESENT`。+3. 双击 `Cicada Dev.cmd` 打开开发版(记录在 `%APPDATA%\Cicada Dev`,日志在 `%TEMP%\cicada-dev-debug.log`)。+4. 用 PowerShell 驱动:`scripts\cicadactl.ps1 state`、`start`、`feed C:\path\en.wav`、`view subtitles`、`capture on`、`stop`。+5. 检查:纪要窗不抢焦点(点它之后原来的窗口仍能打字);Win+Shift+S 截图和会议软件的屏幕共享里看不到它;打开“共享屏幕时让对方看到”后能看到,并显示“对方可见”。diff --git a/windows/scripts/build.sh b/windows/scripts/build.shnew file mode 100755index 0000000..181b0b4--- /dev/null+++ b/windows/scripts/build.sh@@ -0,0 +1,33 @@+#!/bin/bash+# Builds the Windows app on the Mac: build/Cicada-win-x64/ and build/Cicada-win-arm64/, each a+# self-contained Cicada.exe plus Resources/. RELEASE=1 for a release build (else a dev build,+# which keeps its records under "Cicada Dev" and opens the debug pipe).+set -euo pipefail+cd "$(dirname "$0")/.."+root=..+mkdir -p build/icon src/Cicada/Assets++# The icon (committed, regenerated here): the Mac app's 256 px icon at the sizes Windows asks for, PNGs inside one .ico.+for s in 16 24 32 48 64 256; do sips -z $s $s "$root/docs/icon.png" --out "build/icon/$s.png" >/dev/null; done+python3 - build/icon <<'PY'+import struct, sys, os+d = sys.argv[1]; sizes = [16, 24, 32, 48, 64, 256]+pngs = [open(os.path.join(d, f"{s}.png"), "rb").read() for s in sizes]+out = struct.pack("<HHH", 0, 1, len(sizes)); offset = 6 + 16 * len(sizes)+for s, p in zip(sizes, pngs):+ out += struct.pack("<BBBBHHII", s % 256, s % 256, 0, 0, 1, 32, len(p), offset); offset += len(p)+open(os.path.join(d, "..", "..", "src", "Cicada", "Assets", "cicada.ico"), "wb").write(out + b"".join(pngs))+PY++# The onboarding sample as 16 kHz WAV: SoundPlayer and the file source both read WAV only.+afconvert -f WAVE -d LEI16@16000 -c 1 "$root/Resources/sample/sample.m4a" src/Cicada/Assets/sample.wav++config=Debug; [ "${RELEASE:-}" = 1 ] && config=Release+for rid in win-x64 win-arm64; do+ out="build/Cicada-$rid"+ rm -rf "$out"+ scripts/dotnet.sh publish src/Cicada -c "$config" -r "$rid" -o "$out" -p:DebugType=embedded -v quiet -nologo 2>&1 | grep -E ' error |warning CS' | sort -u || true+ [ -f "$out/Cicada.exe" ] || { echo "build failed for $rid" >&2; exit 1; }+ [ "$config" = Debug ] && printf '@echo off\r\nstart "" "%%~dp0Cicada.exe" --dev\r\n' > "$out/Cicada Dev.cmd"+ echo "$out/Cicada.exe ($(du -h "$out/Cicada.exe" | cut -f1))"+donediff --git a/windows/scripts/cicadactl.ps1 b/windows/scripts/cicadactl.ps1new file mode 100644index 0000000..00d69d1--- /dev/null+++ b/windows/scripts/cicadactl.ps1@@ -0,0 +1,10 @@+# Sends one debug command to a running dev build (Cicada.exe --dev) and prints its JSON state.+# .\cicadactl.ps1 state | start | stop | sample | feed C:\clip.wav | view subtitles | capture on | show records | quit+param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Command)+$pipe = New-Object System.IO.Pipes.NamedPipeClientStream(".", "cicada-dev", [System.IO.Pipes.PipeDirection]::InOut)+$pipe.Connect(3000)+$writer = New-Object System.IO.StreamWriter($pipe); $writer.AutoFlush = $true+$reader = New-Object System.IO.StreamReader($pipe)+$writer.WriteLine(($Command -join " "))+$reader.ReadLine()+$pipe.Dispose()diff --git a/windows/scripts/strings.py b/windows/scripts/strings.pynew file mode 100755index 0000000..ff46076--- /dev/null+++ b/windows/scripts/strings.py@@ -0,0 +1,28 @@+#!/usr/bin/env python3+"""Lists Windows UI text with no translation: every L("…") / LF("…") key in windows/src that is in+neither the Mac's Resources/<lang>.lproj/Localizable.strings nor windows/src/Cicada/Strings/<lang>.lproj/Windows.strings.+--write appends the missing keys to Windows.strings as TODO lines (value = the Chinese)."""+import re, sys, pathlib+win = pathlib.Path(__file__).resolve().parent.parent+root = win.parent+keys = []+for f in sorted((win / "src").rglob("*.cs")):+ for k in re.findall(r'\bLF?\("((?:[^"\\]|\\.)*)"', f.read_text(encoding="utf-8")):+ if k not in keys: keys.append(k)+def table(path):+ if not path.exists(): return {}+ return dict(re.findall(r'^"((?:[^"\\]|\\.)*)"\s*=\s*"((?:[^"\\]|\\.)*)";', path.read_text(encoding="utf-8"), re.M))+missing_any = False+for lang in ["en", "ja", "ko"]:+ have = table(root / f"Resources/{lang}.lproj/Localizable.strings") | table(win / f"src/Cicada/Strings/{lang}.lproj/Windows.strings")+ missing = [k for k in keys if k not in have]+ if missing:+ missing_any = True+ print(f"{lang}: {len(missing)} missing")+ for k in missing: print(f" {k}")+ if "--write" in sys.argv:+ out = win / f"src/Cicada/Strings/{lang}.lproj/Windows.strings"+ out.parent.mkdir(parents=True, exist_ok=True)+ with out.open("a", encoding="utf-8") as f:+ for k in missing: f.write(f'"{k}" = "{k}"; /* TODO */\n')+sys.exit(1 if missing_any else 0)diff --git a/windows/src/Cicada.Core/Strings.cs b/windows/src/Cicada.Core/Strings.csindex a9d184b..3fa07d9 100644--- a/windows/src/Cicada.Core/Strings.cs+++ b/windows/src/Cicada.Core/Strings.cs@@ -4,7 +4,8 @@ using System.Text;namespace Cicada;/// UI text. The Chinese text is the key, as on the Mac, and the translations are the Mac's own-/// `Resources/{en,ja,ko}.lproj/Localizable.strings`, copied next to the app at build time.+/// `Resources/{en,ja,ko}.lproj/Localizable.strings`, copied next to the app at build time, plus+/// `windows/src/Cicada/Strings/*.lproj/Windows.strings` for text only the Windows app has./// Placeholders are the Mac's `%@`, filled in order. Never for prompts, logs or stored values.public static class Strings{@@ -18,8 +19,14 @@ public static class Stringsvar ui = language ?? CultureInfo.CurrentUICulture.Name;var head = ui.Split('-')[0];Language = head is "en" or "ja" or "ko" ? head : "zh-Hans";- var file = Path.Combine(folder, $"{Language}.lproj", "Localizable.strings");- table = File.Exists(file) ? Parse(File.ReadAllText(file, Encoding.UTF8)) : [];+ // The Mac's table, then the Windows-only strings over it (Windows.strings, same format).+ table = [];+ foreach (var name in new[] { "Localizable.strings", "Windows.strings" })+ {+ var file = Path.Combine(folder, $"{Language}.lproj", name);+ if (!File.Exists(file)) continue;+ foreach (var (k, v) in Parse(File.ReadAllText(file, Encoding.UTF8))) table[k] = v;+ }}public static string L(string key) => table.TryGetValue(key, out var v) && v.Length > 0 ? v : key;diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.csnew file mode 100644index 0000000..dc2847e--- /dev/null+++ b/windows/src/Cicada/App.cs@@ -0,0 +1,290 @@+using System.IO.Pipes;+using System.Media;+using System.Text.Json.Nodes;+using System.Windows;+using System.Windows.Threading;+using static Cicada.Strings;+using Forms = System.Windows.Forms;++namespace Cicada.App;++static class Program+{+ [STAThread]+ static int Main(string[] args)+ {+ Paths.Dev = Paths.Dev || args.Contains("--dev");+ // One Cicada per user: a second launch just opens the records of the running one.+ using var single = new Mutex(true, Paths.Dev ? "com.wquguru.cicada.dev" : "com.wquguru.cicada", out bool first);+ if (!first) { DebugServer.Send("show records"); return 0; }+ var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };+ app.DispatcherUnhandledException += (_, e) => { Log.Debug($"ui: unhandled {e.Exception.GetType().Name}: {e.Exception.Message}"); e.Handled = true; };+ var controller = new Controller(app);+ app.Startup += (_, _) => controller.Launch();+ return app.Run();+ }+}++/// Wires the engines to the windows, as AppModel does on the Mac. Engine events arrive on worker+/// threads; everything here that touches UI runs on the dispatcher.+sealed class Controller+{+ readonly Application application;+ public readonly AppSettings Settings = AppSettings.Load();+ public readonly AIKey Key = new(new DpapiProtector());+ public readonly LingClient Ling;+ public readonly SessionStore Store = new();+ public readonly NotesEngine Notes;+ public readonly Translator Translator;+ public readonly ListenEngine Listen;+ readonly Forms.NotifyIcon tray = new();+ NotesWindow? notesWindow;+ MainWindow? mainWindow;+ SettingsWindow? settingsWindow;+ Dispatcher Ui => application.Dispatcher;++ public Controller(Application application)+ {+ this.application = application;+ var ui = Settings.UiLanguage == "system" ? null : Settings.UiLanguage;+ Strings.Load(Path.Combine(AppContext.BaseDirectory, "Resources"), ui);+ Ling = new LingClient(Key) { Model = Settings.Model };+ Notes = new NotesEngine(Ling, Store);+ Translator = new Translator(Ling);+ Listen = new ListenEngine(Ling, Translator, Store, Notes, Settings);+ Listen.Changed += Changed;+ Notes.Changed += Changed;+ Store.Changed += _ => Changed();+ }++ public void Launch()+ {+ Log.Debug($"app: launch {(Paths.Dev ? "dev" : "release")} {Environment.OSVersion.Version}");+ SetUpTray();+ DebugServer.Start(this);+ if (!Settings.Onboarded) new Onboarding(this).Show();+ else if (Ling.HasKey) _ = Ling.Check();+ }++ void Changed() => Ui.BeginInvoke(() =>+ {+ notesWindow?.Refresh();+ mainWindow?.Refresh();+ UpdateTray();+ });++ // MARK: Tray (the Mac's menu bar panel)++ void SetUpTray()+ {+ tray.Icon = LoadIcon();+ tray.Text = L("知了");+ tray.Visible = true;+ tray.MouseClick += (_, e) => { if (e.Button == Forms.MouseButtons.Left) Ui.BeginInvoke(ShowNotes); };+ UpdateTray();+ }++ static System.Drawing.Icon LoadIcon()+ {+ try+ {+ var info = Application.GetResourceStream(new Uri("pack://application:,,,/cicada.ico"));+ return new System.Drawing.Icon(info!.Stream);+ }+ catch { return System.Drawing.SystemIcons.Application; }+ }++ void UpdateTray()+ {+ var menu = new Forms.ContextMenuStrip();+ menu.Items.Add(Listen.Listening ? L("结束") : L("开始听"), null, (_, _) => Ui.BeginInvoke(() => _ = ToggleListening()));+ menu.Items.Add(new Forms.ToolStripSeparator());+ menu.Items.Add(L("显示纪要"), null, (_, _) => Ui.BeginInvoke(ShowNotes));+ menu.Items.Add(L("会议记录"), null, (_, _) => Ui.BeginInvoke(ShowRecords));+ menu.Items.Add(L("设置"), null, (_, _) => Ui.BeginInvoke(ShowSettings));+ menu.Items.Add(new Forms.ToolStripSeparator());+ menu.Items.Add(L("退出"), null, (_, _) => Ui.BeginInvoke(() => _ = Quit()));+ var old = tray.ContextMenuStrip;+ tray.ContextMenuStrip = menu;+ old?.Dispose();+ tray.Text = Listen.Listening ? L("知了") + " · " + L("正在听") : L("知了");+ }++ // MARK: Listening++ public async Task ToggleListening()+ {+ if (Listen.Listening) await StopListening();+ else StartListening(new SystemAudioTap());+ }++ public void StartListening(IAudioSource source)+ {+ if (Listen.Listening) return;+ if (!Ling.HasKey) { new Onboarding(this).Show(); return; }+ source.Ended += reason =>+ {+ if (reason is null) return;+ Log.Debug($"listen: source ended {reason}");+ Ui.BeginInvoke(() => _ = StopListening());+ };+ Listen.Start(source);+ ShowNotes();+ }++ public async Task StopListening()+ {+ await Listen.Stop();+ Changed();+ }++ /// The onboarding sample: heard straight from the file (Cicada's own sound is left out of+ /// the system capture) while it plays aloud for the user.+ public async Task PlaySample()+ {+ var wav = Path.Combine(AppContext.BaseDirectory, "Resources", "sample.wav");+ if (!File.Exists(wav) || Listen.Listening) return;+ var source = new FileAudioSource(wav);+ var done = new TaskCompletionSource();+ source.Ended += _ => done.TrySetResult();+ StartListening(source);+ try { new SoundPlayer(wav).Play(); } catch (Exception e) { Log.Debug($"sample: play failed {e.GetType().Name}"); }+ await done.Task;+ await Task.Delay(3000); // the last segment's reply+ await StopListening();+ }++ // MARK: Windows++ public void ShowNotes()+ {+ notesWindow ??= new NotesWindow(this);+ notesWindow.Show();+ notesWindow.Refresh();+ }++ public void ShowRecords()+ {+ if (mainWindow is null) { mainWindow = new MainWindow(this); mainWindow.Closed += (_, _) => mainWindow = null; }+ mainWindow.Show();+ mainWindow.Activate();+ }++ public void ShowSettings()+ {+ if (settingsWindow is null) { settingsWindow = new SettingsWindow(this); settingsWindow.Closed += (_, _) => settingsWindow = null; }+ settingsWindow.Show();+ settingsWindow.Activate();+ }++ public void SetView(string view)+ {+ Settings.View = view;+ Settings.Save();+ if (notesWindow is null) return;+ notesWindow.Place();+ notesWindow.Refresh();+ }++ public void CaptureSettingChanged() => notesWindow?.ApplyCaptureSetting();+ public void SettingsChanged() => Changed();++ public async Task Quit()+ {+ if (Listen.Listening) await StopListening();+ Store.Flush();+ tray.Visible = false;+ tray.Dispose();+ application.Shutdown();+ }++ /// For the debug pipe: what a test needs to see (never meeting text).+ public JsonObject State() => new()+ {+ ["listening"] = Listen.Listening,+ ["session"] = Listen.SessionId,+ ["lines"] = Listen.SessionId is { } id ? Store.Get(id)?.Lines.Count ?? 0 : 0,+ ["pending"] = Listen.Pending,+ ["spoken"] = Listen.Spoken,+ ["target"] = Listen.Target,+ ["problem"] = Listen.Problem,+ ["notes"] = Notes.Status.ToString(),+ ["topics"] = Notes.Notes.Topics.Count,+ ["key"] = Ling.KeyState.ToString(),+ ["view"] = Settings.View,+ ["showInCapture"] = Settings.ShowInCapture,+ ["sessions"] = Store.All().Count,+ };+}++/// Debug commands over a named pipe (\\.\pipe\cicada-dev), dev builds only: the Windows+/// counterpart of the Mac's `tools/lsctl`. One command per connection, one JSON line back.+/// state | start | stop | feed <wav> | sample | view notes|subtitles | capture on|off+/// show notes|records|settings | quit+static class DebugServer+{+ static string Pipe => Paths.Dev ? "cicada-dev" : "cicada";++ public static void Start(Controller app)+ {+ new Thread(() =>+ {+ while (true)+ {+ try+ {+ using var server = new NamedPipeServerStream(Pipe, PipeDirection.InOut, 1);+ server.WaitForConnection();+ using var reader = new StreamReader(server);+ using var writer = new StreamWriter(server) { AutoFlush = true };+ var line = reader.ReadLine() ?? "";+ // A release build only takes "show records" (a second launch); the rest is for dev builds.+ if (!Paths.Dev && line != "show records") { writer.WriteLine("{\"error\":\"dev builds only\"}"); continue; }+ var reply = app.Dispatcher().Invoke(() => Run(app, line));+ writer.WriteLine(reply.ToJsonString());+ }+ catch (Exception e) { Log.Debug($"debug: {e.GetType().Name}"); Thread.Sleep(200); }+ }+ }) { IsBackground = true, Name = "DebugServer" }.Start();+ }++ static Dispatcher Dispatcher(this Controller _) => Application.Current.Dispatcher;++ static JsonObject Run(Controller app, string line)+ {+ var parts = line.Trim().Split(' ', 2);+ var arg = parts.Length > 1 ? parts[1].Trim() : "";+ Log.Debug($"debug: {parts[0]}");+ switch (parts[0])+ {+ case "start": app.StartListening(new SystemAudioTap()); break;+ case "stop": _ = app.StopListening(); break;+ case "feed": app.StartListening(new FileAudioSource(arg)); break;+ case "sample": _ = app.PlaySample(); break;+ case "view": app.SetView(arg == "subtitles" ? "subtitles" : "notes"); break;+ case "capture": app.Settings.ShowInCapture = arg == "on"; app.Settings.Save(); app.CaptureSettingChanged(); break;+ case "show":+ if (arg == "records") app.ShowRecords(); else if (arg == "settings") app.ShowSettings(); else app.ShowNotes();+ break;+ case "quit": _ = app.Quit(); break;+ case "state": break;+ default: return new JsonObject { ["error"] = $"unknown command {parts[0]}" };+ }+ return app.State();+ }++ /// Sends one command to the running app (a second launch uses it to bring records forward).+ public static string? Send(string command)+ {+ try+ {+ using var client = new NamedPipeClientStream(".", Pipe, PipeDirection.InOut);+ client.Connect(2000);+ using var writer = new StreamWriter(client) { AutoFlush = true };+ using var reader = new StreamReader(client);+ writer.WriteLine(command);+ return reader.ReadLine();+ }+ catch { return null; }+ }+}diff --git a/windows/src/Cicada/Assets/cicada.ico b/windows/src/Cicada/Assets/cicada.iconew file mode 100644index 0000000..a9d0a9aBinary files /dev/null and b/windows/src/Cicada/Assets/cicada.ico differdiff --git a/windows/src/Cicada/Assets/sample.wav b/windows/src/Cicada/Assets/sample.wavnew file mode 100644index 0000000..955877fBinary files /dev/null and b/windows/src/Cicada/Assets/sample.wav differdiff --git a/windows/src/Cicada/Cicada.csproj b/windows/src/Cicada/Cicada.csprojnew file mode 100644index 0000000..20823b8--- /dev/null+++ b/windows/src/Cicada/Cicada.csproj@@ -0,0 +1,35 @@+<Project Sdk="Microsoft.NET.Sdk">+ <!-- The Windows app: tray icon, notes window / subtitle bar, records, settings, onboarding.+ WPF in code (no XAML), WinForms only for the tray icon; no NuGet packages. -->+ <PropertyGroup>+ <OutputType>WinExe</OutputType>+ <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>+ <SupportedOSPlatformVersion>10.0.19041.0</SupportedOSPlatformVersion>+ <UseWPF>true</UseWPF>+ <UseWindowsForms>true</UseWindowsForms>+ <AssemblyName>Cicada</AssemblyName>+ <RootNamespace>Cicada.App</RootNamespace>+ <ApplicationIcon>Assets/cicada.ico</ApplicationIcon>+ <ApplicationManifest>app.manifest</ApplicationManifest>+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>+ <SelfContained>true</SelfContained>+ <PublishSingleFile>true</PublishSingleFile>+ <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>+ <!-- Self-contained WPF is ~200 MB; compressed ~half. Starts a little slower the first time. -->+ <EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>+ <Product>Cicada</Product>+ <Company>wquguru</Company>+ </PropertyGroup>+ <ItemGroup>+ <!-- WinForms is only here for the tray icon: keep its names out of the WPF code. -->+ <Using Remove="System.Windows.Forms" />+ <Using Remove="System.Drawing" />+ <Using Include="System.IO" />+ <None Include="../../../Resources/**/Localizable.strings" LinkBase="Resources" CopyToOutputDirectory="PreserveNewest" />+ <None Include="Strings/**/Windows.strings" LinkBase="Resources" CopyToOutputDirectory="PreserveNewest" />+ <!-- Both made by scripts/build.sh from docs/icon.png and Resources/sample/sample.m4a; committed so CI on Windows needs no Mac tools. -->+ <Resource Include="Assets/cicada.ico" Link="cicada.ico" />+ <None Include="Assets/sample.wav" Link="Resources/sample.wav" CopyToOutputDirectory="PreserveNewest" />+ <ProjectReference Include="../Cicada.Core/Cicada.Core.csproj" />+ </ItemGroup>+</Project>diff --git a/windows/src/Cicada/MainWindow.cs b/windows/src/Cicada/MainWindow.csnew file mode 100644index 0000000..7d654ae--- /dev/null+++ b/windows/src/Cicada/MainWindow.cs@@ -0,0 +1,165 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media;+using static Cicada.Strings;++namespace Cicada.App;++/// 会议记录: the meetings on the left, the chosen one's notes and bilingual transcript on the+/// right, on one white sheet (no cards), as the Mac's main window.+sealed class MainWindow : Window+{+ readonly Controller app;+ readonly ListBox list = new() { BorderThickness = new Thickness(0), Background = Brushes.Transparent, FontFamily = Palette.Font };+ readonly ContentControl detail = new();+ string? selected;+ bool refreshQueued;++ public MainWindow(Controller app)+ {+ this.app = app;+ Title = L("会议记录") + " · " + L("知了");+ Width = 1000; Height = 680; MinWidth = 720; MinHeight = 480;+ Background = Palette.Card; FontFamily = Palette.Font; Icon = AppIcon.Image;+ WindowStartupLocation = WindowStartupLocation.CenterScreen;++ var grid = new Grid();+ grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(290) });+ grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1) });+ grid.ColumnDefinitions.Add(new ColumnDefinition());+ var left = new DockPanel { Margin = new Thickness(12, 16, 8, 12) };+ var top = Ui.Row(8, Ui.Heading(L("会议记录"), 17));+ top.Margin = new Thickness(8, 0, 0, 12);+ DockPanel.SetDock(top, Dock.Top);+ left.Children.Add(top);+ left.Children.Add(list);+ Grid.SetColumn(left, 0);+ var divider = new Border { Background = Palette.Line };+ Grid.SetColumn(divider, 1);+ var right = new ScrollViewer { Content = detail, Padding = new Thickness(32, 24, 32, 32), VerticalScrollBarVisibility = ScrollBarVisibility.Auto };+ Grid.SetColumn(right, 2);+ grid.Children.Add(left); grid.Children.Add(divider); grid.Children.Add(right);+ Content = grid;++ list.SelectionChanged += (_, _) =>+ {+ if (list.SelectedItem is ListBoxItem { Tag: string id } && id != selected) { selected = id; ShowDetail(); }+ };+ Refresh();+ }++ public void Refresh()+ {+ if (refreshQueued) return;+ refreshQueued = true;+ Dispatcher.BeginInvoke(() => { refreshQueued = false; Fill(); });+ }++ void Fill()+ {+ var sessions = app.Store.All();+ list.Items.Clear();+ foreach (var s in sessions)+ {+ var live = app.Listen.Listening && app.Listen.SessionId == s.Id;+ var row = Ui.Stack(2,+ Ui.Text(SessionStore.DisplayTitle(s), 13, Palette.Ink, FontWeights.SemiBold, wrap: false),+ Ui.Text(live ? L("正在听") : $"{s.StartedAt.ToLocalTime():yyyy-MM-dd HH:mm} · {Languages.Clock(s.Duration.TotalSeconds)}", 11, live ? Palette.Accent : Palette.Tertiary, wrap: false));+ row.Margin = new Thickness(6, 6, 6, 6);+ list.Items.Add(new ListBoxItem { Content = row, Tag = s.Id });+ }+ if (sessions.Count == 0) { selected = null; detail.Content = Empty(); return; }+ selected ??= sessions[0].Id;+ if (sessions.All(s => s.Id != selected)) selected = sessions[0].Id;+ list.SelectedItem = list.Items.Cast<ListBoxItem>().First(i => (string)i.Tag == selected);+ ShowDetail();+ }++ static FrameworkElement Empty() => Ui.Stack(6, Ui.Heading(L("还没有会议记录")), Ui.Helper(L("点“开始听”,电脑里播放的声音会变成双语字幕和纪要")));++ void ShowDetail()+ {+ if (selected is null || app.Store.Get(selected) is not { } s) { detail.Content = Empty(); return; }+ var page = new StackPanel { MaxWidth = 720, HorizontalAlignment = HorizontalAlignment.Left };+ var title = Ui.Text(SessionStore.DisplayTitle(s), 22, Palette.Ink, FontWeights.SemiBold);+ page.Children.Add(title);+ page.Children.Add(Gap(Ui.Helper($"{s.StartedAt.ToLocalTime():yyyy-MM-dd HH:mm} · {Languages.Clock(s.Duration.TotalSeconds)} · {s.Lines.Count} {L("句")}"), 4));++ var actions = Ui.Row(8,+ Ui.Button(L("导出"), () => Export(s)),+ Ui.Button(L("重命名"), () => Rename(s)),+ Ui.Button(L("删除"), () => Delete(s)));+ if (s.Notes is null or { IsEmpty: true } && !(app.Listen.Listening && app.Listen.SessionId == s.Id))+ actions.Children.Insert(0, Ui.Button(L("生成纪要"), () => _ = app.Notes.Generate(s.Id), "primary"));+ page.Children.Add(Gap(actions, 14));++ if (s.Notes is { IsEmpty: false } n)+ {+ page.Children.Add(Gap(Ui.Heading(L("纪要"), 16), 28));+ page.Children.Add(Gap(Ui.Text(n.Summary, 14, Palette.Body), 8));+ foreach (var t in n.Topics)+ {+ page.Children.Add(Gap(Ui.Row(8, Ui.Text(Languages.Clock(t.Start), 12, Palette.Link, FontWeights.SemiBold, wrap: false), Ui.Text(t.Title, 14, Palette.Ink, FontWeights.SemiBold)), 16));+ if (t.Summary.Length > 0) page.Children.Add(Gap(Ui.Text(t.Summary, 13, Palette.Secondary), 4));+ foreach (var p in t.Points) page.Children.Add(Gap(Ui.Text("· " + p, 13, Palette.Body), 4));+ }+ Section(page, L("结论"), n.Conclusions.Select(c => c.Text));+ Section(page, L("待办"), n.Todos.Select(t => "☐ " + t.Text + (t.Owner is null ? "" : $" · {t.Owner}")));+ }++ page.Children.Add(Gap(Ui.Heading(L("文字记录"), 16), 28));+ foreach (var l in s.Lines)+ {+ var row = new Grid { Margin = new Thickness(0, 10, 0, 0) };+ row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(56) });+ row.ColumnDefinitions.Add(new ColumnDefinition());+ var time = Ui.Text(Languages.Clock(l.T), 12, Palette.Link, FontWeights.SemiBold, wrap: false);+ var text = Ui.Stack(2, Ui.Text(l.Src, 14, Palette.Ink));+ if (!string.IsNullOrEmpty(l.Dst) && l.Dst != l.Src) text.Children.Add(Ui.Text(l.Dst, 13, Palette.Secondary));+ Grid.SetColumn(text, 1);+ row.Children.Add(time); row.Children.Add(text);+ page.Children.Add(row);+ }+ detail.Content = page;+ }++ static FrameworkElement Gap(FrameworkElement e, double top) { e.Margin = new Thickness(0, top, 0, 0); return e; }++ static void Section(StackPanel page, string title, IEnumerable<string> items)+ {+ var list = items.ToList();+ if (list.Count == 0) return;+ page.Children.Add(Gap(Ui.Text(title, 13, Palette.Secondary, FontWeights.SemiBold), 18));+ foreach (var i in list) page.Children.Add(Gap(Ui.Text(i, 13, Palette.Body), 4));+ }++ void Export(Session s)+ {+ var dialog = new Microsoft.Win32.SaveFileDialog+ {+ FileName = SafeName(SessionStore.DisplayTitle(s)) + ".md", Filter = "Markdown (*.md)|*.md", DefaultExt = ".md",+ };+ if (dialog.ShowDialog(this) == true) File.WriteAllText(dialog.FileName, SessionStore.Markdown(s));+ }++ static string SafeName(string name) => string.Concat(name.Select(c => Path.GetInvalidFileNameChars().Contains(c) ? '-' : c)).Trim();++ void Rename(Session s)+ {+ var box = new TextBox { Text = SessionStore.DisplayTitle(s), FontSize = 14, Padding = new Thickness(6), MinWidth = 320 };+ var window = Ui.StyledWindow(L("重命名"), 420, 170);+ window.Owner = this;+ window.ResizeMode = ResizeMode.NoResize;+ window.Content = Ui.Card(Ui.Stack(12, box, Ui.Row(8,+ Ui.Button(L("保存"), () => { if (box.Text.Trim().Length > 0) app.Store.Rename(s.Id, box.Text); window.Close(); }, "primary"),+ Ui.Button(L("取消"), window.Close))), 16);+ window.Loaded += (_, _) => { box.Focus(); box.SelectAll(); };+ window.ShowDialog();+ }++ void Delete(Session s)+ {+ var ok = MessageBox.Show(this, LF("删除“%@”?删除后无法恢复。", SessionStore.DisplayTitle(s)), L("删除"), MessageBoxButton.OKCancel, MessageBoxImage.Warning);+ if (ok == MessageBoxResult.OK) app.Store.Delete(s.Id);+ }+}diff --git a/windows/src/Cicada/Native.cs b/windows/src/Cicada/Native.csnew file mode 100644index 0000000..c21982b--- /dev/null+++ b/windows/src/Cicada/Native.cs@@ -0,0 +1,80 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Interop;++namespace Cicada.App;++/// Win32 bits WPF doesn't expose: windows that never take focus and stay out of screen captures,+/// and DPAPI for the key file.+static class Native+{+ const int GWL_EXSTYLE = -20;+ const long WS_EX_NOACTIVATE = 0x08000000, WS_EX_TOOLWINDOW = 0x00000080, WS_EX_TOPMOST = 0x00000008;+ const int WM_MOUSEACTIVATE = 0x0021, MA_NOACTIVATE = 3;+ const uint WDA_NONE = 0, WDA_EXCLUDEFROMCAPTURE = 0x11;++ [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW")] static extern IntPtr GetWindowLongPtr(IntPtr hwnd, int index);+ [DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW")] static extern IntPtr SetWindowLongPtr(IntPtr hwnd, int index, IntPtr value);+ [DllImport("user32.dll")] static extern bool SetWindowDisplayAffinity(IntPtr hwnd, uint affinity);++ /// Makes a window like the Mac's non-activating panel: clicks and drags work, but the app the+ /// user is in keeps the keyboard focus, and the window isn't in Alt+Tab or the taskbar.+ public static void MakeNonActivating(Window window)+ {+ var hwnd = new WindowInteropHelper(window).EnsureHandle();+ var ex = GetWindowLongPtr(hwnd, GWL_EXSTYLE).ToInt64();+ SetWindowLongPtr(hwnd, GWL_EXSTYLE, new IntPtr(ex | WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST));+ HwndSource.FromHwnd(hwnd)?.AddHook((IntPtr h, int msg, IntPtr w, IntPtr l, ref bool handled) =>+ {+ if (msg == WM_MOUSEACTIVATE) { handled = true; return new IntPtr(MA_NOACTIVATE); }+ return IntPtr.Zero;+ });+ }++ /// Out of screenshots and screen sharing (Windows 10 2004+), unless the user lets the other side see it.+ public static bool SetCaptureVisible(Window window, bool visible)+ {+ var hwnd = new WindowInteropHelper(window).EnsureHandle();+ var ok = SetWindowDisplayAffinity(hwnd, visible ? WDA_NONE : WDA_EXCLUDEFROMCAPTURE);+ if (!ok) Log.Debug($"window: display affinity failed {Marshal.GetLastWin32Error()}");+ return ok;+ }+}++/// DPAPI, current user: the key file can only be opened by this Windows account.+sealed class DpapiProtector : IKeyProtector+{+ public string Tag => "dpapi";++ [StructLayout(LayoutKind.Sequential)]+ struct Blob { public int cbData; public IntPtr pbData; }++ [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)]+ static extern bool CryptProtectData(ref Blob input, string? description, IntPtr entropy, IntPtr reserved, IntPtr prompt, int flags, out Blob output);+ [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)]+ static extern bool CryptUnprotectData(ref Blob input, IntPtr description, IntPtr entropy, IntPtr reserved, IntPtr prompt, int flags, out Blob output);+ [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr mem);++ const int CRYPTPROTECT_UI_FORBIDDEN = 0x1;++ public byte[] Protect(byte[] data) => Run(data, protect: true);+ public byte[] Unprotect(byte[] data) => Run(data, protect: false);++ static byte[] Run(byte[] data, bool protect)+ {+ var handle = GCHandle.Alloc(data, GCHandleType.Pinned);+ try+ {+ var input = new Blob { cbData = data.Length, pbData = handle.AddrOfPinnedObject() };+ bool ok = protect+ ? CryptProtectData(ref input, "Cicada Ling key", IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, CRYPTPROTECT_UI_FORBIDDEN, out var output)+ : CryptUnprotectData(ref input, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, CRYPTPROTECT_UI_FORBIDDEN, out output);+ if (!ok) throw new InvalidOperationException($"DPAPI failed {Marshal.GetLastWin32Error()}");+ var result = new byte[output.cbData];+ Marshal.Copy(output.pbData, result, 0, output.cbData);+ LocalFree(output.pbData);+ return result;+ }+ finally { handle.Free(); }+ }+}diff --git a/windows/src/Cicada/NotesWindow.cs b/windows/src/Cicada/NotesWindow.csnew file mode 100644index 0000000..d6c2cb2--- /dev/null+++ b/windows/src/Cicada/NotesWindow.cs@@ -0,0 +1,208 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Threading;+using static Cicada.Strings;++namespace Cicada.App;++/// The window shown while listening: live notes (default) or the subtitle bar. Like the Mac's+/// notes panel it never takes focus (the user keeps typing in their meeting app) and stays out of+/// screen captures unless 共享屏幕时让对方看到 is on, which shows a badge.+sealed class NotesWindow : Window+{+ readonly Controller app;+ readonly DispatcherTimer clock = new() { Interval = TimeSpan.FromSeconds(1) };+ // Kept across renders: the clock only redraws the header, and the notes keep their scroll position.+ ContentControl header = new(), live = new();+ ScrollViewer scroll = new();+ string? builtFor;+ bool renderQueued;++ public NotesWindow(Controller app)+ {+ this.app = app;+ WindowStyle = WindowStyle.None;+ AllowsTransparency = true;+ Background = Brushes.Transparent;+ Topmost = true;+ ShowInTaskbar = false;+ ShowActivated = false;+ ResizeMode = ResizeMode.CanResizeWithGrip;+ FontFamily = Palette.Font;+ Title = L("知了");+ SourceInitialized += (_, _) =>+ {+ Native.MakeNonActivating(this);+ ApplyCaptureSetting();+ };+ // Drag from anywhere that isn't a link, button or scroll bar (those mark the click handled).+ MouseLeftButtonDown += (_, e) => { if (e.ButtonState == MouseButtonState.Pressed) try { DragMove(); } catch { } };+ clock.Tick += (_, _) => header.Content = Header();+ IsVisibleChanged += (_, _) => { if (IsVisible) clock.Start(); else clock.Stop(); };+ Place();+ Render();+ }++ bool Subtitles => app.Settings.View == "subtitles";++ /// Notes at the right edge, subtitles along the bottom, on the primary screen's work area.+ public void Place()+ {+ var area = SystemParameters.WorkArea;+ if (Subtitles)+ {+ Width = Math.Min(820, area.Width - 40); Height = 128;+ Left = area.Left + (area.Width - Width) / 2; Top = area.Bottom - Height - 24;+ }+ else+ {+ Width = 380; Height = Math.Min(620, area.Height - 48);+ Left = area.Right - Width - 20; Top = area.Top + 24;+ }+ }++ public void ApplyCaptureSetting()+ {+ if (!Native.SetCaptureVisible(this, app.Settings.ShowInCapture) && !app.Settings.ShowInCapture)+ Log.Debug("notes window: could not hide from capture (needs Windows 10 2004+)");+ Render();+ }++ /// Changes come from engine threads: coalesce them into one render on the UI thread.+ public void Refresh()+ {+ if (renderQueued) return;+ renderQueued = true;+ Dispatcher.BeginInvoke(DispatcherPriority.Background, () => { renderQueued = false; Render(); });+ }++ void Render()+ {+ var mode = Subtitles ? "subtitles" : "notes";+ if (builtFor != mode)+ {+ builtFor = mode;+ // New hosts for a new layout: an element can't move between parents.+ header = new ContentControl(); live = new ContentControl();+ scroll = new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Margin = new Thickness(0, 12, 0, 0) };+ FrameworkElement layout;+ if (Subtitles) layout = Ui.Stack(8, header, live);+ else+ {+ var dock = new DockPanel();+ DockPanel.SetDock(header, Dock.Top);+ var liveCard = new Border { Background = Palette.Ground, CornerRadius = new CornerRadius(10), Padding = new Thickness(12, 10, 12, 10), Child = live, Margin = new Thickness(0, 12, 0, 0) };+ DockPanel.SetDock(liveCard, Dock.Top);+ dock.Children.Add(header); dock.Children.Add(liveCard); dock.Children.Add(scroll);+ layout = dock;+ }+ Content = new Border+ {+ Background = Palette.Card, CornerRadius = new CornerRadius(14), BorderBrush = Palette.Line, BorderThickness = new Thickness(1),+ Padding = new Thickness(16, 12, 16, 14), Child = layout,+ Effect = new System.Windows.Media.Effects.DropShadowEffect { BlurRadius = 18, ShadowDepth = 2, Opacity = 0.12 },+ Margin = new Thickness(8),+ };+ }+ header.Content = Header();+ live.Content = LiveLine(Subtitles ? 20 : 15);+ if (!Subtitles)+ {+ var offset = scroll.VerticalOffset;+ scroll.Content = NotesBody();+ scroll.ScrollToVerticalOffset(offset);+ }+ }++ FrameworkElement Header()+ {+ var listen = app.Listen;+ var session = listen.SessionId is { } id ? app.Store.Get(id) : null;+ string status = listen.Listening && session is not null+ ? L("正在听 · ") + Languages.Clock((DateTimeOffset.Now - session.StartedAt).TotalSeconds)+ : L("知了");+ var left = Ui.Row(8, Ui.Dot(listen.Listening ? Palette.Accent : Palette.Line), Ui.Text(status, 13, Palette.Ink, FontWeights.SemiBold, wrap: false));+ if (app.Settings.ShowInCapture) left.Children.Add(WithMargin(Ui.Badge(L("对方可见")), 8));+ var right = Ui.Row(12,+ Ui.LinkText(listen.Listening ? L("结束") : L("开始听"), () => _ = app.ToggleListening()),+ Ui.LinkText(Subtitles ? L("纪要") : L("字幕"), () => app.SetView(Subtitles ? "notes" : "subtitles")),+ Ui.LinkText("×", Hide));+ var grid = new DockPanel { LastChildFill = false };+ DockPanel.SetDock(left, Dock.Left); DockPanel.SetDock(right, Dock.Right);+ grid.Children.Add(left); grid.Children.Add(right);+ return grid;+ }++ static T WithMargin<T>(T e, double left) where T : FrameworkElement { e.Margin = new Thickness(left, 0, 0, 0); return e; }++ /// The newest line, translation large, original small above it; "…" while Ming is still on one.+ FrameworkElement LiveLine(double big)+ {+ var listen = app.Listen;+ var line = listen.SessionId is { } id ? app.Store.Get(id)?.Lines.LastOrDefault() : null;+ var stack = new StackPanel();+ if (line is null)+ {+ var hint = listen.Problem ?? (listen.Listening ? (listen.Pending > 0 ? L("正在听…") : L("等有人说话")) : L("点“开始听”,电脑里播放的声音会变成双语字幕和纪要"));+ stack.Children.Add(Ui.Text(hint, 13, listen.Problem is null ? Palette.Tertiary : Palette.Accent));+ return stack;+ }+ if (line.Dst is not null && line.Dst != line.Src) stack.Children.Add(Ui.Text(line.Src, 12, Palette.Secondary));+ var main = Ui.Text(line.Dst ?? line.Src, big, Palette.Ink, FontWeights.SemiBold);+ main.Margin = new Thickness(0, 2, 0, 0);+ stack.Children.Add(main);+ var foot = listen.Problem ?? (listen.Pending > 0 ? L("正在听…") : null);+ if (foot is not null) { var f = Ui.Helper(foot); f.Margin = new Thickness(0, 4, 0, 0); stack.Children.Add(f); }+ return stack;+ }++ FrameworkElement NotesBody()+ {+ var notes = app.Notes.Notes;+ var body = new StackPanel();+ if (notes.IsEmpty)+ {+ var hint = app.Notes.Status switch+ {+ NotesEngine.State.NoKey => L("生成纪要需要 API key"),+ NotesEngine.State.InvalidKey => L("这个 key 无效,请检查是否复制完整,或重新创建一个"),+ NotesEngine.State.RateLimited => L("请求过于频繁,稍后会自动重试。"),+ NotesEngine.State.Updating => L("正在整理纪要…"),+ _ => app.Listen.Listening ? L("会中每 45 秒更新") : "",+ };+ if (hint.Length > 0) body.Children.Add(Spaced(Ui.Helper(hint), 2));+ return body;+ }+ if (notes.Title is { Length: > 0 } t) body.Children.Add(Spaced(Ui.Heading(t, 16), 4));+ if (notes.Summary.Length > 0) body.Children.Add(Spaced(Ui.Text(notes.Summary, 13, Palette.Body), 6));+ foreach (var topic in notes.Topics)+ {+ body.Children.Add(Spaced(Ui.Row(8, Ui.Text(Languages.Clock(topic.Start), 11, Palette.Link, FontWeights.SemiBold, wrap: false),+ Ui.Text(topic.Title, 13, Palette.Ink, FontWeights.SemiBold)), 14));+ foreach (var p in topic.Points) body.Children.Add(Spaced(Bullet(p), 4));+ }+ if (notes.Conclusions.Count > 0)+ {+ body.Children.Add(Spaced(Ui.Text(L("结论"), 12, Palette.Secondary, FontWeights.SemiBold), 16));+ foreach (var c in notes.Conclusions) body.Children.Add(Spaced(Bullet(c.Text), 4));+ }+ if (notes.Todos.Count > 0)+ {+ body.Children.Add(Spaced(Ui.Text(L("待办"), 12, Palette.Secondary, FontWeights.SemiBold), 16));+ foreach (var todo in notes.Todos) body.Children.Add(Spaced(Bullet("☐ " + todo.Text + (todo.Owner is null ? "" : $" · {todo.Owner}"), bullet: false), 4));+ }+ if (app.Notes.Status == NotesEngine.State.Updating) body.Children.Add(Spaced(Ui.Helper(L("正在整理纪要…")), 12));+ return body;+ }++ static FrameworkElement Spaced(FrameworkElement e, double top) { e.Margin = new Thickness(0, top, 0, 0); return e; }++ static FrameworkElement Bullet(string text, bool bullet = true)+ {+ var t = Ui.Text((bullet ? "· " : "") + text, 13, Palette.Body);+ t.Margin = new Thickness(bullet ? 2 : 0, 0, 0, 0);+ return t;+ }+}diff --git a/windows/src/Cicada/Onboarding.cs b/windows/src/Cicada/Onboarding.csnew file mode 100644index 0000000..e0d1801--- /dev/null+++ b/windows/src/Cicada/Onboarding.cs@@ -0,0 +1,112 @@+using System.Diagnostics;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Threading;+using static Cicada.Strings;++namespace Cicada.App;++/// First run, three steps. Windows needs no permission for system audio, and listening needs the+/// Ling key (recognition is Ming's), so the key comes first: Ling key → system audio → sample meeting.+sealed class Onboarding : Window+{+ readonly Controller app;+ readonly ContentControl page = new();+ int step;+ SystemAudioTap? tap;+ readonly DispatcherTimer meter = new() { Interval = TimeSpan.FromMilliseconds(100) };+ double level, peak;++ public Onboarding(Controller app)+ {+ this.app = app;+ Title = L("知了");+ Width = 520; Height = 460; ResizeMode = ResizeMode.NoResize;+ Background = Palette.Ground; FontFamily = Palette.Font; Icon = AppIcon.Image;+ WindowStartupLocation = WindowStartupLocation.CenterScreen;+ Content = new Border { Padding = new Thickness(24), Child = page };+ meter.Tick += (_, _) => { if (step == 1) Render(); };+ Closed += (_, _) => StopTap();+ step = app.Ling.HasKey ? 1 : 0;+ Render();+ }++ void Next()+ {+ StopTap();+ step++;+ if (step > 2) { app.Settings.Onboarded = true; app.Settings.Save(); Close(); return; }+ Render();+ }++ void Render() => page.Content = step switch { 0 => KeyStep(), 1 => AudioStep(), _ => SampleStep() };++ FrameworkElement Frame(string title, string helper, FrameworkElement body, FrameworkElement buttons)+ {+ var dots = Ui.Row(6, Enumerable.Range(0, 3).Select(i => Ui.Dot(i == step ? Palette.Accent : Palette.Line, 7)).ToArray());+ var dock = new DockPanel();+ DockPanel.SetDock(buttons, Dock.Bottom);+ buttons.HorizontalAlignment = HorizontalAlignment.Right;+ dock.Children.Add(buttons);+ dock.Children.Add(Ui.Card(Ui.Stack(12, dots, Ui.Heading(title, 18), Ui.Helper(helper), body), 24));+ return dock;+ }++ FrameworkElement KeyStep()+ {+ var box = new PasswordBox { FontSize = 13, Padding = new Thickness(6) };+ var status = Ui.Helper("");+ async void Save()+ {+ var text = box.Password.Trim();+ if (!text.StartsWith("sk-")) { status.Text = L("复制 sk- 开头的 key,回来粘贴"); return; }+ app.Key.Save(text);+ app.Ling.KeyChanged();+ status.Text = L("正在检查…");+ var (state, _) = await app.Ling.Check();+ if (state == KeyState.Ok) Next();+ else status.Text = state == KeyState.Invalid ? L("这个 key 无效,请检查是否复制完整,或重新创建一个") : L("连不上 Ling,检查网络");+ }+ var body = Ui.Stack(10,+ Ui.LinkText(L("在 Ling 开放平台创建 key"), () => Process.Start(new ProcessStartInfo("https://chat.ant-ling.com/platform/api") { UseShellExecute = true })),+ Ui.Helper(L("在 Ling 开放平台点“创建令牌”,复制以 sk- 开头的那串。")),+ box, status);+ return Frame(L("接上 Ling,用上完整的知了"), L("识别、翻译和纪要都靠它,约 1 分钟。"), body, Ui.Row(8, Ui.Button(L("继续"), Save, "primary")));+ }++ FrameworkElement AudioStep()+ {+ if (tap is null)+ {+ tap = new SystemAudioTap();+ tap.Samples += buf =>+ {+ double sum = 0;+ foreach (var s in buf) sum += (double)s * s;+ level = buf.Length == 0 ? 0 : Math.Sqrt(sum / buf.Length) / 32768;+ peak = Math.Max(peak, level);+ };+ tap.Start();+ meter.Start();+ }+ var bar = new ProgressBar { Minimum = 0, Maximum = 1, Value = Math.Min(1, level * 8), Height = 8, Foreground = Palette.Accent, Background = Palette.Ground, BorderThickness = new Thickness(0) };+ var heard = peak >= 0.01;+ var body = Ui.Stack(12, bar, Ui.Text(heard ? L("听到了") : L("放一段视频或音乐,看这条有没有跳动"), 13, heard ? Palette.Ink : Palette.Secondary));+ return Frame(L("系统声音"), L("知了听的是电脑播放出来的声音,不用麦克风,也不用授权。"), body,+ Ui.Row(8, Ui.Button(L("继续"), Next, heard ? "primary" : "quiet")));+ }++ FrameworkElement SampleStep()+ {+ var body = Ui.Stack(10, Ui.Text(L("播放一段约 9 秒的示例会议,看字幕和纪要怎么出现。"), 13, Palette.Secondary));+ return Frame(L("示例会议"), L("纪要窗口不会抢走焦点,也不会出现在屏幕共享里。"), body,+ Ui.Row(8, Ui.Button(L("播放示例"), () => _ = app.PlaySample(), "accent"), Ui.Button(L("完成"), Next, "primary")));+ }++ void StopTap()+ {+ meter.Stop();+ tap?.Stop();+ tap = null;+ }+}diff --git a/windows/src/Cicada/SettingsWindow.cs b/windows/src/Cicada/SettingsWindow.csnew file mode 100644index 0000000..e1786b4--- /dev/null+++ b/windows/src/Cicada/SettingsWindow.cs@@ -0,0 +1,121 @@+using System.Diagnostics;+using System.Windows;+using System.Windows.Controls;+using static Cicada.Strings;++namespace Cicada.App;++/// 设置: the Ling key, languages, how listening shows, and the model.+sealed class SettingsWindow : Window+{+ readonly Controller app;+ readonly TextBlock keyStatus = Ui.Text("", 13, Palette.Secondary);+ readonly PasswordBox keyBox = new() { FontSize = 13, Padding = new Thickness(6), MinWidth = 280 };++ public SettingsWindow(Controller app)+ {+ this.app = app;+ Title = L("设置") + " · " + L("知了");+ Width = 560; Height = 640; Background = Palette.Ground; FontFamily = Palette.Font; Icon = AppIcon.Image;+ WindowStartupLocation = WindowStartupLocation.CenterScreen;+ var s = app.Settings;++ var key = Ui.Card(Ui.Stack(10,+ Ui.Heading(L("Ling key")),+ keyStatus,+ Ui.Row(8, keyBox, Ui.Button(L("保存"), SaveKey, "primary")),+ Ui.Row(16, Ui.LinkText(L("获取 Ling key ↗"), OpenLing), Ui.LinkText(L("删除 key"), RemoveKey)),+ Ui.Helper(L("只存在这台电脑上(只有你的 Windows 账户能读),只发给 Ling(ant-ling.com)"))));++ var languages = Ui.Card(Ui.Stack(12,+ Ui.Heading(L("语言")),+ Field(L("翻译成"), Ui.Choice(Ui.TargetOptions(), s.Target, v => { s.Target = v; Save(); })),+ Field(L("纪要语言"), Ui.Choice([("system", L("和字幕一样")), .. Languages.Targets.Select(t => (t.Code, t.Name))], s.NotesLanguage, v => { s.NotesLanguage = v; Save(); })),+ Field(L("界面语言"), Ui.Choice([("system", L("跟随系统")), ("zh-Hans", "简体中文"), ("en", "English"), ("ja", "日本語"), ("ko", "한국어")], s.UiLanguage,+ v => { s.UiLanguage = v; Save(); MessageBox.Show(this, L("重新打开知了后生效"), L("知了")); }))));++ var capture = new CheckBox { Content = Ui.Text(L("共享屏幕时让对方看到"), 13), IsChecked = s.ShowInCapture, FocusVisualStyle = null };+ capture.Click += (_, _) => { s.ShowInCapture = capture.IsChecked == true; Save(); app.CaptureSettingChanged(); };+ var display = Ui.Card(Ui.Stack(12,+ Ui.Heading(L("显示")),+ Field(L("听的时候显示"), Ui.Choice([("notes", L("实时纪要")), ("subtitles", L("字幕条"))], s.View, v => app.SetView(v))),+ capture,+ Ui.Helper(L("关着时,截图和屏幕共享里看不到纪要窗口和字幕"))));++ var model = Ui.Card(Ui.Stack(12,+ Ui.Heading(L("模型")),+ Field(L("纪要和翻译"), Ui.Choice([("Ling-3.1-flash", "Ling-3.1-flash"), ("Ling-3.0-flash", "Ling-3.0-flash")], s.Model,+ v => { s.Model = v; app.Ling.Model = v; Save(); })),+ Ui.Helper(L("3.1 更准;3.0 更快、更省")),+ Ui.Helper(L("语音识别用 Ming(云端),一次请求同时返回原文和译文"))));++ var about = Ui.Card(Ui.Stack(8,+ Ui.Heading(L("关于")),+ Ui.Helper($"{L("知了")} {typeof(SettingsWindow).Assembly.GetName().Version?.ToString(3)} · Windows"),+ Ui.Row(16, Ui.LinkText(L("打开记录所在文件夹"), () => OpenFolder(Paths.Sessions)), Ui.LinkText(L("打开日志"), () => OpenFolder(Path.GetDirectoryName(Paths.Log)!)))));++ Content = new ScrollViewer+ {+ Content = Ui.Stack(12, key, languages, display, model, about),+ Padding = new Thickness(20), VerticalScrollBarVisibility = ScrollBarVisibility.Auto,+ };+ app.Ling.Changed += OnLingChanged;+ Closed += (_, _) => app.Ling.Changed -= OnLingChanged;+ ShowKeyState();+ }++ static FrameworkElement Field(string label, FrameworkElement control)+ {+ var g = new Grid();+ g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(140) });+ g.ColumnDefinitions.Add(new ColumnDefinition());+ var t = Ui.Text(label, 13, Palette.Secondary);+ t.VerticalAlignment = VerticalAlignment.Center;+ Grid.SetColumn(control, 1);+ control.HorizontalAlignment = HorizontalAlignment.Left;+ g.Children.Add(t); g.Children.Add(control);+ return g;+ }++ void Save() { app.Settings.Save(); app.SettingsChanged(); }++ void OnLingChanged() => Dispatcher.BeginInvoke(ShowKeyState);++ void ShowKeyState()+ {+ var key = app.Key.Read();+ keyStatus.Text = app.Ling.KeyState switch+ {+ KeyState.None => L("还没填 API key"),+ KeyState.Checking => L("正在检查…"),+ KeyState.Invalid => L("这个 key 无效,请检查是否复制完整,或重新创建一个"),+ KeyState.Unreachable => L("连不上 Ling,检查网络"),+ KeyState.Ok => AIKey.Masked(key ?? "") + " · " + L("可以用"),+ _ => AIKey.Masked(key ?? ""),+ };+ }++ async void SaveKey()+ {+ var text = keyBox.Password.Trim();+ if (!text.StartsWith("sk-")) { keyStatus.Text = L("复制 sk- 开头的 key,回来粘贴"); return; }+ if (!app.Key.Save(text)) { keyStatus.Text = L("保存失败"); return; }+ keyBox.Clear();+ app.Ling.KeyChanged();+ await app.Ling.Check();+ }++ void RemoveKey()+ {+ app.Key.Remove();+ app.Ling.KeyChanged();+ }++ static void OpenLing() => Process.Start(new ProcessStartInfo("https://chat.ant-ling.com/platform/api") { UseShellExecute = true });++ static void OpenFolder(string path)+ {+ Directory.CreateDirectory(path);+ Process.Start(new ProcessStartInfo("explorer.exe", $"\"{path}\"") { UseShellExecute = true });+ }+}diff --git a/windows/src/Cicada/Strings/en.lproj/Windows.strings b/windows/src/Cicada/Strings/en.lproj/Windows.stringsnew file mode 100644index 0000000..80599f9--- /dev/null+++ b/windows/src/Cicada/Strings/en.lproj/Windows.strings@@ -0,0 +1,40 @@+/* Windows-only UI text; the Mac's Localizable.strings covers the rest. Check: windows/scripts/strings.py */+"显示纪要" = "Show notes";+"还没有会议记录" = "No meetings yet";+"点“开始听”,电脑里播放的声音会变成双语字幕和纪要" = "Click “Start listening” and what your PC plays becomes bilingual subtitles and notes";+"句" = "lines";+"重命名" = "Rename";+"删除“%@”?删除后无法恢复。" = "Delete “%@”? This can't be undone.";+"对方可见" = "Visible to others";+"等有人说话" = "Waiting for someone to speak";+"请求过于频繁,稍后会自动重试。" = "Too many requests; retrying shortly.";+"连不上 Ling,检查网络" = "Can't reach Ling; check your network";+"识别、翻译和纪要都靠它,约 1 分钟。" = "Recognition, translation and notes all run on it. About a minute.";+"听到了" = "Heard it";+"放一段视频或音乐,看这条有没有跳动" = "Play a video or some music and watch this bar move";+"知了听的是电脑播放出来的声音,不用麦克风,也不用授权。" = "Cicada listens to what your PC plays. No microphone, no permission needed.";+"播放一段约 9 秒的示例会议,看字幕和纪要怎么出现。" = "Play a 9-second sample meeting and watch the subtitles and notes appear.";+"示例会议" = "Sample meeting";+"纪要窗口不会抢走焦点,也不会出现在屏幕共享里。" = "The notes window never takes focus and stays out of screen sharing.";+"播放示例" = "Play sample";+"Ling key" = "Ling key";+"删除 key" = "Remove key";+"只存在这台电脑上(只有你的 Windows 账户能读),只发给 Ling(ant-ling.com)" = "Stored only on this PC (readable only by your Windows account) and sent only to Ling (ant-ling.com)";+"和字幕一样" = "Same as subtitles";+"界面语言" = "App language";+"重新打开知了后生效" = "Takes effect after reopening Cicada";+"关着时,截图和屏幕共享里看不到纪要窗口和字幕" = "When off, the notes window and subtitles don't appear in screenshots or screen sharing";+"纪要和翻译" = "Notes and translation";+"语音识别用 Ming(云端),一次请求同时返回原文和译文" = "Speech recognition uses Ming (cloud): one request returns both the original and the translation";+"关于" = "About";+"打开记录所在文件夹" = "Open the records folder";+"可以用" = "Works";+"保存失败" = "Couldn't save";+"需要 Ling key 才能听" = "Listening needs a Ling key";+"Ling key 无效" = "The Ling key is invalid";+"Ling 太忙,稍后再试" = "Ling is busy; trying again shortly";+"会议" = "Meeting";+"M月d日 HH:mm" = "MMM d HH:mm";+"M月d日" = "MMM d";+"yyyy年M月d日" = "MMM d, yyyy";+"纪要停留在 %@。" = "Notes stop at %@.";diff --git a/windows/src/Cicada/Strings/ja.lproj/Windows.strings b/windows/src/Cicada/Strings/ja.lproj/Windows.stringsnew file mode 100644index 0000000..b8dfcc9--- /dev/null+++ b/windows/src/Cicada/Strings/ja.lproj/Windows.strings@@ -0,0 +1,40 @@+/* Windows-only UI text; the Mac's Localizable.strings covers the rest. Check: windows/scripts/strings.py */+"显示纪要" = "メモを表示";+"还没有会议记录" = "まだ会議の記録はありません";+"点“开始听”,电脑里播放的声音会变成双语字幕和纪要" = "「聞き取り開始」を押すと、PC で再生される音声が 2 言語の字幕とメモになります";+"句" = "件";+"重命名" = "名前を変更";+"删除“%@”?删除后无法恢复。" = "「%@」を削除しますか?元に戻せません。";+"对方可见" = "相手に表示中";+"等有人说话" = "誰かが話すのを待っています";+"请求过于频繁,稍后会自动重试。" = "リクエストが多すぎます。まもなく自動で再試行します。";+"连不上 Ling,检查网络" = "Ling に接続できません。ネットワークを確認してください";+"识别、翻译和纪要都靠它,约 1 分钟。" = "認識・翻訳・メモはすべてこれで動きます。約 1 分。";+"听到了" = "聞こえました";+"放一段视频或音乐,看这条有没有跳动" = "動画や音楽を再生して、このバーが動くか確認してください";+"知了听的是电脑播放出来的声音,不用麦克风,也不用授权。" = "知了は PC で再生される音声を聞きます。マイクも許可も不要です。";+"播放一段约 9 秒的示例会议,看字幕和纪要怎么出现。" = "約 9 秒のサンプル会議を再生して、字幕とメモが出る様子を見てみましょう。";+"示例会议" = "サンプル会議";+"纪要窗口不会抢走焦点,也不会出现在屏幕共享里。" = "メモウィンドウはフォーカスを奪わず、画面共有にも映りません。";+"播放示例" = "サンプルを再生";+"Ling key" = "Ling キー";+"删除 key" = "キーを削除";+"只存在这台电脑上(只有你的 Windows 账户能读),只发给 Ling(ant-ling.com)" = "この PC にのみ保存され(あなたの Windows アカウントだけが読めます)、Ling(ant-ling.com)にのみ送信されます";+"和字幕一样" = "字幕と同じ";+"界面语言" = "表示言語";+"重新打开知了后生效" = "知了を開き直すと反映されます";+"关着时,截图和屏幕共享里看不到纪要窗口和字幕" = "オフの間、メモウィンドウと字幕はスクリーンショットや画面共有に映りません";+"纪要和翻译" = "メモと翻訳";+"语音识别用 Ming(云端),一次请求同时返回原文和译文" = "音声認識は Ming(クラウド)を使い、1 回のリクエストで原文と訳文を返します";+"关于" = "情報";+"打开记录所在文件夹" = "記録フォルダを開く";+"可以用" = "使用できます";+"保存失败" = "保存できませんでした";+"需要 Ling key 才能听" = "聞き取りには Ling キーが必要です";+"Ling key 无效" = "Ling キーが無効です";+"Ling 太忙,稍后再试" = "Ling が混み合っています。まもなく再試行します";+"会议" = "会議";+"M月d日 HH:mm" = "M月d日 HH:mm";+"M月d日" = "M月d日";+"yyyy年M月d日" = "yyyy年M月d日";+"纪要停留在 %@。" = "メモは %@ までです。";diff --git a/windows/src/Cicada/Strings/ko.lproj/Windows.strings b/windows/src/Cicada/Strings/ko.lproj/Windows.stringsnew file mode 100644index 0000000..2abdd1e--- /dev/null+++ b/windows/src/Cicada/Strings/ko.lproj/Windows.strings@@ -0,0 +1,40 @@+/* Windows-only UI text; the Mac's Localizable.strings covers the rest. Check: windows/scripts/strings.py */+"显示纪要" = "노트 보기";+"还没有会议记录" = "아직 회의 기록이 없습니다";+"点“开始听”,电脑里播放的声音会变成双语字幕和纪要" = "‘듣기 시작’을 누르면 PC에서 재생되는 소리가 이중 언어 자막과 노트가 됩니다";+"句" = "줄";+"重命名" = "이름 바꾸기";+"删除“%@”?删除后无法恢复。" = "‘%@’을(를) 삭제할까요? 되돌릴 수 없습니다.";+"对方可见" = "상대에게 보임";+"等有人说话" = "누군가 말하기를 기다리는 중";+"请求过于频繁,稍后会自动重试。" = "요청이 너무 많습니다. 잠시 후 자동으로 다시 시도합니다.";+"连不上 Ling,检查网络" = "Ling에 연결할 수 없습니다. 네트워크를 확인하세요";+"识别、翻译和纪要都靠它,约 1 分钟。" = "인식, 번역, 노트 모두 이것으로 동작합니다. 약 1분.";+"听到了" = "들립니다";+"放一段视频或音乐,看这条有没有跳动" = "동영상이나 음악을 재생하고 이 막대가 움직이는지 보세요";+"知了听的是电脑播放出来的声音,不用麦克风,也不用授权。" = "Cicada는 PC에서 재생되는 소리를 듣습니다. 마이크도 권한도 필요 없습니다.";+"播放一段约 9 秒的示例会议,看字幕和纪要怎么出现。" = "약 9초짜리 샘플 회의를 재생해 자막과 노트가 나타나는 모습을 보세요.";+"示例会议" = "샘플 회의";+"纪要窗口不会抢走焦点,也不会出现在屏幕共享里。" = "노트 창은 포커스를 가져가지 않고 화면 공유에도 나오지 않습니다.";+"播放示例" = "샘플 재생";+"Ling key" = "Ling 키";+"删除 key" = "키 삭제";+"只存在这台电脑上(只有你的 Windows 账户能读),只发给 Ling(ant-ling.com)" = "이 PC에만 저장되며(내 Windows 계정만 읽을 수 있음) Ling(ant-ling.com)에만 전송됩니다";+"和字幕一样" = "자막과 같게";+"界面语言" = "앱 언어";+"重新打开知了后生效" = "Cicada를 다시 열면 적용됩니다";+"关着时,截图和屏幕共享里看不到纪要窗口和字幕" = "끄면 노트 창과 자막이 스크린샷과 화면 공유에 나오지 않습니다";+"纪要和翻译" = "노트와 번역";+"语音识别用 Ming(云端),一次请求同时返回原文和译文" = "음성 인식은 Ming(클라우드)을 쓰며, 한 번의 요청으로 원문과 번역을 함께 받습니다";+"关于" = "정보";+"打开记录所在文件夹" = "기록 폴더 열기";+"可以用" = "사용 가능";+"保存失败" = "저장하지 못했습니다";+"需要 Ling key 才能听" = "듣기에는 Ling 키가 필요합니다";+"Ling key 无效" = "Ling 키가 유효하지 않습니다";+"Ling 太忙,稍后再试" = "Ling이 바쁩니다. 잠시 후 다시 시도합니다";+"会议" = "회의";+"M月d日 HH:mm" = "M월 d일 HH:mm";+"M月d日" = "M월 d일";+"yyyy年M月d日" = "yyyy년 M월 d일";+"纪要停留在 %@。" = "노트는 %@에서 멈춰 있습니다.";diff --git a/windows/src/Cicada/SystemAudioTap.cs b/windows/src/Cicada/SystemAudioTap.csnew file mode 100644index 0000000..488c1c4--- /dev/null+++ b/windows/src/Cicada/SystemAudioTap.cs@@ -0,0 +1,211 @@+using System.Runtime.InteropServices;++namespace Cicada.App;++/// Everything the PC plays except Cicada itself: WASAPI process loopback with this process's tree+/// excluded (Windows 10 2004+), the counterpart of the Mac's Core Audio process tap. Asks Windows+/// for 16 kHz mono directly and falls back to 48 kHz stereo converted here. The capture thread+/// only hands buffers on; ListenEngine queues them.+sealed class SystemAudioTap : IAudioSource+{+ const string LoopbackDevice = "VAD\\Process_Loopback";+ const uint StreamLoopback = 0x00020000, StreamEventCallback = 0x00040000, AutoConvertPcm = 0x80000000, SrcDefaultQuality = 0x08000000;+ const uint BufferSilent = 0x2;++ Thread? thread;+ volatile bool running;+ public event Action<short[]>? Samples;+ public event Action<string?>? Ended;++ public void Start()+ {+ running = true;+ thread = new Thread(Run) { IsBackground = true, Name = "SystemAudioTap", Priority = ThreadPriority.AboveNormal };+ thread.SetApartmentState(ApartmentState.MTA);+ thread.Start();+ }++ public void Stop()+ {+ running = false;+ thread?.Join(1000);+ }++ void Run()+ {+ try { Capture(); Ended?.Invoke(null); }+ catch (Exception e)+ {+ Log.Debug($"tap: failed {e.GetType().Name} 0x{e.HResult:X8}");+ Ended?.Invoke(e.Message);+ }+ }++ void Capture()+ {+ (int rate, int channels)[] tries = [(16000, 1), (48000, 2), (44100, 2)];+ IAudioClient? client = null;+ int rate = 0, channels = 0;+ foreach (var (r, c) in tries)+ {+ client = Activate();+ var fmt = WaveFormat.Pcm16(r, c);+ var p = Marshal.AllocHGlobal(Marshal.SizeOf<WaveFormat>());+ Marshal.StructureToPtr(fmt, p, false);+ int hr = client.Initialize(0, StreamLoopback | StreamEventCallback | AutoConvertPcm | SrcDefaultQuality, 200_000, 0, p, IntPtr.Zero);+ Marshal.FreeHGlobal(p);+ if (hr == 0) { rate = r; channels = c; break; }+ Log.Debug($"tap: {r} Hz x{c} refused 0x{hr:X8}");+ Marshal.ReleaseComObject(client);+ client = null;+ }+ if (client is null) throw new InvalidOperationException("no capture format accepted");+ Log.Debug($"tap: capturing {rate} Hz x{channels}");++ using var ready = new AutoResetEvent(false);+ Marshal.ThrowExceptionForHR(client.SetEventHandle(ready.SafeWaitHandle.DangerousGetHandle()));+ var iid = typeof(IAudioCaptureClient).GUID;+ Marshal.ThrowExceptionForHR(client.GetService(ref iid, out var service));+ var capture = (IAudioCaptureClient)service;+ Marshal.ThrowExceptionForHR(client.Start());+ try+ {+ var silence = DateTime.UtcNow;+ while (running)+ {+ // Loopback sends nothing while nothing plays: feed silence ourselves so pauses end+ // segments and the clock keeps going.+ if (!ready.WaitOne(100))+ {+ var gap = DateTime.UtcNow - silence;+ if (gap.TotalMilliseconds >= 100) { Samples?.Invoke(new short[(int)(gap.TotalSeconds * 16000)]); silence = DateTime.UtcNow; }+ continue;+ }+ while (capture.GetNextPacketSize(out var packet) == 0 && packet > 0)+ {+ Marshal.ThrowExceptionForHR(capture.GetBuffer(out var data, out var frames, out var flags, out _, out _));+ int count = (int)frames * channels;+ var buf = new short[count];+ if ((flags & BufferSilent) == 0) Marshal.Copy(data, buf, 0, count);+ capture.ReleaseBuffer(frames);+ Samples?.Invoke(channels == 1 && rate == 16000 ? buf : ToMono16k(buf, rate, channels));+ }+ silence = DateTime.UtcNow;+ }+ }+ finally+ {+ client.Stop();+ Marshal.ReleaseComObject(capture);+ Marshal.ReleaseComObject(client);+ }+ }++ static short[] ToMono16k(short[] interleaved, int rate, int channels)+ {+ int frames = interleaved.Length / channels;+ var mono = new double[frames];+ for (int f = 0; f < frames; f++)+ {+ double sum = 0;+ for (int c = 0; c < channels; c++) sum += interleaved[f * channels + c];+ mono[f] = sum / channels;+ }+ return Wav.Resample(mono, rate);+ }++ static IAudioClient Activate()+ {+ var p = new ActivationParams { ActivationType = 1, TargetProcessId = (uint)Environment.ProcessId, ProcessLoopbackMode = 1 /* exclude tree */ };+ int size = Marshal.SizeOf<ActivationParams>();+ var blob = Marshal.AllocHGlobal(size);+ Marshal.StructureToPtr(p, blob, false);+ var variant = new PropVariantBlob { vt = 65, cbSize = (uint)size, pBlobData = blob };+ var handler = new Completion();+ var iid = typeof(IAudioClient).GUID;+ try+ {+ Marshal.ThrowExceptionForHR(ActivateAudioInterfaceAsync(LoopbackDevice, ref iid, ref variant, handler, out var op));+ if (!handler.Done.Wait(5000)) throw new TimeoutException("audio activation did not complete");+ Marshal.ThrowExceptionForHR(op.GetActivateResult(out var hr, out var iface));+ Marshal.ThrowExceptionForHR(hr);+ return (IAudioClient)iface;+ }+ finally { Marshal.FreeHGlobal(blob); }+ }++ [DllImport("Mmdevapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]+ static extern int ActivateAudioInterfaceAsync(string path, ref Guid riid, ref PropVariantBlob activationParams,+ IActivateAudioInterfaceCompletionHandler handler, out IActivateAudioInterfaceAsyncOperation op);++ // Must be agile, or activation fails with E_ILLEGAL_METHOD_CALL.+ [ComVisible(true)]+ sealed class Completion : IActivateAudioInterfaceCompletionHandler, IAgileObject+ {+ public readonly ManualResetEventSlim Done = new(false);+ public int ActivateCompleted(IActivateAudioInterfaceAsyncOperation op) { Done.Set(); return 0; }+ }++ [StructLayout(LayoutKind.Sequential)]+ struct ActivationParams { public int ActivationType; public uint TargetProcessId; public int ProcessLoopbackMode; }++ [StructLayout(LayoutKind.Explicit)]+ struct PropVariantBlob+ {+ [FieldOffset(0)] public ushort vt;+ [FieldOffset(8)] public uint cbSize;+ [FieldOffset(16)] public IntPtr pBlobData;+ }++ [StructLayout(LayoutKind.Sequential, Pack = 2)]+ struct WaveFormat+ {+ public ushort wFormatTag, nChannels; public uint nSamplesPerSec, nAvgBytesPerSec;+ public ushort nBlockAlign, wBitsPerSample, cbSize;+ public static WaveFormat Pcm16(int rate, int channels) => new()+ {+ wFormatTag = 1, nChannels = (ushort)channels, nSamplesPerSec = (uint)rate,+ nBlockAlign = (ushort)(channels * 2), nAvgBytesPerSec = (uint)(rate * channels * 2), wBitsPerSample = 16,+ };+ }++ [ComImport, Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ interface IAudioClient+ {+ [PreserveSig] int Initialize(int shareMode, uint streamFlags, long bufferDuration, long periodicity, IntPtr format, IntPtr sessionGuid);+ [PreserveSig] int GetBufferSize(out uint frames);+ [PreserveSig] int GetStreamLatency(out long latency);+ [PreserveSig] int GetCurrentPadding(out uint padding);+ [PreserveSig] int IsFormatSupported(int shareMode, IntPtr format, out IntPtr closest);+ [PreserveSig] int GetMixFormat(out IntPtr format);+ [PreserveSig] int GetDevicePeriod(out long defaultPeriod, out long minimumPeriod);+ [PreserveSig] int Start();+ [PreserveSig] int Stop();+ [PreserveSig] int Reset();+ [PreserveSig] int SetEventHandle(IntPtr handle);+ [PreserveSig] int GetService(ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object service);+ }++ [ComImport, Guid("C8ADBD64-E71E-48a0-A4DE-185C395CD317"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ interface IAudioCaptureClient+ {+ [PreserveSig] int GetBuffer(out IntPtr data, out uint frames, out uint flags, out ulong devicePosition, out ulong qpcPosition);+ [PreserveSig] int ReleaseBuffer(uint frames);+ [PreserveSig] int GetNextPacketSize(out uint frames);+ }++ [ComImport, Guid("72A22D78-CDE4-431D-B8CC-843A71199B6D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ interface IActivateAudioInterfaceAsyncOperation+ {+ [PreserveSig] int GetActivateResult(out int hr, [MarshalAs(UnmanagedType.IUnknown)] out object iface);+ }++ [ComImport, Guid("41D949AB-9862-444A-80F6-C261334DA5EB"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ interface IActivateAudioInterfaceCompletionHandler+ {+ [PreserveSig] int ActivateCompleted(IActivateAudioInterfaceAsyncOperation op);+ }++ [ComImport, Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ interface IAgileObject { }+}diff --git a/windows/src/Cicada/Ui.cs b/windows/src/Cicada/Ui.csnew file mode 100644index 0000000..1e03804--- /dev/null+++ b/windows/src/Cicada/Ui.cs@@ -0,0 +1,159 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Media;+using static Cicada.Strings;++namespace Cicada.App;++/// The Mac's palette (Views.swift › Palette) and a few builders, so every window is made the same+/// way in code: ground #F3F4F6, white cards, ink #15171C, one accent #E8552B for "live".+static class Palette+{+ static SolidColorBrush B(byte r, byte g, byte b) { var x = new SolidColorBrush(Color.FromRgb(r, g, b)); x.Freeze(); return x; }+ public static readonly SolidColorBrush Ground = B(0xF3, 0xF4, 0xF6);+ public static readonly SolidColorBrush Card = B(0xFF, 0xFF, 0xFF);+ public static readonly SolidColorBrush Ink = B(0x15, 0x17, 0x1C);+ public static readonly SolidColorBrush Body = B(0x3D, 0x41, 0x4A);+ public static readonly SolidColorBrush Secondary = B(0x5A, 0x5F, 0x6B);+ public static readonly SolidColorBrush Tertiary = B(0x6B, 0x70, 0x80);+ public static readonly SolidColorBrush Line = B(0xE4, 0xE6, 0xEA);+ public static readonly SolidColorBrush Accent = B(0xE8, 0x55, 0x2B);+ public static readonly SolidColorBrush AccentPale = B(0xFD, 0xEB, 0xE4);+ public static readonly SolidColorBrush Link = B(0xB3, 0x3B, 0x14);+ public static readonly SolidColorBrush ErrorPale = B(0xFD, 0xEC, 0xEC);+ public static readonly FontFamily Font = new("Segoe UI Variable Text, Segoe UI, Microsoft YaHei UI, Yu Gothic UI, Malgun Gothic");+}++static class Ui+{+ public static TextBlock Text(string text, double size = 13, Brush? color = null, FontWeight? weight = null, bool wrap = true) => new()+ {+ Text = text, FontSize = size, Foreground = color ?? Palette.Ink, FontWeight = weight ?? FontWeights.Normal,+ TextWrapping = wrap ? TextWrapping.Wrap : TextWrapping.NoWrap, TextTrimming = wrap ? TextTrimming.None : TextTrimming.CharacterEllipsis,+ FontFamily = Palette.Font,+ };++ public static TextBlock Heading(string text, double size = 15) => Text(text, size, Palette.Ink, FontWeights.SemiBold);+ public static TextBlock Helper(string text) => Text(text, 12, Palette.Tertiary);++ public static Border Card(UIElement child, double padding = 16, double radius = 12) => new()+ {+ Background = Palette.Card, CornerRadius = new CornerRadius(radius), Padding = new Thickness(padding), Child = child,+ };++ public static StackPanel Stack(double gap, params UIElement[] children)+ {+ var s = new StackPanel();+ foreach (var c in children)+ {+ if (c is FrameworkElement f && s.Children.Count > 0) f.Margin = new Thickness(f.Margin.Left, f.Margin.Top + gap, f.Margin.Right, f.Margin.Bottom);+ s.Children.Add(c);+ }+ return s;+ }++ public static StackPanel Row(double gap, params UIElement[] children)+ {+ var s = new StackPanel { Orientation = Orientation.Horizontal };+ foreach (var c in children)+ {+ if (c is FrameworkElement f && s.Children.Count > 0) f.Margin = new Thickness(f.Margin.Left + gap, f.Margin.Top, f.Margin.Right, f.Margin.Bottom);+ if (c is FrameworkElement v) v.VerticalAlignment = VerticalAlignment.Center;+ s.Children.Add(c);+ }+ return s;+ }++ /// A flat button: filled ink (primary), filled accent (live) or a quiet grey one.+ public static Button Button(string label, Action onClick, string kind = "quiet")+ {+ var (bg, fg) = kind switch+ {+ "primary" => (Palette.Ink, Brushes.White),+ "accent" => (Palette.Accent, Brushes.White),+ _ => (Palette.Ground, Palette.Ink),+ };+ var b = new Button+ {+ Content = new TextBlock { Text = label, FontSize = 13, FontWeight = FontWeights.SemiBold, FontFamily = Palette.Font },+ Foreground = fg, Background = bg, BorderThickness = new Thickness(0), Padding = new Thickness(14, 7, 14, 7),+ Cursor = Cursors.Hand, Focusable = false,+ };+ b.Template = RoundedTemplate(8);+ b.Click += (_, _) => onClick();+ return b;+ }++ /// A button with rounded corners and no Windows chrome.+ static ControlTemplate RoundedTemplate(double radius)+ {+ var t = new ControlTemplate(typeof(Button));+ var border = new FrameworkElementFactory(typeof(Border));+ border.SetValue(Border.CornerRadiusProperty, new CornerRadius(radius));+ border.SetBinding(Border.BackgroundProperty, new System.Windows.Data.Binding("Background") { RelativeSource = System.Windows.Data.RelativeSource.TemplatedParent });+ border.SetBinding(Border.PaddingProperty, new System.Windows.Data.Binding("Padding") { RelativeSource = System.Windows.Data.RelativeSource.TemplatedParent });+ var content = new FrameworkElementFactory(typeof(ContentPresenter));+ content.SetValue(ContentPresenter.HorizontalAlignmentProperty, HorizontalAlignment.Center);+ content.SetValue(ContentPresenter.VerticalAlignmentProperty, VerticalAlignment.Center);+ border.AppendChild(content);+ t.VisualTree = border;+ var hover = new Trigger { Property = UIElement.IsMouseOverProperty, Value = true };+ hover.Setters.Add(new Setter(UIElement.OpacityProperty, 0.85));+ t.Triggers.Add(hover);+ return t;+ }++ /// A text link in the link colour.+ public static TextBlock LinkText(string label, Action onClick)+ {+ var t = Text(label, 12, Palette.Link, FontWeights.SemiBold, wrap: false);+ t.Cursor = Cursors.Hand;+ // On press, and handled, so the notes window doesn't start dragging instead.+ t.MouseLeftButtonDown += (_, e) => { e.Handled = true; onClick(); };+ return t;+ }++ /// The small round "live" dot.+ public static FrameworkElement Dot(Brush color, double size = 8) => new System.Windows.Shapes.Ellipse { Width = size, Height = size, Fill = color };++ /// The badge shown when the window is visible in screen sharing (共享屏幕时让对方看到).+ public static Border Badge(string text) => new()+ {+ Background = Palette.AccentPale, CornerRadius = new CornerRadius(8), Padding = new Thickness(7, 2, 7, 2),+ Child = Text(text, 10, Palette.Link, FontWeights.SemiBold, wrap: false),+ };++ public static ComboBox Choice(IEnumerable<(string value, string label)> options, string selected, Action<string> changed)+ {+ var box = new ComboBox { MinWidth = 180, FontFamily = Palette.Font, FontSize = 13 };+ foreach (var (value, label) in options)+ {+ var item = new ComboBoxItem { Content = label, Tag = value };+ box.Items.Add(item);+ if (value == selected) box.SelectedItem = item;+ }+ box.SelectionChanged += (_, _) => { if (box.SelectedItem is ComboBoxItem { Tag: string v }) changed(v); };+ return box;+ }++ public static IEnumerable<(string, string)> TargetOptions() =>+ [("system", L("跟随系统")), .. Languages.Targets.Select(t => (t.Code, t.Name))];++ public static Window StyledWindow(string title, double width, double height) => new()+ {+ Title = title, Width = width, Height = height, Background = Palette.Ground, FontFamily = Palette.Font,+ WindowStartupLocation = WindowStartupLocation.CenterScreen, Icon = AppIcon.Image,+ };+}++static class AppIcon+{+ public static readonly System.Windows.Media.Imaging.BitmapFrame? Image = Load();++ static System.Windows.Media.Imaging.BitmapFrame? Load()+ {+ try { return System.Windows.Media.Imaging.BitmapFrame.Create(new Uri("pack://application:,,,/cicada.ico")); }+ catch { return null; }+ }+}diff --git a/windows/src/Cicada/app.manifest b/windows/src/Cicada/app.manifestnew file mode 100644index 0000000..146dcfb--- /dev/null+++ b/windows/src/Cicada/app.manifest@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">+ <assemblyIdentity version="0.1.0.0" name="com.wquguru.cicada"/>+ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">+ <application>+ <!-- Windows 10 and 11 -->+ <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>+ </application>+ </compatibility>+ <application xmlns="urn:schemas-microsoft-com:asm.v3">+ <windowsSettings>+ <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>+ </windowsSettings>+ </application>+</assembly>diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.csindex a4e6377..0e81f7e 100644--- a/windows/tests/Cicada.Tests/Program.cs+++ b/windows/tests/Cicada.Tests/Program.cs@@ -376,16 +376,16 @@ static class Testspublic static async Task ListenEngineEndToEndWithAFakeMing(){- // Two stretches of "speech"; the fake Ming answers the second faster than the first,- // and lines still come out in order.- int n = 0;+ // Two stretches of "speech", told apart by length (1 s, then 1.6 s); the fake Ming+ // answers the first one slower, and lines still come out in order.var fake = new Fake(body =>{if (body.Contains("Ming-3.0-audio-flash")){- int k = Interlocked.Increment(ref n);- if (k == 1) Thread.Sleep(400);- return Reply(k == 1 ? "LANG: en\nORIGINAL: First one.\nTRANSLATION: 第一句。" : "LANG: en\nORIGINAL: Second one.\nTRANSLATION: 第二句。");+ var url = JsonNode.Parse(body)!["messages"]![1]!["content"]![0]!["audio_url"]!["url"]!.GetValue<string>();+ bool first = url.Length < 60_000; // base64 of ~1.3 s at 32 kB/s, with lead-in and tail+ if (first) Thread.Sleep(400);+ return Reply(first ? "LANG: en\nORIGINAL: First one.\nTRANSLATION: 第一句。" : "LANG: en\nORIGINAL: Second one.\nTRANSLATION: 第二句。");}return Reply("{}");});@@ -398,7 +398,7 @@ static class Testsvar notes = new NotesEngine(ling, store);var engine = new ListenEngine(ling, new Translator(ling), store, notes, new AppSettings { Target = "zh-CN" });var path = Path.Combine(Path.GetTempPath(), $"cicada-e2e-{Environment.ProcessId}.wav");- File.WriteAllBytes(path, Wav.Bytes([.. Tone(1), .. Silence(1), .. Tone(1), .. Silence(1)]));+ File.WriteAllBytes(path, Wav.Bytes([.. Tone(1), .. Silence(1), .. Tone(1.6), .. Silence(1)]));var src = new FileAudioSource(path, speed: 0);var ended = new TaskCompletionSource();src.Ended += _ => ended.TrySetResult();