知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
feat: pick a speak-back voice per language, add app menus and diagnostics, clearer Chinese copy
wquguru2ffa1c722b04
diff --git a/Sources/LiveSubs/AISettings.swift b/Sources/LiveSubs/AISettings.swiftindex 0f4f307..0aa2cd2 100644--- a/Sources/LiveSubs/AISettings.swift+++ b/Sources/LiveSubs/AISettings.swift@@ -16,16 +16,13 @@ struct AISettingsView: View {.padding(.top, 4)SettingsCard {usageRow("实时纪要", tag: ling.usable ? "用 Ling" : "需要 key", on: ling.usable,- note: ling.usable ? "会中每 45 秒更新" : "填上 key 才有")+ note: ling.usable ? "会中每 45 秒更新" : "填好 key 后可用")usageRow("翻译", tag: ling.usable ? "用 Ling" : "Google", on: ling.usable,note: ling.usable ? "整句用 Ling;不行时换 Google、本机" : "没有 key 时照常可用")usageRow("语音识别", tag: "本机", on: false, note: "更快,不花钱")- SettingsRow(title: "我说话时的声音", detail: settings.speakVoice == "ming" ? "Ming 声音,首句约 1.3 秒出声" : "系统声音,不用 key", divider: false) {- PillMenu(value: settings.speakVoice == "ming" ? "Ming 声音" : "系统声音",- options: [("system", "系统声音")] + (ling.usable ? [("ming", "Ming 声音")] : [])) {- settings.speakVoice = $0- model.applyVoice()- }+ SettingsRow(title: "同声传译的声音", detail: ling.usable ? "Ming 的声音或你自己的声音" : "没有 key 时用本机声音",+ divider: false) {+ SoftButton("去选声音") { model.settingsSection = .speak }}}SettingsCard {@@ -33,7 +30,7 @@ struct AISettingsView: View {PillMenu(value: settings.aiModel, options: LingClient.models.map { ($0, $0) }) { settings.aiModel = $0 }}}- Text("一小时会议约 ¥0.15–1(目前优惠价)。发出去的只有文字,语音识别留在本机。")+ Text("一小时会议约 ¥0.15–1(目前优惠价)。发出去的只有文字(用你自己的声音时还有那段录音),语音识别留在本机。").font(.system(size: 12)).foregroundStyle(Palette.tertiary)}}@@ -83,7 +80,7 @@ struct AISettingsView: View {}HStack(spacing: 6) {Image(systemName: "lock").font(.system(size: 11)).foregroundStyle(Palette.tertiary)- Text("加密存在这台 Mac 的钥匙串里,只发给 Ling(ant-ling.com)")+ Text("只存在这台 Mac 上(只有你的账户能读),只发给 Ling(ant-ling.com)").font(.system(size: 11)).foregroundStyle(Palette.tertiary)Spacer()if ling.key != nil && !editing {@@ -126,9 +123,9 @@ struct AISettingsView: View {private var statusDetail: String? {switch ling.keyState {case .ok(let s): "\(settings.aiModel) · 响应约 \(String(format: "%.1f", s)) 秒"- case .invalid: "Ling 说这个令牌无效,检查是否复制完整,或新建一个"+ case .invalid: "Ling 提示此令牌无效,请检查是否复制完整,或重新创建一个"case .unreachable(let why): why- case .none: "没有 key 时,字幕和翻译照常可用"+ case .none: "不填 key 时,字幕和翻译仍可正常使用"default: nil}}diff --git a/Sources/LiveSubs/AppMenu.swift b/Sources/LiveSubs/AppMenu.swiftnew file mode 100644index 0000000..790dba8--- /dev/null+++ b/Sources/LiveSubs/AppMenu.swift@@ -0,0 +1,189 @@+import AppKit++/// The menus in the top-left of the screen. They show while any Live Subs window is in front+/// (the app is a regular app then); the Edit menu also makes ⌘C / ⌘V / ⌘A work in text fields.+@MainActor+final class AppMenu: NSObject, NSMenuItemValidation {+ private weak var model: AppModel?+ var showMainWindow: () -> Void = {}+ var showOnboarding: () -> Void = {}++ init(model: AppModel) {+ self.model = model+ super.init()+ }++ func install() {+ let name = DevBuild.isDev ? "Live Subs Dev" : "Live Subs"+ let main = NSMenu()++ let app = NSMenu(title: name)+ app.addItem(item("关于 \(name)", #selector(about)))+ app.addItem(.separator())+ app.addItem(item("设置…", #selector(openSettings), ","))+ app.addItem(item("AI 服务…", #selector(openAI)))+ app.addItem(.separator())+ app.addItem(item("隐藏 \(name)", #selector(NSApplication.hide(_:)), "h", target: NSApp))+ app.addItem(item("隐藏其他", #selector(NSApplication.hideOtherApplications(_:)), "h", [.command, .option], target: NSApp))+ app.addItem(item("全部显示", #selector(NSApplication.unhideAllApplications(_:)), target: NSApp))+ app.addItem(.separator())+ app.addItem(item("退出 \(name)", #selector(NSApplication.terminate(_:)), "q", target: NSApp))+ add(app, to: main)++ let notes = NSMenu(title: "纪要")+ notes.addItem(item("停止记录", #selector(toggleRecording), "r"))+ notes.addItem(item("立即更新纪要", #selector(updateNotes), "u"))+ notes.addItem(item("收起后的新内容", #selector(catchUp), "j"))+ notes.addItem(.separator())+ notes.addItem(item("复制纪要", #selector(copyNotes), "c", [.command, .shift]))+ let export = NSMenu(title: "导出")+ export.addItem(item("Markdown…", #selector(exportNotes(_:)), "e", tag: 0))+ export.addItem(item("Word…", #selector(exportNotes(_:)), tag: 1))+ export.addItem(item("SRT 字幕…", #selector(exportNotes(_:)), tag: 2))+ let exportItem = NSMenuItem(title: "导出", action: nil, keyEquivalent: "")+ exportItem.submenu = export+ notes.addItem(exportItem)+ notes.addItem(.separator())+ notes.addItem(item("会议记录", #selector(openRecords), "0"))+ add(notes, to: main)++ let display = NSMenu(title: "显示")+ display.addItem(item("实时纪要", #selector(setDisplay(_:)), tag: 0))+ display.addItem(item("字幕条", #selector(setDisplay(_:)), tag: 1))+ display.addItem(item("不显示", #selector(setDisplay(_:)), tag: 2))+ display.addItem(.separator())+ display.addItem(item("小卡", #selector(setSize(_:)), "1", tag: 0))+ display.addItem(item("侧栏", #selector(setSize(_:)), "2", tag: 1))+ display.addItem(item("纪要和原话并排", #selector(setSize(_:)), "3", tag: 2))+ display.addItem(.separator())+ display.addItem(item("始终置顶", #selector(toggleOnTop)))+ add(display, to: main)++ // Standard actions with no target go down the responder chain (text fields, selectable text).+ let edit = NSMenu(title: "编辑")+ edit.addItem(item("撤销", Selector(("undo:")), "z", chain: true))+ edit.addItem(item("重做", Selector(("redo:")), "z", [.command, .shift], chain: true))+ edit.addItem(.separator())+ edit.addItem(item("剪切", #selector(NSText.cut(_:)), "x", chain: true))+ edit.addItem(item("拷贝", #selector(NSText.copy(_:)), "c", chain: true))+ edit.addItem(item("粘贴", #selector(NSText.paste(_:)), "v", chain: true))+ edit.addItem(item("全选", #selector(NSText.selectAll(_:)), "a", chain: true))+ edit.addItem(.separator())+ edit.addItem(item("搜索文字记录", #selector(search), "f"))+ add(edit, to: main)++ let window = NSMenu(title: "窗口")+ window.addItem(item("最小化", #selector(NSWindow.performMiniaturize(_:)), "m", chain: true))+ window.addItem(item("关闭", #selector(NSWindow.performClose(_:)), "w", chain: true))+ window.addItem(.separator())+ window.addItem(item("实时纪要", #selector(openNotes)))+ window.addItem(item("会议记录", #selector(openRecords)))+ add(window, to: main)++ let help = NSMenu(title: "帮助")+ help.addItem(item("新手引导", #selector(onboarding)))+ add(help, to: main)++ NSApp.mainMenu = main+ NSApp.helpMenu = help+ }++ private func item(_ title: String, _ action: Selector, _ key: String = "",+ _ mods: NSEvent.ModifierFlags = .command, tag: Int = 0,+ target: AnyObject? = nil, chain: Bool = false) -> NSMenuItem {+ let i = NSMenuItem(title: title, action: action, keyEquivalent: key)+ i.keyEquivalentModifierMask = mods+ i.tag = tag+ i.target = chain ? nil : (target ?? self)+ return i+ }++ private func add(_ menu: NSMenu, to main: NSMenu) {+ let top = NSMenuItem(title: menu.title, action: nil, keyEquivalent: "")+ top.submenu = menu+ main.addItem(top)+ }++ // MARK: State++ func validateMenuItem(_ item: NSMenuItem) -> Bool {+ guard let model else { return false }+ let notesWindow = model.notesWindow+ let session = model.store.session(model.store.liveID ?? model.notes.shownID)+ switch item.action {+ case #selector(toggleRecording):+ item.title = model.running ? "停止记录" : "开始记录"+ return true+ case #selector(updateNotes):+ return model.store.liveID != nil && model.ling.hasKey && model.notes.state != .updating+ case #selector(catchUp):+ return notesWindow.isVisible && !model.notes.notes.isEmpty+ case #selector(copyNotes):+ return !model.notes.notes.isEmpty+ case #selector(exportNotes(_:)):+ return session.map { !$0.lines.isEmpty } ?? false+ case #selector(setDisplay(_:)):+ item.state = ["notes", "bar", "none"][item.tag] == model.settings.displayMode ? .on : .off+ return true+ case #selector(setSize(_:)):+ item.state = notesWindow.isVisible && notesWindow.layout == NotesWindowController.Layout.allCases[item.tag] ? .on : .off+ return true+ case #selector(toggleOnTop):+ item.state = notesWindow.onTop ? .on : .off+ return true+ case #selector(search):+ return notesWindow.isVisible+ default:+ return true+ }+ }++ // MARK: Actions++ @objc private func about() {+ NSApp.activate()+ NSApp.orderFrontStandardAboutPanel(nil)+ }++ @objc private func openSettings() { model?.openSettings() }+ @objc private func openAI() { model?.openSettings(.ai) }+ @objc private func openRecords() { showMainWindow() }+ @objc private func onboarding() { showOnboarding() }+ @objc private func openNotes() { model?.openNotesWindow() }++ @objc private func toggleRecording() {+ guard let model else { return }+ model.setRunning(!model.running)+ }++ @objc private func updateNotes() { model?.notes.updateNow() }++ @objc private func catchUp() { model?.notesWindow.send(.catchUp) }++ @objc private func copyNotes() {+ guard let model else { return }+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(TranscriptExport.notesMarkdown(model.notes.notes), forType: .string)+ }++ @objc private func exportNotes(_ sender: NSMenuItem) {+ guard let model, let s = model.store.session(model.store.liveID ?? model.notes.shownID) else { return }+ NSApp.activate()+ model.export(s, kind: ["md", "word", "srt"][sender.tag])+ }++ @objc private func setDisplay(_ sender: NSMenuItem) { model?.setDisplayMode(["notes", "bar", "none"][sender.tag]) }++ @objc private func setSize(_ sender: NSMenuItem) {+ guard let model else { return }+ model.openNotesWindow()+ model.notesWindow.send(.layout(NotesWindowController.Layout.allCases[sender.tag]))+ }++ @objc private func toggleOnTop() {+ guard let w = model?.notesWindow else { return }+ w.onTop.toggle()+ }++ @objc private func search() { model?.notesWindow.send(.search) }+}diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swiftindex 3a17a64..90b328a 100644--- a/Sources/LiveSubs/AppModel.swift+++ b/Sources/LiveSubs/AppModel.swift@@ -37,6 +37,7 @@ final class AppModel: ObservableObject {let installer = VirtualMicInstaller()let ling = LingClient()lazy var translator = TranslationService(ling: ling)+ let diagnostics = Diagnostics()lazy var notes = NotesEngine(ling: ling, store: store)lazy var notesWindow = NotesWindowController(model: self)let sample = SamplePlayer()@@ -68,6 +69,15 @@ final class AppModel: ObservableObject {self.store.setTranslation(lineID: line, text)}+ diagnostics.enabled = { [weak self] in self?.settings.diagnostics ?? false }+ diagnostics.folder = { [weak self] in+ guard let self, let id = self.store.liveID else { return nil }+ return self.store.folder(id)+ }+ listen.onTiming = { [weak self] in self?.diagnostics.record($0) }+ speak.onTiming = { [weak self] in self?.diagnostics.record($0) }+ ling.onCall = { [weak self] in self?.diagnostics.record($0) }+ling.model = { [weak self] in self?.settings.aiModel ?? "Ling-3.1-flash" }listen.translator = translatortranslator.glossary = { [weak self] in self?.notes.glossary ?? [] }@@ -84,11 +94,10 @@ final class AppModel: ObservableObject {}installer.onLoaded = { [weak self] in self?.virtualMicInstalled() }- speak.translate = { [weak self] text, from, to in- await self?.listen.translate(text, source: from, target: to, kind: .speak)+ speak.translate = { [weak self] text, from, to, trace in+ await self?.listen.translate(text, source: from, target: to, kind: .speak, trace: trace)}speak.roomLanguage = { [weak self] in self?.listen.activeLang?.code }- speak.mingVoice = nilapplyVoice()speak.onStatus = { [weak self] text in self?.status = text }speak.onLive = { [weak self] phase, src, dst in@@ -203,6 +212,8 @@ final class AppModel: ObservableObject {func openSettings(_ section: SettingsSection? = nil) {if let section { settingsSection = section }+ // The 诊断 tab only exists while its switch is on.+ if settingsSection == .diagnostics && !settings.diagnostics { settingsSection = .overlay }openSettingsWindow?()}@@ -224,6 +235,7 @@ final class AppModel: ObservableObject {func start() {guard !listen.isRunning else { return }let session = store.begin()+ diagnostics.begin()lineForSegment = [:]if settings.recordAudio {listen.router.setRecording(store.systemAudioURL(session.id))@@ -251,6 +263,13 @@ final class AppModel: ObservableObject {func setRunning(_ on: Bool) { on ? start() : stop() }+ /// The bottom-left 诊断 switch in settings: shows or hides the 诊断 tab.+ func setDiagnostics(_ on: Bool) {+ settings.diagnostics = on+ if !on && settingsSection == .diagnostics { settingsSection = .overlay }+ objectWillChange.send()+ }+// MARK: Display (live notes / subtitle bar / nothing)func setDisplayMode(_ mode: String) {@@ -381,10 +400,10 @@ final class AppModel: ObservableObject {/// Validates and saves a new shortcut. Returns why it was refused, or nil.func setShortcut(_ s: Shortcut, for role: ShortcutRole) -> String? {- if role == .toggle && s.isRightOption { return "右 ⌥ 只能用来按住说话" }+ if role == .toggle && s.isRightOption { return "右 ⌥ 只能用于“按住说话”" }if let p = s.typingProblem { return p }let other = role == .talk ? settings.toggleKey : settings.talkKey- if s == other { return "和另一个快捷键重复了" }+ if s == other { return "与另一个快捷键冲突" }if s.isSystemShortcut { return "\(s.display) 是系统快捷键,换一个吧" }if !s.isRightOption {// Probe: Carbon refuses a combo another app already registered.@@ -406,14 +425,60 @@ final class AppModel: ObservableObject {return nil}- /// Ming's voice when chosen and a key works; otherwise the system voice.+ /// The room hears the voice chosen for its language (looked up each time it speaks).func applyVoice() {- speak.mingVoice = settings.speakVoice == "ming" ? { [weak self] text in- guard let self, self.ling.usable else {- return AsyncThrowingStream { $0.finish(throwing: LingClient.Failure.noKey) }+ speak.route = { [weak self] language in+ guard let self else { return .system(nil) }+ return self.voiceRoute(id: self.voiceID(for: language), language: language)+ }+ }++ /// The chosen voice for a language, or its default (Ming's first with a key, else the Mac's).+ func voiceID(for language: String) -> String? {+ if let id = settings.speakVoices[VoiceCatalog.key(for: language)] {+ if id == "clone" && !VoiceReference.exists { return VoiceCatalog.defaultID(for: language, hasKey: ling.usable) }+ return id+ }+ return VoiceCatalog.defaultID(for: language, hasKey: ling.usable)+ }++ func setVoice(_ id: String, for language: String) {+ settings.speakVoices[VoiceCatalog.key(for: language)] = id+ }++ /// Ming's voices need a working key; without one the Mac's voice speaks.+ func voiceRoute(id: String?, language: String) -> SpeakEngine.VoiceRoute {+ guard let id else { return .system(nil) }+ if id.hasPrefix("system:") { return .system(String(id.dropFirst("system:".count))) }+ guard ling.usable else { return .system(nil) }+ let lang = VoiceCatalog.mingLanguage(for: language)+ if id == "clone" {+ guard let ref = VoiceReference.reference() else { return .system(nil) }+ return .stream { [weak self] text in+ self?.ling.speech(text, voice: nil, reference: ref, language: lang)+ ?? AsyncThrowingStream { $0.finish(throwing: LingClient.Failure.noKey) }}- return self.ling.speech(text)- } : nil+ }+ let voice = String(id.dropFirst("ming:".count))+ return .stream { [weak self] text in+ self?.ling.speech(text, voice: voice, language: lang)+ ?? AsyncThrowingStream { $0.finish(throwing: LingClient.Failure.noKey) }+ }+ }++ /// Plays a voice on the speakers (not into the room) with a line in that language.+ @Published var previewing: String?++ func previewVoice(_ id: String, language: String, text: String? = nil) {+ previewing = id+ let route = voiceRoute(id: id, language: language)+ Task {+ let started = Date()+ await speak.speak(text ?? VoiceCatalog.sample(for: language), language: language,+ device: AudioDevices.defaultOutput, route: route)+ debugLog("voice preview \(id) \(language) took \(String(format: "%.1f", Date().timeIntervalSince(started))) s")+ if previewing == id { previewing = nil }+ }}func speakFromChanged() {@@ -501,6 +566,11 @@ final class AppModel: ObservableObject {case "settings":settingsSection = SettingsSection(rawValue: arg) ?? settingsSectionopenSettings(settingsSection)+ case "diagnostics":+ setDiagnostics(arg != "off")+ debugLog("diagnostics \(settings.diagnostics ? "on" : "off")")+ case "diagReport":+ debugLog("diag report:\n" + diagnostics.report(version: "", model: settings.aiModel))case "micTest": installer.runTest()case "micNext": installer.next()case "talkKey", "toggleKey":@@ -514,21 +584,39 @@ final class AppModel: ObservableObject {if let k = try? String(contentsOfFile: arg, encoding: .utf8) { Task { await ling.setKey(k) } }case "aiCheck": Task { await ling.check() }case "voice":- settings.speakVoice = arg == "ming" ? "ming" : "system"- applyVoice()+ // voice:<lang>=<id> chooses ("voice:en=ming:UK_George", "voice:zh=clone"); voice:<lang> logs the choice.+ let kv = arg.split(separator: "=", maxSplits: 1).map(String.init)+ if kv.count == 2 { setVoice(kv[1], for: kv[0]) }+ debugLog("voice \(kv[0]) → \(voiceID(for: kv[0]) ?? "none") options=\(VoiceCatalog.options(for: kv[0]).map(\.id)) clone=\(VoiceReference.exists)")+ case "voiceCloneFile":+ // voiceCloneFile:<wav> uses a recording as "my voice", transcribing it like the sheet does.+ Task {+ let url = URL(fileURLWithPath: arg)+ guard let f = try? AVAudioFile(forReading: url),+ let buf = AVAudioPCMBuffer(pcmFormat: f.processingFormat, frameCapacity: AVAudioFrameCount(f.length)),+ (try? f.read(into: buf)) != nil else { debugLog("voiceCloneFile: unreadable"); return }+ let text = await LoopbackTest.transcribe([buf], locale: settings.speakFromLang.locale)+ do { try VoiceReference.save(wav: url, text: text) } catch { debugLog("voiceCloneFile: \(error)") }+ debugLog("voiceCloneFile: saved, transcript \(text.count) chars")+ }+ case "voicePreview":+ // voicePreview:<lang>=<id>+ let kv = arg.split(separator: "=", maxSplits: 1).map(String.init)+ if kv.count == 2 { previewVoice(kv[1], language: kv[0]) }case "notesNow": notes.updateNow()case "display": setDisplayMode(arg)case "notesWindow":let v = arg.split(separator: ",").compactMap { Double($0) }openNotesWindow()if v.count == 4 { notesWindow.place(NSRect(x: v[0], y: v[1], width: v[2], height: v[3])) }- case "notesFrame": debugLog("notes window frame=\(String(describing: notesWindow.frame)) visible=\(notesWindow.isVisible)")+ case "notesFrame": debugLog("notes window frame=\(String(describing: notesWindow.frame)) visible=\(notesWindow.isVisible) policy=\(NSApp.activationPolicy() == .regular ? "regular" : "accessory")")case "notesReplay": Task { await notes.replay(arg) }case "notesShow": notes.show(arg)case "notesCapturable": notesWindow.setCapturable(arg != "off")case "notesRender":// The whole notes column as a PNG, for checking what is below the fold.- let view = NotesContentView(notes: notes.notes, fresh: notes.fresh, live: store.liveID != nil)+ let view = NotesContentView(notes: notes.notes, fresh: notes.fresh, live: store.liveID != nil,+ updating: notes.state == .updating).padding(24).frame(width: 460).background(Color.white)let r = ImageRenderer(content: view)r.scale = 2@@ -536,7 +624,7 @@ final class AppModel: ObservableObject {let png = rep.representation(using: .png, properties: [:]) {try? png.write(to: URL(fileURLWithPath: arg))}- case "notesState": debugLog("notes state=\(notes.state) topics=\(notes.notes.topics.count) covered=\(notes.notes.covered) glossary=\(notes.glossary.count)")+ case "notesState": debugLog("notes state=\(notes.state) topics=\(notes.notes.topics.count) covered=\(notes.notes.covered) glossary=\(notes.glossary.count) timedPoints=\(notes.notes.topics.reduce(0) { $0 + ($1.pointTimes?.compactMap { $0 }.count ?? 0) })/\(notes.notes.topics.reduce(0) { $0 + $1.points.count }) fresh=\(notes.fresh.count)")case "lingSimulate":ling.simulate = ["429": .rateLimited, "hijack": .hijacked, "timeout": .timeout][arg]debugLog("ling simulate=\(String(describing: ling.simulate))")@@ -581,9 +669,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {private var settingsWindow: NSWindow?private var pollTimer: Timer?private var runningObserver: Any?+ private lazy var menu = AppMenu(model: model)func applicationDidFinishLaunching(_ notification: Notification) {NSApp.setActivationPolicy(.accessory)+ menu.showMainWindow = { [weak self] in self?.showMainWindow() }+ menu.showOnboarding = { [weak self] in self?.showOnboarding() }+ menu.install()+ model.notesWindow.onVisibilityChange = { [weak self] in self?.updateActivationPolicy() }setupStatusItem()model.openMainWindow = { [weak self] in self?.showMainWindow() }model.openSettingsWindow = { [weak self] in self?.showSettingsWindow() }@@ -728,8 +821,19 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {model.sample.stop()UserDefaults.standard.set(true, forKey: "onboarded")}- let otherOpen = [mainWindow, onboardingWindow, settingsWindow].contains { $0 != nil && $0 != w && $0!.isVisible }- if !otherOpen { NSApp.setActivationPolicy(.accessory) }+ updateActivationPolicy(closing: w)+ }++ /// A regular app (name and menus top left, Dock icon, ⌘Tab) while any of its windows is+ /// open, the notes window included; only the menu bar item otherwise. Never activates: the+ /// notes window appearing must not take focus from the meeting app.+ func updateActivationPolicy(closing: NSWindow? = nil) {+ let open = [mainWindow, onboardingWindow, settingsWindow].contains { $0 != nil && $0 != closing && $0!.isVisible }+ || model.notesWindow.isVisible+ let policy: NSApplication.ActivationPolicy = open ? .regular : .accessory+ guard NSApp.activationPolicy() != policy else { return }+ NSApp.setActivationPolicy(policy)+ debugLog("activation policy → \(open ? "regular" : "accessory")")}// MARK: Output device changes@@ -775,6 +879,9 @@ struct LiveSubsMain {exit(1)}}+ // AppKit adds "进入全屏幕" to a menu titled 显示 (View) unless told before launch;+ // no Live Subs window goes full screen.+ UserDefaults.standard.register(defaults: ["NSFullScreenMenuItemEverywhere": false])MainActor.assumeIsolated {let app = NSApplication.sharedlet delegate = AppDelegate()diff --git a/Sources/LiveSubs/AudioRouter.swift b/Sources/LiveSubs/AudioRouter.swiftindex 14d28e2..0759087 100644--- a/Sources/LiveSubs/AudioRouter.swift+++ b/Sources/LiveSubs/AudioRouter.swift@@ -89,6 +89,7 @@ final class AudioRouter: @unchecked Sendable {guard let format, let converted = converter.convert(mono, to: format) else { return }continuation?.yield(AnalyzerInput(buffer: converted))+ if continuation != nil { fed += seconds }record(converted)ring.append((converted, seconds, voiced))ringSeconds += seconds@@ -116,8 +117,14 @@ final class AudioRouter: @unchecked Sendable {try? recorder?.write(from: buffer)}+ /// Seconds of audio given to the current analyzer, replay included: the analyzer's clock. A+ /// result ending at t was spoken (fed − t) seconds ago, since the tap runs in real time.+ private var fed = 0.0+ func fedSeconds() -> Double { queue.sync { fed } }+func attach(format: AVAudioFormat, continuation: AsyncStream<AnalyzerInput>.Continuation, replaySeconds: Double = 0) {queue.sync {+ fed = 0if self.format != format {ring.removeAll()ringSeconds = 0@@ -130,6 +137,7 @@ final class AudioRouter: @unchecked Sendable {replay.append(item.buffer)}for buffer in replay.reversed() { continuation.yield(AnalyzerInput(buffer: buffer)) }+ fed = acc}self.format = formatself.continuation?.finish()diff --git a/Sources/LiveSubs/Diagnostics.swift b/Sources/LiveSubs/Diagnostics.swiftnew file mode 100644index 0000000..8d33a38--- /dev/null+++ b/Sources/LiveSubs/Diagnostics.swift@@ -0,0 +1,378 @@+import AppKit+import SwiftUI++// MARK: - Records++/// One provider tried for one translation, and why it fell through.+struct TranslateAttempt: Codable {+ let provider: String // ling / google / apple+ let seconds: Double+ let failure: String? // nil = this one answered+}++/// Filled in by `TranslationService` as it walks Ling → Google → Apple.+@MainActor+final class TranslateTrace {+ var attempts: [TranslateAttempt] = []+ var lingQueue: Double = 0+ var failedSeconds: Double { attempts.filter { $0.failure != nil }.reduce(0) { $0 + $1.seconds } }+ var via: String { attempts.first(where: { $0.failure == nil })?.provider ?? "none" }+ var fallbacks: [String] { attempts.compactMap { a in a.failure.map { "\(a.provider):\($0)" } } }+}++/// Timings for one sentence, heard ("them") or said ("me"). Never the text itself.+struct SentenceTiming: Codable, Identifiable {+ var id = UUID()+ let at: Date+ let side: String+ let chars: Int+ /// them: last word spoken → final transcript (audio clock); me: key released → transcript.+ let recognize: Double?+ /// Waiting at Ling's start gate (part of `translate`).+ let queue: Double+ /// Final transcript → translation, the whole chain.+ let translate: Double+ /// me: translation → the voice finished.+ let voice: Double?+ /// Time spent on providers that failed before the one that answered (part of `translate`).+ let failed: Double+ let via: String+ let fallbacks: [String]+ var total: Double { (recognize ?? 0) + translate }+}++/// One Ling request.+struct LingCall: Codable {+ let at: Date+ let priority: String+ let queue: Double+ let seconds: Double+ let outcome: String // ok / rateLimited / hijacked / timeout / …+ let promptTokens: Int+ let completionTokens: Int+}++// MARK: - Recorder++/// Keeps the current meeting's timings in memory and appends them to `metrics.jsonl` in the meeting+/// folder. UI-free; everything is on the main actor like the engines that report into it.+@MainActor+final class Diagnostics: ObservableObject {+ @Published private(set) var sentences: [SentenceTiming] = []+ @Published private(set) var calls: [LingCall] = []+ @Published private(set) var startedAt: Date?++ var enabled: () -> Bool = { false }+ /// The live meeting's folder, nil when not listening.+ var folder: () -> URL? = { nil }++ func begin() {+ sentences = []+ calls = []+ startedAt = Date()+ }++ func record(_ s: SentenceTiming) {+ guard enabled() else { return }+ sentences.append(s)+ if sentences.count > 500 { sentences.removeFirst(sentences.count - 500) }+ write("sentence", s)+ debugLog(String(format: "diag: %@ recognize=%@ translate=%.2f queue=%.2f via=%@%@", s.side,+ s.recognize.map { String(format: "%.2f", $0) } ?? "-", s.translate, s.queue, s.via,+ s.fallbacks.isEmpty ? "" : " fallbacks=" + s.fallbacks.joined(separator: ",")))+ }++ func record(_ c: LingCall) {+ guard enabled() else { return }+ calls.append(c)+ if calls.count > 1000 { calls.removeFirst(calls.count - 1000) }+ write("ling", c)+ }++ private func write<T: Encodable>(_ type: String, _ value: T) {+ guard let dir = folder() else { return }+ let enc = JSONEncoder()+ enc.dateEncodingStrategy = .iso8601+ guard let data = try? enc.encode(value), var obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return }+ obj["type"] = type+ obj.removeValue(forKey: "id")+ guard var line = try? JSONSerialization.data(withJSONObject: obj, options: [.sortedKeys]) else { return }+ line.append(0x0A)+ let url = dir.appendingPathComponent("metrics.jsonl")+ if let h = try? FileHandle(forWritingTo: url) {+ h.seekToEndOfFile()+ h.write(line)+ try? h.close()+ } else {+ try? line.write(to: url)+ }+ }++ // MARK: Summary++ struct Stat { let p50: Double; let p95: Double; let n: Int }++ static func stat(_ xs: [Double]) -> Stat? {+ guard !xs.isEmpty else { return nil }+ let s = xs.sorted()+ let pick = { (q: Double) in s[min(s.count - 1, Int((q * Double(s.count - 1)).rounded()))] }+ return Stat(p50: pick(0.5), p95: pick(0.95), n: s.count)+ }++ var heard: [SentenceTiming] { sentences.filter { $0.side == "them" } }+ var said: [SentenceTiming] { sentences.filter { $0.side == "me" } }+ var endToEnd: Stat? { Self.stat(heard.map(\.total)) }+ var recognize: Stat? { Self.stat(heard.compactMap(\.recognize)) }+ var translate: Stat? { Self.stat(heard.map(\.translate)) }+ var speakBack: Stat? { Self.stat(said.map { ($0.recognize ?? 0) + $0.translate }) }+ var notesRounds: Stat? { Self.stat(calls.filter { $0.priority == "notes" && $0.outcome == "ok" }.map(\.seconds)) }++ /// How many sentences each provider answered, most first.+ var viaCounts: [(String, Int, Double)] {+ Dictionary(grouping: sentences, by: \.via).map { via, xs in+ (via, xs.count, Self.stat(xs.map(\.translate))?.p50 ?? 0)+ }.sorted { $0.1 > $1.1 }+ }++ /// Why Ling (or Google) was passed over: hijacked, rateLimited, timeout…+ var fallbackCounts: [(String, Int)] {+ var counts: [String: Int] = [:]+ for s in sentences { for f in s.fallbacks { counts[f, default: 0] += 1 } }+ for c in calls where c.outcome == "rateLimited" && c.priority == "notes" { counts["notes:rateLimited", default: 0] += 1 }+ return counts.sorted { $0.value > $1.value }.map { ($0.key, $0.value) }+ }++ /// Ling requests started in the last 10 s, per second (the account allows about 2).+ var lingRate: Double {+ let since = Date().addingTimeInterval(-10)+ return Double(calls.filter { $0.at > since }.count) / 10+ }+ var maxQueue: Double { calls.map(\.queue).max() ?? 0 }+ var tokens: (Int, Int) { calls.reduce((0, 0)) { ($0.0 + $1.promptTokens, $0.1 + $1.completionTokens) } }++ /// Plain text for "复制诊断信息": numbers only, safe to paste anywhere.+ func report(version: String, model: String) -> String {+ func f(_ s: Stat?) -> String { s.map { String(format: "p50 %.2fs p95 %.2fs n=%d", $0.p50, $0.p95, $0.n) } ?? "-" }+ var lines = ["Live Subs \(version) 诊断 \(Date())", "模型 \(model)"]+ if let startedAt { lines.append(String(format: "本场 %.0f 分钟", Date().timeIntervalSince(startedAt) / 60)) }+ lines.append("说完到出字幕 " + f(endToEnd))+ lines.append("识别定稿 " + f(recognize))+ lines.append("翻译 " + f(translate))+ lines.append("同声传译(松开到译好)" + f(speakBack))+ lines.append("单轮纪要耗时 " + f(notesRounds))+ lines.append("翻译来源 " + viaCounts.map { String(format: "%@ %d (p50 %.2fs)", $0.0, $0.1, $0.2) }.joined(separator: " · "))+ lines.append("换后备 " + (fallbackCounts.isEmpty ? "无" : fallbackCounts.map { "\($0.0) \($0.1)" }.joined(separator: " · ")))+ let t = tokens+ lines.append(String(format: "Ling 请求 %d 次 · 排队最久 %.2fs · token %d/%d", calls.count, maxQueue, t.0, t.1))+ return lines.joined(separator: "\n")+ }+}++// MARK: - View (settings › 诊断)++struct DiagnosticsView: View {+ @ObservedObject var diagnostics: Diagnostics+ var model: String = ""+ @State private var copied = false+ @State private var tick = Date()+ private let timer = Timer.publish(every: 2, on: .main, in: .common).autoconnect()++ var body: some View {+ VStack(alignment: .leading, spacing: 14) {+ Text(subtitle).font(.system(size: 12)).foregroundStyle(Palette.secondary).padding(.top, -8)+ HStack(spacing: 8) {+ tile("说完到上屏", diagnostics.endToEnd, dark: true)+ tile("识别定稿", diagnostics.recognize)+ tile("翻译", diagnostics.translate)+ tile("纪要一轮", diagnostics.notesRounds)+ }+ providers+ lingCard+ recent+ HStack(spacing: 8) {+ SoftButton(copied ? "已复制" : "复制诊断信息", dark: true) { copy() }+ // The meeting folder holds metrics.jsonl; the log only exists in dev builds or with `debug` on.+ SoftButton(diagnostics.folder() == nil ? "打开日志" : "打开本场数据") {+ NSWorkspace.shared.open(diagnostics.folder() ?? URL(fileURLWithPath: DevBuild.logPath))+ }+ Spacer()+ Text("只记时间和次数,不存字幕原文").font(.system(size: 11)).foregroundStyle(Palette.tertiary)+ }+ }+ .onReceive(timer) { tick = $0 }+ }++ private var subtitle: String {+ guard let s = diagnostics.startedAt else { return "开始聆听后,这里会显示每句话的耗时明细" }+ let m = Int(tick.timeIntervalSince(s) / 60)+ return "这场会议 · \(m) 分钟 · \(diagnostics.heard.count) 句 · 同声传译 \(diagnostics.said.count) 次"+ }++ private func tile(_ title: String, _ s: Diagnostics.Stat?, dark: Bool = false) -> some View {+ VStack(alignment: .leading, spacing: 4) {+ Text(title).font(.system(size: 11)).foregroundStyle(dark ? Color.white.opacity(0.75) : Palette.secondary)+ Text(s.map { String(format: "%.1fs", $0.p50) } ?? "—").font(.system(size: 20, weight: .bold).monospacedDigit())+ .foregroundStyle(dark ? Color.white : Palette.ink)+ Text(s.map { String(format: "p95 %.1fs · %d", $0.p95, $0.n) } ?? "暂无数据")+ .font(.system(size: 11).monospacedDigit()).foregroundStyle(dark ? Color.white.opacity(0.75) : Palette.tertiary)+ }+ .padding(12).frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 12).fill(dark ? Palette.ink : Color.white))+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(dark ? .clear : Palette.line, lineWidth: 1))+ }++ private static func color(_ via: String) -> Color {+ switch via {+ case "ling": Palette.ink+ case "google": Palette.accent+ default: Color(red: 0.72, green: 0.74, blue: 0.78)+ }+ }++ private static func name(_ via: String) -> String {+ switch via {+ case "ling": "Ling"+ case "google": "Google"+ case "apple": "本机"+ default: "没译出"+ }+ }++ private static func reason(_ key: String) -> String {+ let parts = key.split(separator: ":").map(String.init)+ let who = parts.first.map { $0 == "ling" ? "Ling" : $0 == "google" ? "Google" : $0 == "notes" ? "纪要" : "本机" } ?? ""+ let why: String+ switch parts.last ?? "" {+ case "hijacked": why = "被搜索劫持"+ case "rateLimited", "429": why = "限流"+ case "timeout": why = "超时"+ case "network": why = "网络错误"+ case "unavailable": why = "未安装语言包"+ default: why = parts.last ?? ""+ }+ return "\(who) \(why)"+ }++ private var providers: some View {+ let counts = diagnostics.viaCounts+ let total = max(1, counts.reduce(0) { $0 + $1.1 })+ return VStack(alignment: .leading, spacing: 10) {+ HStack {+ Text("翻译通道分布").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)+ Spacer()+ Text("共 \(diagnostics.sentences.count) 句").font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ }+ GeometryReader { geo in+ HStack(spacing: 2) {+ ForEach(counts, id: \.0) { c in+ Rectangle().fill(Self.color(c.0)).frame(width: max(2, geo.size.width * CGFloat(c.1) / CGFloat(total) - 2))+ }+ if counts.isEmpty { Rectangle().fill(Palette.fill) }+ }+ .clipShape(RoundedRectangle(cornerRadius: 5))+ }+ .frame(height: 10)+ HStack(spacing: 14) {+ ForEach(counts, id: \.0) { c in+ HStack(spacing: 6) {+ RoundedRectangle(cornerRadius: 2).fill(Self.color(c.0)).frame(width: 8, height: 8)+ Text(String(format: "%@ %d · %.1fs", Self.name(c.0), c.1, c.2)).font(.system(size: 12).monospacedDigit())+ .foregroundStyle(Palette.secondary)+ }+ }+ }+ if !diagnostics.fallbackCounts.isEmpty {+ HStack(spacing: 6) {+ ForEach(diagnostics.fallbackCounts.prefix(4), id: \.0) { f in+ Text("\(Self.reason(f.0)) \(f.1)").font(.system(size: 12))+ .foregroundStyle(f.0.hasSuffix("hijacked") ? Palette.accentInk : Palette.secondary)+ .padding(.horizontal, 8).padding(.vertical, 3)+ .background(RoundedRectangle(cornerRadius: 6).fill(f.0.hasSuffix("hijacked") ? Palette.accentPale : Palette.fill))+ }+ }+ }+ }+ .padding(14)+ .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))+ }++ private var lingCard: some View {+ let _ = tick+ let t = diagnostics.tokens+ return SettingsCard {+ SettingsRow(title: "Ling 请求速度", detail: "账号上限约每秒 2 次") {+ Text(String(format: "%.1f / 2 次每秒", diagnostics.lingRate)).font(.system(size: 12).monospacedDigit())+ .foregroundStyle(Palette.secondary)+ }+ SettingsRow(title: "排队最久") {+ Text(String(format: "%.1fs", diagnostics.maxQueue)).font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.secondary)+ }+ SettingsRow(title: "本场用量", divider: false) {+ Text("\(diagnostics.calls.count) 次 · \(t.0 + t.1) token").font(.system(size: 12).monospacedDigit())+ .foregroundStyle(Palette.secondary)+ }+ }+ }++ /// The last few sentences as stacked bars: recognise · queue · translate (· voice).+ private var recent: some View {+ let rows = Array(diagnostics.sentences.suffix(6).reversed())+ return VStack(alignment: .leading, spacing: 0) {+ Text("最近的句子").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink).padding(.bottom, 8)+ if rows.isEmpty {+ Text("还没有").font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ }+ ForEach(rows) { s in+ HStack(spacing: 10) {+ VStack(alignment: .leading, spacing: 1) {+ Text("\(Self.clock.string(from: s.at)) \(s.side == "me" ? "你" : "对方")").font(.system(size: 12).monospacedDigit())+ Text(s.fallbacks.isEmpty ? "\(Self.name(s.via)) · \(s.chars) 字" : s.fallbacks.map(Self.reason).joined(separator: "、") + " → " + Self.name(s.via))+ .font(.system(size: 10)).foregroundStyle(s.fallbacks.isEmpty ? Palette.tertiary : Palette.accentInk).lineLimit(1)+ }+ .frame(width: 150, alignment: .leading)+ bar(s)+ Spacer(minLength: 0)+ Text(String(format: "%.1fs", s.total + (s.voice ?? 0))).font(.system(size: 12, weight: .semibold).monospacedDigit())+ }+ .frame(height: 34)+ }+ }+ .padding(14)+ .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))+ }++ private func bar(_ s: SentenceTiming) -> some View {+ let scale: CGFloat = 50 // points per second; 4 s ≈ 200 pt+ let fallback = s.failed+ return HStack(spacing: 1) {+ if let r = s.recognize { seg(r, Color(red: 0.42, green: 0.44, blue: 0.50), scale) }+ if s.queue > 0.05 { seg(s.queue, Color(red: 0.96, green: 0.78, blue: 0.71), scale) }+ if fallback > 0.05 { seg(fallback, Palette.accent, scale) }+ seg(max(0.02, s.translate - s.queue - fallback), Palette.ink, scale)+ if let v = s.voice { seg(v, Color(red: 0.60, green: 0.63, blue: 0.67), scale) }+ }+ .frame(width: 200, alignment: .leading).clipped()+ }++ private func seg(_ seconds: Double, _ color: Color, _ scale: CGFloat) -> some View {+ RoundedRectangle(cornerRadius: 2).fill(color).frame(width: max(2, CGFloat(seconds) * scale), height: 10)+ }++ private static let clock: DateFormatter = {+ let f = DateFormatter()+ f.dateFormat = "HH:mm:ss"+ return f+ }()++ private func copy() {+ let text = diagnostics.report(version: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "",+ model: model)+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(text, forType: .string)+ copied = true+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { copied = false }+ }+}+diff --git a/Sources/LiveSubs/Ling.swift b/Sources/LiveSubs/Ling.swiftindex b63ea9c..22419c1 100644--- a/Sources/LiveSubs/Ling.swift+++ b/Sources/LiveSubs/Ling.swift@@ -1,60 +1,104 @@import Foundationimport Security-// MARK: - API key (Keychain)+// MARK: - API key (local file)-/// The user's Ling API key, kept in the login Keychain (encrypted by the system, readable only by-/// this app's code signature). Never written to UserDefaults, logs or exports.+/// The user's Ling API key, in a file only this user can read (0600, folder 0700) under+/// Application Support, left out of backups. Never written to UserDefaults, logs or exports.+///+/// Not the Keychain for now: the app is signed ad hoc, so the Keychain only trusts one exact build+/// (its cdhash) and asks for the login password after every rebuild or update. Back to the Keychain+/// once builds are signed with a Developer ID (a stable team id). Keys saved there by earlier+/// builds are moved over once.enum AIKey {- /// Dev and release builds keep separate keys, like their other settings.- private static var service: String { (Bundle.main.bundleIdentifier ?? "com.wquguru.cicada.swiftrun") + ".ai" }- private static let account = "ling"private static var cached: String??+ private static var folder: URL {+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+ .appendingPathComponent(DevBuild.supportFolder)+ }+ private static var file: URL { folder.appendingPathComponent("ling-api-key") }+static func read() -> String? {if let cached { return cached }- let query: [String: Any] = [- kSecClass as String: kSecClassGenericPassword,- kSecAttrService as String: service,- kSecAttrAccount as String: account,- kSecReturnData as String: true,- kSecMatchLimit as String: kSecMatchLimitOne,- ]- var out: AnyObject?- let status = SecItemCopyMatching(query as CFDictionary, &out)- let value = status == errSecSuccess ? (out as? Data).flatMap { String(data: $0, encoding: .utf8) } : nil- if status != errSecSuccess && status != errSecItemNotFound { debugLog("keychain read failed: \(status)") }+ var value = (try? String(contentsOf: file, encoding: .utf8))?.trimmingCharacters(in: .whitespacesAndNewlines)+ if value?.isEmpty ?? true { value = nil }+ if value == nil, let old = LegacyKeychain.take() {+ // One last Keychain prompt, then the key lives in the file.+ value = old+ write(old)+ }cached = .some(value)return value}@discardableResultstatic func save(_ key: String) -> Bool {- remove()- let item: [String: Any] = [- kSecClass as String: kSecClassGenericPassword,- kSecAttrService as String: service,- kSecAttrAccount as String: account,- kSecAttrLabel as String: "Live Subs · Ling API key",- kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,- kSecValueData as String: Data(key.utf8),- ]- let status = SecItemAdd(item as CFDictionary, nil)- if status != errSecSuccess { debugLog("keychain save failed: \(status)") }- cached = .some(status == errSecSuccess ? key : nil)- return status == errSecSuccess+ let ok = write(key)+ cached = .some(ok ? key : nil)+ return ok}static func remove() {- let query: [String: Any] = [- kSecClass as String: kSecClassGenericPassword,- kSecAttrService as String: service,- kSecAttrAccount as String: account,- ]- SecItemDelete(query as CFDictionary)+ try? FileManager.default.removeItem(at: file)+ LegacyKeychain.delete()cached = .some(nil)}+ @discardableResult+ private static func write(_ key: String) -> Bool {+ let fm = FileManager.default+ do {+ try fm.createDirectory(at: folder, withIntermediateDirectories: true)+ try fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: folder.path)+ // Create it 0600 before the key goes in, so it is never readable by others.+ if !fm.fileExists(atPath: file.path) {+ guard fm.createFile(atPath: file.path, contents: nil, attributes: [.posixPermissions: 0o600]) else {+ debugLog("ai key: could not create the key file")+ return false+ }+ }+ try fm.setAttributes([.posixPermissions: 0o600], ofItemAtPath: file.path)+ try Data(key.utf8).write(to: file)+ var url = file+ var values = URLResourceValues()+ values.isExcludedFromBackup = true+ try? url.setResourceValues(values)+ return true+ } catch {+ debugLog("ai key: save failed \(error.localizedDescription)")+ return false+ }+ }++ /// Where builds before the file kept the key: login Keychain, service = bundle id + ".ai".+ private enum LegacyKeychain {+ private static var query: [String: Any] {+ [kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: (Bundle.main.bundleIdentifier ?? "com.wquguru.cicada.swiftrun") + ".ai",+ kSecAttrAccount as String: "ling"]+ }++ /// The old key, removed from the Keychain once read.+ static func take() -> String? {+ // Skip the Keychain entirely when there was never an item (no prompt for new users).+ var exists = query+ exists[kSecReturnAttributes as String] = true+ guard SecItemCopyMatching(exists as CFDictionary, nil) == errSecSuccess else { return nil }+ var q = query+ q[kSecReturnData as String] = true+ q[kSecMatchLimit as String] = kSecMatchLimitOne+ var out: AnyObject?+ guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess,+ let key = (out as? Data).flatMap({ String(data: $0, encoding: .utf8) }), !key.isEmpty else { return nil }+ delete()+ debugLog("ai key: moved from the Keychain to the key file")+ return key+ }++ static func delete() { SecItemDelete(query as CFDictionary) }+ }+/// "sk-…3f9a" for display.static func masked(_ key: String) -> String {guard key.count > 8 else { return "sk-…" }@@ -157,7 +201,8 @@ final class LingClient: ObservableObject {/// message. Notes retry 429s with backoff; translation and speak-back fail fast so the caller/// can fall back to another translator.func chat(content: String, instruction: String, priority: Priority, json: Bool = false,- maxTokens: Int = 1024, timeout: TimeInterval = 30, model: String? = nil) async throws -> String {+ maxTokens: Int = 1024, timeout: TimeInterval = 30, model: String? = nil,+ onQueued: ((Double) -> Void)? = nil) async throws -> String {guard let key else { throw Failure.noKey }guard keyState != .invalid else { throw Failure.invalidKey }if let simulate {@@ -179,7 +224,10 @@ final class LingClient: ObservableObject {let attempts = priority == .notes ? 4 : 1var delay = 1.0for attempt in 1...attempts {+ let asked = Date()await acquire(priority)+ let queued = Date().timeIntervalSince(asked)+ onQueued?(queued)let started = Date()do {let root = try await post("chat/completions", body: body, key: key, timeout: timeout)@@ -195,25 +243,48 @@ final class LingClient: ObservableObject {let ms = Int(Date().timeIntervalSince(started) * 1000)let usage = root["usage"] as? [String: Any]debugLog("ling: \(priority) ok \(ms) ms tokens=\(usage?["prompt_tokens"] ?? "?")/\(usage?["completion_tokens"] ?? "?")")+ report(priority, at: started, queued: queued, outcome: "ok",+ tokens: (usage?["prompt_tokens"] as? Int ?? 0, usage?["completion_tokens"] as? Int ?? 0))if rateLimitedAt != nil { rateLimitedAt = nil }return trimmed- } catch Failure.rateLimited where attempt < attempts {+ } catch let failure as Failure {+ report(priority, at: started, queued: queued, outcome: Self.name(failure))+ guard failure == .rateLimited else { throw failure }+ guard attempt < attempts else {+ rateLimitedAt = Date()+ throw failure+ }let wait = delay + Double.random(in: 0...0.5)debugLog("ling: \(priority) 429, retry in \(String(format: "%.1f", wait)) s")try? await Task.sleep(nanoseconds: UInt64(wait * 1_000_000_000))delay *= 2- } catch Failure.rateLimited {- rateLimitedAt = Date()- throw Failure.rateLimited}}throw Failure.rateLimited}+ /// Every request, for diagnostics (timings and token counts only).+ var onCall: ((LingCall) -> Void)?++ private func report(_ priority: Priority, at started: Date, queued: Double, outcome: String, tokens: (Int, Int) = (0, 0)) {+ onCall?(LingCall(at: started, priority: "\(priority)", queue: queued, seconds: Date().timeIntervalSince(started),+ outcome: outcome, promptTokens: tokens.0, completionTokens: tokens.1))+ }++ static func name(_ failure: Failure) -> String {+ switch failure {+ case .http(let code): "http\(code)"+ default: "\(failure)"+ }+ }+// MARK: Speech (Ming TTS)- /// Streams Ming's voice for `text` as raw 24 kHz mono 16-bit PCM chunks.- func speech(_ text: String, voice: String = "UK_Charlotte") -> AsyncThrowingStream<Data, Error> {+ /// Streams Ming's voice for `text` as raw 24 kHz mono 16-bit PCM chunks: a built-in `voice`, or+ /// a voice cloned from `reference` (a WAV data URI and what it says). `language` is Ming's+ /// `language_id`, needed for Japanese, Korean, German, French and Spanish.+ func speech(_ text: String, voice: String? = "UK_Charlotte", reference: (audio: String, text: String)? = nil,+ language: String? = nil) -> AsyncThrowingStream<Data, Error> {AsyncThrowingStream { cont inlet task = Task { @MainActor [weak self] inguard let self, let key = self.key else { cont.finish(throwing: Failure.noKey); return }@@ -223,10 +294,18 @@ final class LingClient: ObservableObject {req.timeoutInterval = 20req.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")req.setValue("application/json", forHTTPHeaderField: "Content-Type")- req.httpBody = try? JSONSerialization.data(withJSONObject: [- "model": "Ming-3.0-tts-0.5B", "input": text, "voice": voice,+ var body: [String: Any] = [+ "model": "Ming-3.0-tts-0.5B", "input": text,"response_format": "pcm", "sample_rate": 24000, "stream": true, "stream_format": "sse",- ] as [String: Any])+ ]+ if let reference {+ body["references"] = [["audio": reference.audio, "text": reference.text]]+ req.timeoutInterval = 30+ } else if let voice {+ body["voice"] = voice+ }+ if let language { body["language_id"] = language }+ req.httpBody = try? JSONSerialization.data(withJSONObject: body)do {let (bytes, response) = try await URLSession.shared.bytes(for: req)switch (response as? HTTPURLResponse)?.statusCode ?? 0 {diff --git a/Sources/LiveSubs/ListenEngine.swift b/Sources/LiveSubs/ListenEngine.swiftindex 603aece..9c536e1 100644--- a/Sources/LiveSubs/ListenEngine.swift+++ b/Sources/LiveSubs/ListenEngine.swift@@ -21,6 +21,8 @@ final class ListenEngine {/// A finished sentence; `secondsAgo` ≈ how long ago it started.var onFinal: ((Segment, _ secondsAgo: Double) -> Void)?var onTranslated: ((_ segmentID: Int, _ translation: String) -> Void)?+ /// Diagnostics: how long a sentence took from its last new words to its translation on screen.+ var onTiming: ((SentenceTiming) -> Void)?let settings: AppSettingslet router = AudioRouter()@@ -52,6 +54,8 @@ final class ListenEngine {private var volatileInFlight = falseprivate var volatileEpoch = 0private var tickTimer: Timer?+ /// Final transcript time and how long after the last word it came, per segment, until its translation lands.+ private var finalTiming: [Int: (at: Date, recognize: Double?)] = [:]init(settings: AppSettings) {self.settings = settings@@ -308,6 +312,10 @@ final class ListenEngine {let provisional = volatileTranslation.isEmpty ? nil : volatileTranslationlet seg = Segment(id: nextSegmentID, text: text, sourceCode: activeLang?.code ?? "auto", translation: provisional)nextSegmentID += 1+ // How long ago, in real time, the sentence's last word was spoken.+ let ago = router.fedSeconds() - CMTimeGetSeconds(result.range.end)+ finalTiming[seg.id] = (Date(), ago.isFinite && ago >= 0 && ago < 30 ? ago : nil)+ if finalTiming.count > 40, let oldest = finalTiming.keys.min() { finalTiming[oldest] = nil }segments.append(seg)// Only the last few are shown; in notes mode nothing clears them after a pause.if segments.count > 30 { segments.removeFirst(segments.count - 30) }@@ -427,10 +435,10 @@ final class ListenEngine {var translator: TranslationService?func translate(_ text: String, source: String, target: String? = nil,- kind: TranslationService.Kind = .sentence) async -> String? {+ kind: TranslationService.Kind = .sentence, trace: TranslateTrace? = nil) async -> String? {let target = target ?? resolvedTargetif source == target { return text }- let out = await translator?.translate(text, source: source, target: target, kind: kind)+ let out = await translator?.translate(text, source: source, target: target, kind: kind, trace: trace)if out == nil, segments.allSatisfy({ $0.translation == nil }) && volatileTranslation.isEmpty {onSubtitle?(volatileText.isEmpty ? (segments.last?.text ?? "") : volatileText, "翻译暂不可用")}@@ -439,8 +447,18 @@ final class ListenEngine {private func translateSegment(id: Int) {guard let seg = segments.first(where: { $0.id == id }) else { return }+ let trace = TranslateTrace()+ let asked = Date()Task { [weak self] in- guard let self, let out = await self.translate(seg.text, source: seg.sourceCode) else { return }+ guard let self else { return }+ let result = await self.translate(seg.text, source: seg.sourceCode, trace: trace)+ if let timing = self.finalTiming.removeValue(forKey: id), !trace.attempts.isEmpty {+ self.onTiming?(SentenceTiming(at: timing.at, side: "them", chars: seg.text.count, recognize: timing.recognize,+ queue: trace.lingQueue, translate: Date().timeIntervalSince(asked), voice: nil,+ failed: trace.failedSeconds, via: result == nil ? "none" : trace.via,+ fallbacks: trace.fallbacks))+ }+ guard let out = result else { return }guard self.isRunning else { return }if let idx = self.segments.firstIndex(where: { $0.id == id }) {self.segments[idx].translation = outdiff --git a/Sources/LiveSubs/Notes.swift b/Sources/LiveSubs/Notes.swiftindex 56c3541..741ea46 100644--- a/Sources/LiveSubs/Notes.swift+++ b/Sources/LiveSubs/Notes.swift@@ -24,7 +24,11 @@ struct NoteTopic: Codable, Equatable, Identifiable {var summary: Stringvar points: [String]var fishbone: Fishbone?+ /// When each point was said (its first evidence line), parallel to `points`; older notes have none.+ var pointTimes: [Double?]?var id: String { "\(Int(start))-\(title)" }++ func pointTime(_ i: Int) -> Double? { pointTimes.flatMap { i < $0.count ? $0[i] : nil } }}/// A cause-and-effect diagram for a topic that discusses why something happened.@@ -46,6 +50,8 @@ struct NoteItem: Codable, Equatable, Identifiable {var text: Stringvar owner: String?var support: Int+ /// When it was said (first evidence line).+ var t: Double?var id: String { text }}@@ -94,6 +100,7 @@ final class NotesEngine: ObservableObject {/// A final pass asked for while another call was running; it runs right after.private var pendingFinal: String?private var lastAttempt = Date.distantPast+ private var freshGeneration = 0static let interval: TimeInterval = 45init(ling: LingClient, store: SessionStore) {@@ -203,16 +210,17 @@ final class NotesEngine: ObservableObject {do {let raw = try await ling.chat(content: prompt, instruction: "Update the notes.", priority: .notes,json: true, maxTokens: 6000, timeout: 90)- guard var next = Self.parse(raw, lineCount: lines.count, startedAt: session.lines.first?.t ?? 0) else {+ guard var next = Self.parse(raw, times: lines.map(\.t), startedAt: session.lines.first?.t ?? 0) else {debugLog("notes: reply was not usable JSON, kept the previous notes")state = .failedreturn}+ Self.carryTimes(from: base, into: &next)next.covered = lines.countnext.updatedAt = Date()next.final = finalif id == shownID {- markFresh(old: notes, new: next)+ markFresh(old: notes, new: next, final: final)if next.summary != notes.summary { summaryChangedAt = Date() }notes = next}@@ -231,10 +239,32 @@ final class NotesEngine: ObservableObject {}}- private func markFresh(old: MeetingNotes, new: MeetingNotes) {- guard !old.isEmpty else { fresh = []; return }+ /// "新" marks what the last live update added, for a minute. The final pass rewrites+ /// everything, so it marks nothing.+ private func markFresh(old: MeetingNotes, new: MeetingNotes, final: Bool) {+ freshGeneration += 1+ guard !old.isEmpty, !final else { fresh = []; return }let before = Set(old.topics.flatMap { [$0.title] + $0.points })fresh = Set(new.topics.flatMap { [$0.title] + $0.points }).subtracting(before)+ let generation = freshGeneration+ DispatchQueue.main.asyncAfter(deadline: .now() + 60) { [weak self] in+ MainActor.assumeIsolated {+ if self?.freshGeneration == generation { self?.fresh = [] }+ }+ }+ }++ /// The model echoes points it already had without evidence: keep the times they had.+ static func carryTimes(from old: MeetingNotes, into new: inout MeetingNotes) {+ var known: [String: Double] = [:]+ for t in old.topics { for (i, p) in t.points.enumerated() { if let x = t.pointTime(i) { known[p] = x } } }+ for (ti, t) in new.topics.enumerated() {+ let times = t.points.enumerated().map { i, p in t.pointTime(i) ?? known[p] }+ new.topics[ti].pointTimes = times.contains { $0 != nil } ? times : nil+ }+ let items = Dictionary((old.conclusions + old.todos).compactMap { i in i.t.map { (i.text, $0) } }, uniquingKeysWith: { a, _ in a })+ for i in new.conclusions.indices where new.conclusions[i].t == nil { new.conclusions[i].t = items[new.conclusions[i].text] }+ for i in new.todos.indices where new.todos[i].t == nil { new.todos[i].t = items[new.todos[i].text] }}// MARK: Prompt@@ -269,7 +299,7 @@ final class NotesEngine: ObservableObject {Return the full notes as one JSON object with exactly these keys:{"summary": "2-3 sentences on the whole meeting so far",- "topics": [{"start": seconds, "title": "short title", "summary": "one sentence", "points": ["key point"], "evidence": ["L3"],+ "topics": [{"start": seconds, "title": "short title", "summary": "one sentence", "points": [{"text": "key point", "evidence": ["L4"]}], "evidence": ["L3"],"fishbone": null or {"question": "the problem or question", "branches": [{"label": "2-6 words", "detail": "one short line", "t": seconds, "evidence": ["L5"]}]}}],"conclusions": [{"text": "...", "evidence": ["L7", "L8"]}],"todos": [{"text": "...", "owner": "对方" or "你" or null, "evidence": ["L9"]}],@@ -280,7 +310,7 @@ final class NotesEngine: ObservableObject {- At most 4 points per topic, each one short phrase. Merge rather than repeat.- At most 5 conclusions and only real to-dos (often none).- Add a fishbone only to a topic that discusses causes, reasons or factors (3-5 branches); otherwise null.- - Every topic, point source, branch, conclusion and to-do needs evidence: the ids of the lines that say it. Never state anything the transcript does not say.+ - Every topic, point, branch, conclusion and to-do needs evidence: the ids of the lines that say it. Never state anything the transcript does not say.- terms: at most 10 people, places or jargon words that matter. name is the correct spelling in the transcript's language (no translation in brackets); heard lists only the wrong forms the transcript used; note is a few words.- Write about what was said, never about the transcript or recognition quality.- Use empty arrays when there is nothing. No markdown, no text outside the JSON.@@ -291,13 +321,20 @@ final class NotesEngine: ObservableObject {/// The current notes as sent back to the model (no bookkeeping fields).private struct Compact: Encodable {let summary: String- let topics: [NoteTopic]+ let topics: [Topic]let conclusions: [String]let todos: [String]let terms: [NoteTerm]+ struct Topic: Encodable {+ let start: Double+ let title: String+ let summary: String+ let points: [String]+ let fishbone: Fishbone?+ }init(_ n: MeetingNotes) {summary = n.summary- topics = n.topics+ topics = n.topics.map { Topic(start: $0.start, title: $0.title, summary: $0.summary, points: $0.points, fishbone: $0.fishbone) }conclusions = n.conclusions.map(\.text)todos = n.todos.map(\.text)terms = n.terms@@ -307,20 +344,24 @@ final class NotesEngine: ObservableObject {// MARK: Parse/// Lenient: missing keys become empty, evidence ids are checked against the transcript.- static func parse(_ raw: String, lineCount: Int, startedAt: Double) -> MeetingNotes? {+ static func parse(_ raw: String, times: [Double], startedAt: Double) -> MeetingNotes? {+ let lineCount = times.countvar text = rawif let a = text.firstIndex(of: "{"), let b = text.lastIndex(of: "}") { text = String(text[a...b]) }guard let data = text.data(using: .utf8),let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }func str(_ v: Any?) -> String { (v as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" }func num(_ v: Any?) -> Double? { (v as? NSNumber)?.doubleValue ?? (v as? String).flatMap(Double.init) }- func support(_ v: Any?) -> Int {+ func lineNumbers(_ v: Any?) -> Set<Int> {let ids = (v as? [Any])?.compactMap { $0 as? String } ?? []return Set(ids.compactMap { id -> Int? inguard let n = Int(id.drop(while: { !$0.isNumber })), n >= 1, n <= lineCount else { return nil }return n- }).count+ })}+ func support(_ v: Any?) -> Int { lineNumbers(v).count }+ /// When it was first said: the earliest evidence line.+ func time(_ v: Any?) -> Double? { lineNumbers(v).min().map { times[$0 - 1] } }var n = MeetingNotes()n.summary = str(root["summary"])n.topics = (root["topics"] as? [[String: Any]] ?? []).compactMap { t in@@ -335,14 +376,24 @@ final class NotesEngine: ObservableObject {}if branches.count >= 2 { fish = Fishbone(question: str(f["question"]), branches: branches) }}+ // Points come as {"text", "evidence"} (or plain strings from older replies).+ var points: [String] = [], pointTimes: [Double?] = []+ for p in t["points"] as? [Any] ?? [] {+ let text = (p as? [String: Any]).map { str($0["text"]) } ?? str(p)+ guard !text.isEmpty else { continue }+ points.append(text)+ pointTimes.append((p as? [String: Any]).flatMap { time($0["evidence"]) })+ }return NoteTopic(start: num(t["start"]) ?? startedAt, title: title, summary: str(t["summary"]),- points: (t["points"] as? [Any] ?? []).map(str).filter { !$0.isEmpty }, fishbone: fish)+ points: points, fishbone: fish,+ pointTimes: pointTimes.contains { $0 != nil } ? pointTimes : nil)}func items(_ key: String) -> [NoteItem] {(root[key] as? [[String: Any]] ?? []).compactMap { i inlet text = str(i["text"])let owner = str(i["owner"])- return text.isEmpty ? nil : NoteItem(text: text, owner: owner.isEmpty ? nil : owner, support: support(i["evidence"]))+ return text.isEmpty ? nil : NoteItem(text: text, owner: owner.isEmpty ? nil : owner, support: support(i["evidence"]),+ t: time(i["evidence"]))}}n.conclusions = items("conclusions")diff --git a/Sources/LiveSubs/NotesViews.swift b/Sources/LiveSubs/NotesViews.swiftindex 1530b1c..8c2d5a4 100644--- a/Sources/LiveSubs/NotesViews.swift+++ b/Sources/LiveSubs/NotesViews.swift@@ -14,6 +14,10 @@ struct NotesContentView: View {var live = falsevar updating = falsevar summaryJustChanged = false+ /// The time of the last line the notes cover ("到 03:52").+ var coveredUntil: Double?+ /// Where the last topic ends when the meeting is over (its last line).+ var endedAt: Double?var onJump: (Double) -> Void = { _ in }var body: some View {@@ -24,7 +28,9 @@ struct NotesContentView: View {Text("总结").font(.system(size: 15, weight: .bold))if summaryJustChanged { Tag("刚更新", live: true) }Spacer()- if notes.final { Tag("完整版") } else if live { Tag("速记版") }+ if notes.final { Tag("完整版") } else if live {+ Tag(coveredUntil.map { "速记版 · 到 \(NotesEngine.clock($0))" } ?? "速记版")+ }}Text(notes.summary).font(.system(size: 14)).lineSpacing(4).textSelection(.enabled)}@@ -37,7 +43,9 @@ struct NotesContentView: View {VStack(alignment: .leading, spacing: 14) {SectionTitle("议题")ForEach(Array(notes.topics.enumerated()), id: \.element.id) { i, topic in- TopicView(topic: topic, current: live && i == notes.topics.count - 1,+ TopicView(topic: topic,+ end: i + 1 < notes.topics.count ? notes.topics[i + 1].start : (live ? nil : endedAt),+ current: live && i == notes.topics.count - 1,updating: updating && i == notes.topics.count - 1, fresh: fresh, onJump: onJump)}}@@ -57,7 +65,13 @@ struct NotesContentView: View {.font(.system(size: 14)).lineSpacing(2).foregroundStyle(item.support == 0 ? Palette.tertiary : Palette.ink).frame(maxWidth: .infinity, alignment: .leading)- Tag(item.support == 0 ? "依据少" : "依据 \(item.support) 句")+ if item.support == 0 {+ Tag("依据较少")+ } else if let t = item.t {+ TimeLink(text: "\(NotesEngine.clock(t)) · \(item.support) 句", t: t, onJump: onJump)+ } else {+ Tag("依据 \(item.support) 句")+ }}.padding(.horizontal, 16).padding(.vertical, 11)if i < notes.conclusions.count + notes.todos.count - 1 { Divider() }@@ -87,6 +101,8 @@ struct NotesContentView: View {private struct TopicView: View {let topic: NoteTopic+ /// The next topic's start, or the meeting's end; nil while it is still being discussed.+ let end: Double?let current: Boollet updating: Boollet fresh: Set<String>@@ -96,10 +112,10 @@ private struct TopicView: View {VStack(alignment: .leading, spacing: 8) {HStack(alignment: .firstTextBaseline, spacing: 10) {Button { onJump(topic.start) } label: {- Text(NotesEngine.clock(topic.start))- .font(.system(size: 12).monospacedDigit())+ Text(range)+ .font(.system(size: 12, weight: current ? .semibold : .regular).monospacedDigit()).foregroundStyle(current ? Palette.accentInk : Palette.tertiary)- .frame(width: topic.start >= 3600 ? 56 : 40, alignment: .leading)+ .frame(width: column, alignment: .leading)}.buttonStyle(.plain).help("看原话")Text(topic.title).font(.system(size: 15, weight: .bold))@@ -111,30 +127,62 @@ private struct TopicView: View {Text(topic.summary).font(.system(size: 13)).foregroundStyle(Palette.secondary).lineSpacing(2).fixedSize(horizontal: false, vertical: true)}- ForEach(topic.points, id: \.self) { p in+ ForEach(Array(topic.points.enumerated()), id: \.offset) { i, p inHStack(alignment: .firstTextBaseline, spacing: 8) {Circle().fill(fresh.contains(p) ? Palette.accent : Palette.ink.opacity(0.55)).frame(width: 4, height: 4).alignmentGuide(.firstTextBaseline) { $0[.bottom] + 4 }Text(p).font(.system(size: 14)).lineSpacing(2).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)if fresh.contains(p) { Tag("新", live: true) }+ Spacer(minLength: 4)+ if let t = topic.pointTime(i) { TimeLink(text: NotesEngine.clock(t), t: t, onJump: onJump) }}+ .modifier(FadeIn(active: fresh.contains(p)))}if let fish = topic.fishbone { FishboneView(fishbone: fish, onJump: onJump).padding(.top, 4) }if updating {- VStack(alignment: .leading, spacing: 6) {- RoundedRectangle(cornerRadius: 4).fill(Palette.fill).frame(height: 9).frame(maxWidth: 260)- RoundedRectangle(cornerRadius: 4).fill(Palette.fill).frame(width: 160, height: 9)- Text("正在整理这一段…").font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ VStack(alignment: .leading, spacing: 7) {+ SkeletonBar(fraction: 0.82, height: 10, warm: true)+ SkeletonBar(fraction: 0.56, height: 10, warm: true)}- .padding(.top, 4)+ .padding(.top, 2)}}- .padding(.leading, topic.start >= 3600 ? 66 : 50)+ .padding(.leading, column + 10)}.padding(.vertical, current ? 10 : 0).padding(.horizontal, current ? 10 : 0).background(RoundedRectangle(cornerRadius: 14).fill(current ? Palette.accentWash : .clear))}++ /// "01:04–02:02", or "02:03 起" for the topic being discussed.+ private var range: String {+ let from = NotesEngine.clock(topic.start)+ guard let end, end > topic.start + 1 else { return current ? "\(from) 起" : from }+ return "\(from)–\(NotesEngine.clock(end))"+ }++ private var column: CGFloat { (end ?? topic.start) >= 3600 ? 104 : 76 }+}++/// A small time that jumps to that moment in the transcript.+struct TimeLink: View {+ let text: String+ let t: Double+ let onJump: (Double) -> Void+ @State private var hover = false++ var body: some View {+ Button { onJump(t) } label: {+ Text(text).font(.system(size: 12).monospacedDigit())+ .foregroundStyle(hover ? Palette.ink : Palette.tertiary)+ .padding(.horizontal, 6).padding(.vertical, 2)+ .background(RoundedRectangle(cornerRadius: 5).fill(hover ? Palette.fill : .clear))+ .fixedSize()+ }+ .buttonStyle(.plain)+ .onHover { hover = $0 }+ .help("回到原话")+ }}/// A fishbone drawn upright for a narrow window: the question on top, branches alternating on@@ -165,7 +213,7 @@ struct FishboneView: View {.fixedSize(horizontal: false, vertical: true)}}- Text("点分支回到原话").font(.system(size: 11)).foregroundStyle(Palette.tertiary)+ Text("点击分支跳回原话").font(.system(size: 11)).foregroundStyle(Palette.tertiary)}.padding(12).background(RoundedRectangle(cornerRadius: 16).stroke(Palette.line, lineWidth: 1))@@ -198,89 +246,231 @@ struct FishboneView: View {.contentShape(Rectangle())}.buttonStyle(.plain)- .help(weak ? "依据少,仅供参考" : "看原话")+ .help(weak ? "依据较少,仅供参考" : "看原话")}}// MARK: - Transcript-/// The transcript grouped under the notes' topics, newest at the bottom.+/// The transcript grouped under the notes' topics, oldest first. While live it follows the+/// newest line; scrolling up pauses that and collects new lines into a "↓ N 句新内容" button.+/// A search highlights matches in place instead of hiding the lines around them.struct TranscriptListView: View {let lines: [TranscriptLine]let topics: [NoteTopic]- var query = ""+ /// Spellings to highlight: the query, plus the notes' misrecognised forms of a name.+ var terms: [String] = []+ var currentMatch: String?var bilingual = truevar live = false+ /// What is being said right now, not yet a finished line.+ var partial = ""+ var partialTime: Double?var jumpTo: Double?+ @State private var following = true+ @State private var seenCount = 0++ private var searching: Bool { !terms.isEmpty }+ /// The caption keeps the last sentence after it is finished: only show text not yet a line.+ private var showsPartial: Bool {+ let p = partial.trimmingCharacters(in: .whitespacesAndNewlines)+ guard live, !p.isEmpty else { return false }+ guard let last = lines.last?.src else { return true }+ return !last.contains(p) && !p.contains(last)+ }+private var groups: [(title: String, start: Double, lines: [TranscriptLine])] {- let shown = query.isEmpty ? lines : lines.filter {- $0.src.localizedCaseInsensitiveContains(query) || ($0.dst ?? "").localizedCaseInsensitiveContains(query)- }- guard !topics.isEmpty else { return [("", 0, shown)] }+ guard !topics.isEmpty else { return [("", 0, lines)] }var out: [(String, Double, [TranscriptLine])] = []for (i, t) in topics.enumerated() {let end = i + 1 < topics.count ? topics[i + 1].start : .infinitylet first = i == 0 ? -Double.infinity : t.start- let ls = shown.filter { $0.t >= first && $0.t < end }+ let ls = lines.filter { $0.t >= first && $0.t < end }if !ls.isEmpty { out.append((t.title, t.start, ls)) }}return out}+ private struct Edge: Equatable {+ var distance: CGFloat+ var height: CGFloat+ }+var body: some View {ScrollViewReader { proxy in- ScrollView {- LazyVStack(alignment: .leading, spacing: 10) {- ForEach(groups, id: \.start) { g in- if !g.title.isEmpty { SectionTitle(g.title).padding(.top, 6) }- FramedList {- ForEach(Array(g.lines.enumerated()), id: \.element.id) { i, l in- row(l, current: live && l.id == lines.last?.id).id(l.id)- if i < g.lines.count - 1 { Divider() }+ ZStack(alignment: .bottom) {+ ScrollView {+ LazyVStack(alignment: .leading, spacing: 10) {+ let gs = groups+ ForEach(Array(gs.enumerated()), id: \.element.start) { gi, g in+ // One lazy child per topic group, with an id to scroll to before it is drawn.+ VStack(alignment: .leading, spacing: 10) {+ if !g.title.isEmpty {+ Text("\(NotesEngine.clock(g.start)) · \(g.title)")+ .font(.system(size: 13, weight: .bold)).foregroundStyle(Palette.secondary).padding(.top, 6)+ }+ FramedList {+ ForEach(Array(g.lines.enumerated()), id: \.element.id) { i, l in+ row(l).id(l.id)+ if i < g.lines.count - 1 { Divider() }+ }+ if gi == gs.count - 1, showsPartial {+ Divider()+ partialRow+ }+ }}+ .id(groupID(g.start))+ }+ if lines.isEmpty && !showsPartial {+ Text("说话的内容会出现在这里").font(.system(size: 13)).foregroundStyle(Palette.tertiary)+ .frame(maxWidth: .infinity).padding(.top, 40)}+ Color.clear.frame(height: 1).id("bottom")}- if lines.isEmpty {- Text("说话的内容会出现在这里").font(.system(size: 13)).foregroundStyle(Palette.tertiary)- .frame(maxWidth: .infinity).padding(.top, 40)+ .padding(.bottom, 12)+ }+ .onScrollGeometryChange(for: Edge.self) { g in+ Edge(distance: g.contentSize.height - g.contentOffset.y - g.containerSize.height, height: g.contentSize.height)+ } action: { old, new in+ if new.distance < 40 {+ if !following { following = true }+ } else if following, new.distance > 60, new.height == old.height {+ // The reader scrolled up (content growing never pauses following).+ following = false+ seenCount = lines.count}}- .padding(.bottom, 12)- }- .onChange(of: lines.count) { _, _ in- if live, query.isEmpty, let last = lines.last { withAnimation { proxy.scrollTo(last.id, anchor: .bottom) } }- }- .onChange(of: jumpTo) { _, t in- guard let t, let target = lines.first(where: { $0.t >= t - 1 }) ?? lines.last else { return }- withAnimation { proxy.scrollTo(target.id, anchor: .top) }+ .onChange(of: lines.count) { _, _ in follow(proxy) }+ .onChange(of: partial) { _, _ in follow(proxy) }+ .onChange(of: currentMatch) { _, id in+ guard let id, let line = lines.first(where: { $0.id == id }) else { return }+ reveal(line, anchor: .center, proxy)+ }+ .onChange(of: jumpTo) { _, t in+ guard let t, let target = lines.first(where: { $0.t >= t - 1 }) ?? lines.last else { return }+ following = false+ seenCount = lines.count+ reveal(target, anchor: .top, proxy)+ }+ .onAppear {+ seenCount = lines.count+ if let t = jumpTo, let target = lines.first(where: { $0.t >= t - 1 }) {+ following = false+ reveal(target, anchor: .top, proxy)+ } else if live {+ proxy.scrollTo("bottom", anchor: .bottom)+ }+ }++ if live, !following, !searching, lines.count > seenCount {+ newLinesButton { following = true; proxy.scrollTo("bottom", anchor: .bottom) }+ }}- .onAppear {- if let t = jumpTo, let target = lines.first(where: { $0.t >= t - 1 }) {- proxy.scrollTo(target.id, anchor: .top)- } else if live, let last = lines.last {- proxy.scrollTo(last.id, anchor: .bottom)+ }+ }++ private func groupID(_ start: Double) -> String { "group-\(start)" }++ /// Rows inside a topic group that the lazy stack hasn't drawn yet can't be scrolled to:+ /// bring the group in first, then the line.+ private func reveal(_ line: TranscriptLine, anchor: UnitPoint, _ proxy: ScrollViewProxy) {+ if let g = groups.last(where: { $0.lines.contains { $0.id == line.id } }) {+ proxy.scrollTo(groupID(g.start), anchor: .top)+ }+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {+ withAnimation { proxy.scrollTo(line.id, anchor: anchor) }+ }+ }++ private func follow(_ proxy: ScrollViewProxy) {+ guard live, following, !searching else { return }+ proxy.scrollTo("bottom", anchor: .bottom)+ }++ private func newLinesButton(_ action: @escaping () -> Void) -> some View {+ VStack(spacing: 0) {+ LinearGradient(colors: [.white.opacity(0), .white], startPoint: .top, endPoint: .bottom).frame(height: 40)+ Button(action: action) {+ HStack(spacing: 10) {+ Image(systemName: "arrow.down").font(.system(size: 12, weight: .bold))+ Text("\(lines.count - seenCount) 句新内容").font(.system(size: 13, weight: .semibold))+ if let last = lines.last {+ Text(last.src).font(.system(size: 13)).foregroundStyle(Color(white: 0.74)).lineLimit(1)+ }}+ .foregroundStyle(.white)+ .padding(.leading, 14).padding(.trailing, 18).frame(height: 40)+ .background(Capsule().fill(Palette.ink).shadow(color: .black.opacity(0.18), radius: 12, y: 6))+ .frame(maxWidth: 380)+ .fixedSize(horizontal: true, vertical: false)}+ .buttonStyle(.plain)+ .padding(.bottom, 14)+ .frame(maxWidth: .infinity)+ .background(Color.white)}+ .transition(.opacity)}- private func row(_ l: TranscriptLine, current: Bool) -> some View {- HStack(alignment: .top, spacing: 12) {- Text(NotesEngine.clock(l.t)).font(.system(size: 12).monospacedDigit())- .foregroundStyle(current ? Palette.accentInk : Palette.tertiary)+ private func matches(_ l: TranscriptLine) -> Bool {+ terms.contains { l.src.localizedCaseInsensitiveContains($0) || (l.dst ?? "").localizedCaseInsensitiveContains($0) }+ }++ private func highlighted(_ text: String, current: Bool) -> AttributedString {+ var a = AttributedString(text)+ for term in terms where !term.isEmpty {+ var from = a.startIndex+ while from < a.endIndex, let r = a[from...].range(of: term, options: .caseInsensitive) {+ a[r].backgroundColor = current ? Palette.accent : Palette.accentPale+ a[r].foregroundColor = current ? .white : Palette.accentInk+ from = r.upperBound+ }+ }+ return a+ }++ private func row(_ l: TranscriptLine) -> some View {+ let isMatch = l.id == currentMatch+ let latest = live && l.id == lines.last?.id+ let dim = searching && !matches(l)+ return HStack(alignment: .top, spacing: 12) {+ Text(NotesEngine.clock(l.t)).font(.system(size: 12, weight: isMatch ? .semibold : .regular).monospacedDigit())+ .foregroundStyle(latest || isMatch ? Palette.accentInk : Palette.tertiary).frame(width: l.t >= 3600 ? 56 : 40, alignment: .leading).padding(.top, 2)VStack(alignment: .leading, spacing: 4) {if l.speaker == "me" { Text("你").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.accentInk) }- Text(l.src).font(.system(size: 14)).lineSpacing(2).textSelection(.enabled)+ Text(highlighted(l.src, current: isMatch)).font(.system(size: 14)).lineSpacing(2).textSelection(.enabled)if bilingual, let d = l.dst, d != l.src {- Text(d).font(.system(size: 13)).foregroundStyle(Palette.secondary).lineSpacing(2).textSelection(.enabled)+ Text(highlighted(d, current: isMatch)).font(.system(size: 13)).foregroundStyle(Palette.secondary)+ .lineSpacing(2).textSelection(.enabled)+ }+ }+ Spacer(minLength: 0)+ }+ .padding(.horizontal, 14).padding(.vertical, 11)+ .background(latest || isMatch ? Palette.accentWash : Color.clear)+ .opacity(dim ? 0.5 : 1)+ }++ private var partialRow: some View {+ HStack(alignment: .top, spacing: 12) {+ Text(partialTime.map(NotesEngine.clock) ?? "").font(.system(size: 12).monospacedDigit())+ .foregroundStyle(Palette.accentInk)+ .frame(width: (partialTime ?? 0) >= 3600 ? 56 : 40, alignment: .leading).padding(.top, 2)+ VStack(alignment: .leading, spacing: 4) {+ HStack(alignment: .lastTextBaseline, spacing: 0) {+ Text(partial).font(.system(size: 14)).foregroundStyle(Palette.secondary).lineSpacing(2)+ AnimatedDots().font(.system(size: 14)).foregroundStyle(Palette.secondary)}+ Text("正在说").font(.system(size: 11)).foregroundStyle(Palette.tertiary)}Spacer(minLength: 0)}.padding(.horizontal, 14).padding(.vertical, 11)- .background(current ? Palette.accentWash : Color.clear)+ .background(Palette.accentWash)+ .id("partial")}}@@ -347,3 +537,189 @@ struct FlowLayout: Layout {}}}++// MARK: - Motion (notes in progress)+// One moving thing at a time says the app is working. Driven by TimelineView rather than+// repeatForever animations, which the window's once-a-second redraw would restart.++private func phase(_ date: Date, period: Double, delay: Double = 0) -> Double {+ let t = date.timeIntervalSinceReferenceDate - delay+ return (t.truncatingRemainder(dividingBy: period) + period).truncatingRemainder(dividingBy: period) / period+}++/// Listening, nobody has spoken yet: five sound bars with a soft ring pulsing behind them.+struct ListeningMark: View {+ var body: some View {+ TimelineView(.animation(minimumInterval: 1 / 30)) { ctx in+ let ring = phase(ctx.date, period: 2)+ ZStack {+ Circle().fill(Palette.accentPale)+ .scaleEffect(0.8 + 0.8 * ring).opacity(0.55 * (1 - ring))+ HStack(spacing: 6) {+ ForEach(0..<5, id: \.self) { i in+ let p = phase(ctx.date, period: 1.1, delay: Double(i) * 0.15)+ Capsule().fill(Palette.accent).frame(width: 6, height: 44)+ .scaleEffect(x: 1, y: 0.25 + 0.75 * (0.5 - 0.5 * cos(p * 2 * .pi)))+ }+ }+ }+ .frame(width: 120, height: 120)+ }+ .accessibilityHidden(true)+ }+}++/// A small orange ring spinner.+struct Spinner: View {+ var size: CGFloat = 16+ var track = Palette.accentPale++ var body: some View {+ TimelineView(.animation(minimumInterval: 1 / 30)) { ctx in+ ZStack {+ Circle().stroke(track, lineWidth: 2)+ Circle().trim(from: 0, to: 0.25)+ .stroke(Palette.accent, style: StrokeStyle(lineWidth: 2, lineCap: .round))+ .rotationEffect(.degrees(phase(ctx.date, period: 0.9) * 360))+ }+ .frame(width: size, height: size)+ }+ .accessibilityHidden(true)+ }+}++/// "…" whose dots light up one after another.+struct AnimatedDots: View {+ var body: some View {+ TimelineView(.animation(minimumInterval: 1 / 15)) { ctx in+ HStack(spacing: 0) {+ ForEach(0..<3, id: \.self) { i in+ Text(".").opacity(0.3 + 0.7 * (0.5 - 0.5 * cos(phase(ctx.date, period: 1.2, delay: Double(i) * 0.2) * 2 * .pi)))+ }+ }+ }+ }+}++/// The live dot beside "正在记录", breathing slowly.+struct LiveDot: View {+ var body: some View {+ TimelineView(.animation(minimumInterval: 1 / 15)) { ctx in+ Circle().fill(Palette.accent).frame(width: 7, height: 7)+ .opacity(0.35 + 0.65 * (0.5 + 0.5 * cos(phase(ctx.date, period: 1.4) * 2 * .pi)))+ }+ }+}++/// A placeholder line with a light sweeping across it. `warm` is the pale orange used inside+/// the topic being updated.+struct SkeletonBar: View {+ var fraction: CGFloat = 1+ var height: CGFloat = 12+ var warm = false++ var body: some View {+ let base = warm ? Color(red: 0.965, green: 0.89, blue: 0.86) : Color(red: 0.933, green: 0.941, blue: 0.953)+ let light = warm ? Color(red: 0.992, green: 0.953, blue: 0.933) : Color(red: 0.969, green: 0.973, blue: 0.98)+ GeometryReader { g in+ TimelineView(.animation(minimumInterval: 1 / 30)) { ctx in+ let x = phase(ctx.date, period: 1.4) * 2 - 0.5+ RoundedRectangle(cornerRadius: min(6, height / 2))+ .fill(LinearGradient(stops: [.init(color: base, location: 0), .init(color: light, location: 0.5),+ .init(color: base, location: 1)],+ startPoint: UnitPoint(x: x - 0.6, y: 0.5), endPoint: UnitPoint(x: x + 0.6, y: 0.5)))+ .frame(width: g.size.width * fraction)+ }+ }+ .frame(height: height)+ .accessibilityHidden(true)+ }+}++/// Listening, nothing said yet.+struct NotesListeningView: View {+ var body: some View {+ VStack(spacing: 22) {+ ListeningMark()+ VStack(spacing: 8) {+ Text("正在听").font(.system(size: 17, weight: .bold))+ Text("有人说话时,会自动开始写纪要").font(.system(size: 13)).foregroundStyle(Palette.secondary)+ }+ }+ .frame(maxWidth: .infinity)+ }+}++/// The first version of the notes is being written: a spinner, how much has been heard, and+/// the shape of the notes shimmering where they will appear.+struct NotesGeneratingView: View {+ var heard: Int?++ var body: some View {+ VStack(alignment: .leading, spacing: 18) {+ HStack(spacing: 10) {+ Spinner()+ HStack(spacing: 0) {+ Text("正在生成纪要")+ AnimatedDots()+ }+ .font(.system(size: 15, weight: .bold))+ Spacer()+ if let heard, heard > 0 {+ Text("已听到 \(heard) 句").font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ }+ }+ VStack(alignment: .leading, spacing: 10) {+ Text("总结").font(.system(size: 15, weight: .bold)).foregroundStyle(Palette.placeholder)+ SkeletonBar()+ SkeletonBar(fraction: 0.92)+ SkeletonBar(fraction: 0.64)+ }+ .padding(18)+ .background(RoundedRectangle(cornerRadius: 18).fill(Palette.raised))+ VStack(alignment: .leading, spacing: 14) {+ Text("议题").font(.system(size: 15, weight: .bold)).foregroundStyle(Palette.placeholder)+ topicRow(lines: [0.55, 0.88, 0.72])+ topicRow(lines: [0.42, 0.8]).opacity(0.6)+ }+ }+ }++ private func topicRow(lines: [CGFloat]) -> some View {+ HStack(alignment: .top, spacing: 12) {+ SkeletonBar(height: 12).frame(width: 36)+ VStack(alignment: .leading, spacing: 9) {+ ForEach(Array(lines.enumerated()), id: \.offset) { i, f in+ SkeletonBar(fraction: f, height: i == 0 ? 14 : 10)+ }+ }+ }+ }+}++/// "正在更新" pill in the header while notes that already exist are being updated.+struct UpdatingPill: View {+ var body: some View {+ HStack(spacing: 7) {+ Spinner(size: 12, track: Color(red: 0.965, green: 0.847, blue: 0.796))+ Text("正在更新").font(.system(size: 12, weight: .semibold))+ }+ .foregroundStyle(Palette.accentInk)+ .padding(.horizontal, 11).padding(.vertical, 6)+ .background(Capsule().fill(Palette.accentPale))+ .fixedSize()+ }+}++/// A point that just arrived fades in from slightly below.+struct FadeIn: ViewModifier {+ let active: Bool+ @State private var shown = false++ func body(content: Content) -> some View {+ content+ .opacity(!active || shown ? 1 : 0)+ .offset(y: !active || shown ? 0 : 4)+ .onAppear { if active { withAnimation(.easeOut(duration: 0.6)) { shown = true } } }+ }+}diff --git a/Sources/LiveSubs/NotesWindow.swift b/Sources/LiveSubs/NotesWindow.swiftindex b0b7470..7ee20c6 100644--- a/Sources/LiveSubs/NotesWindow.swift+++ b/Sources/LiveSubs/NotesWindow.swift@@ -1,18 +1,53 @@import AppKit+import Combineimport SwiftUI/// The live notes window: floats over the meeting app, can be dragged and resized anywhere,/// stays out of screen sharing, and remembers its frame. Three layouts by width: a small card/// (< 360), a sidebar with 纪要 / 文字记录 tabs, and notes beside the transcript (≥ 760).@MainActor-final class NotesWindowController {+final class NotesWindowController: NSObject, NSWindowDelegate {+ enum Layout: CaseIterable { case card, sidebar, wide }+ /// Menu commands that change the view's own state.+ enum Command { case catchUp, search, layout(Layout) }+private var panel: NSPanel?private weak var model: AppModel?+ let commands = PassthroughSubject<Command, Never>()+ /// Shown or hidden: the app is a regular app (menus, Dock) while any of its windows is open.+ var onVisibilityChange: () -> Void = {}- init(model: AppModel) { self.model = model }+ init(model: AppModel) {+ self.model = model+ super.init()+ }var isVisible: Bool { panel?.isVisible ?? false }+ var layout: Layout {+ let w = panel?.frame.width ?? 460+ return w < 360 ? .card : w >= 760 ? .wide : .sidebar+ }++ /// "浮在最上层" (`notesOnTop`, on by default).+ var onTop: Bool {+ get { UserDefaults.standard.object(forKey: "notesOnTop") as? Bool ?? true }+ set {+ UserDefaults.standard.set(newValue, forKey: "notesOnTop")+ panel?.level = newValue ? .floating : .normal+ panel?.isFloatingPanel = newValue+ }+ }++ func send(_ command: Command) {+ if case .search = command { panel?.makeKey() }+ commands.send(command)+ }++ func windowWillClose(_ notification: Notification) {+ DispatchQueue.main.async { [weak self] in self?.onVisibilityChange() }+ }+func show() {guard let model else { return }if panel == nil {@@ -21,8 +56,9 @@ final class NotesWindowController {p.titleVisibility = .hiddenp.titlebarAppearsTransparent = truep.isMovableByWindowBackground = true- p.isFloatingPanel = true- p.level = .floating+ p.isFloatingPanel = onTop+ p.level = onTop ? .floating : .normal+ p.delegate = selfp.hidesOnDeactivate = falsep.becomesKeyOnlyIfNeeded = truep.isReleasedWhenClosed = false@@ -33,15 +69,20 @@ final class NotesWindowController {p.backgroundColor = .whitep.contentView = NSHostingView(rootView: NotesWindowView(model: model, engine: model.notes, store: model.store, settings: model.settings,+ commands: commands.eraseToAnyPublisher(),setWidth: { [weak self] w, h in self?.resize(width: w, height: h) }))p.setFrameAutosaveName("LiveSubsNotes")if !p.setFrameUsingName("LiveSubsNotes") { p.setFrame(defaultFrame(), display: false) }panel = p}panel?.orderFrontRegardless()+ onVisibilityChange()}- func hide() { panel?.orderOut(nil) }+ func hide() {+ panel?.orderOut(nil)+ onVisibilityChange()+ }var frame: NSRect? { panel?.frame }@@ -76,19 +117,26 @@ struct NotesWindowView: View {@ObservedObject var engine: NotesEngine@ObservedObject var store: SessionStore@ObservedObject var settings: AppSettings+ let commands: AnyPublisher<NotesWindowController.Command, Never>let setWidth: (CGFloat, CGFloat?) -> Void@State private var tab = "notes"@State private var query = ""@State private var jumpTo: Double?@State private var keyDraft = ""- /// Session time when the window was collapsed to the card: "what did I miss" starts there.+ /// Session time when the window was collapsed to the card, and the topics and points the+ /// notes had then: the card offers what was added since.@State private var collapsedAt: Double = 0+ @State private var seenItems: Set<String> = []@State private var catchUp = false+ @State private var matchIndex = 0@State private var now = Date()+ @State private var width: CGFloat = 460+ @FocusState private var searchFocused: Boolprivate var session: Session? { store.session(store.liveID ?? engine.shownID) }private var live: Bool { store.liveID != nil }+ private var heard: Int { session?.lines.count ?? 0 }private let tick = Timer.publish(every: 1, on: .main, in: .common).autoconnect()var body: some View {@@ -102,24 +150,71 @@ struct NotesWindowView: View {banner.padding(.horizontal, 24).padding(.bottom, 4)if geo.size.width >= 760 {HStack(alignment: .top, spacing: 0) {- notesScroll.frame(maxWidth: .infinity)+ notesPane.frame(maxWidth: .infinity)Divider()transcript.padding(.horizontal, 20).padding(.top, 12).frame(maxWidth: .infinity)}} else if tab == "notes" {- notesScroll+ notesPane} else {transcript.padding(.horizontal, 24).padding(.top, 12)}- caption+ // The transcript shows what is being said in place; the caption is for the notes tab.+ if geo.size.width < 760 && tab == "notes" { caption }}}}.frame(width: geo.size.width, height: geo.size.height)+ .onAppear { width = geo.size.width }+ .onChange(of: geo.size.width) { _, w in width = w }}.background(Color.white).foregroundStyle(Palette.ink).onReceive(tick) { now = $0 }+ .onReceive(commands) { run($0) }+ }++ /// Commands from the app menu (纪要 / 显示 / 编辑).+ private func run(_ command: NotesWindowController.Command) {+ let card = width < 360+ switch command {+ case .catchUp:+ // From the full window: what was added in the last three minutes.+ if !card {+ collapsedAt = max(0, elapsed - 180)+ seenItems = items(before: collapsedAt)+ }+ catchUp = true+ setWidth(320, 420)+ case .search:+ if card { setWidth(460, 760) }+ tab = "transcript"+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { searchFocused = true }+ case .layout(.card):+ guard !card else { return }+ collapse()+ case .layout(.sidebar):+ setWidth(460, card ? 760 : nil)+ case .layout(.wide):+ setWidth(820, card ? 760 : nil)+ }+ }++ private func collapse() {+ collapsedAt = elapsed+ seenItems = items(before: .infinity)+ catchUp = false+ setWidth(320, 230)+ }++ /// Topic titles and points of the current notes said before a time (all of them for `.infinity`).+ private func items(before t: Double) -> Set<String> {+ var out: Set<String> = []+ for topic in engine.notes.topics {+ if topic.start < t { out.insert(topic.title) }+ for (i, p) in topic.points.enumerated() where (topic.pointTime(i) ?? topic.start) < t { out.insert(p) }+ }+ return out}// MARK: Header@@ -130,40 +225,83 @@ struct NotesWindowView: View {VStack(alignment: .leading, spacing: 6) {Text("实时纪要").font(.system(size: 24, weight: .bold))HStack(spacing: 6) {- if live { Circle().fill(Palette.accent).frame(width: 7, height: 7) }+ if live { LiveDot() }Text(statusLine).font(.system(size: 12)).foregroundStyle(Palette.tertiary).lineLimit(1)}}Spacer()+ if engine.state == .updating, !engine.notes.isEmpty {+ UpdatingPill().padding(.top, 4).padding(.trailing, 4)+ }iconButton(wide ? "rectangle.split.2x1.fill" : "rectangle.split.2x1", help: wide ? "收窄" : "纪要和原话并排") {setWidth(wide ? 460 : 820, nil)}- iconButton("minus", help: "收成小卡") {- collapsedAt = elapsed- catchUp = false- setWidth(320, 230)- }+ iconButton("minus", help: "收成小卡") { collapse() }}if !wide {HStack(spacing: 0) {segment("纪要", "notes")- segment("文字记录", "transcript")+ segment(engine.notes.isEmpty && heard > 0 ? "文字记录 · \(heard)" : "文字记录", "transcript")}.padding(4).background(RoundedRectangle(cornerRadius: 12).fill(Palette.fill))}if wide || tab == "transcript" {- HStack(spacing: 8) {- Image(systemName: "magnifyingglass").font(.system(size: 13)).foregroundStyle(Palette.tertiary)- TextField("搜索文字记录", text: $query).textFieldStyle(.plain).font(.system(size: 13))- }- .padding(.horizontal, 12).frame(height: 34)- .background(RoundedRectangle(cornerRadius: 10).fill(Palette.fill))+ searchField}}.padding(.horizontal, 24).padding(.top, 34).padding(.bottom, 12)}+ private var searchField: some View {+ HStack(spacing: 6) {+ Image(systemName: "magnifyingglass").font(.system(size: 13)).foregroundStyle(Palette.tertiary)+ TextField("在文字记录中搜索 ⌘F", text: $query).textFieldStyle(.plain).font(.system(size: 13))+ .focused($searchFocused)+ .onSubmit { step(1) }+ .onChange(of: query) { _, _ in matchIndex = 0 }+ if !query.isEmpty {+ Text(matches.isEmpty ? "无结果" : "\(currentIndex + 1) / \(matches.count)")+ .font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.tertiary)+ iconButton("chevron.up", help: "上一个") { step(-1) }.disabled(matches.isEmpty)+ iconButton("chevron.down", help: "下一个") { step(1) }.disabled(matches.isEmpty)+ iconButton("xmark", help: "清除") { query = "" }+ }+ }+ .padding(.leading, 12).padding(.trailing, 2).frame(height: 34)+ .background(RoundedRectangle(cornerRadius: 10).fill(searchFocused ? Color.white : Palette.fill))+ .overlay(RoundedRectangle(cornerRadius: 10).stroke(searchFocused ? Palette.accent : .clear, lineWidth: 1.5))+ }++ /// The query, plus every way the notes say that name was heard (江充 also finds 江松).+ private var searchTerms: [String] {+ let q = query.trimmingCharacters(in: .whitespaces)+ guard !q.isEmpty else { return [] }+ var out = [q]+ for t in engine.notes.terms {+ let forms = [t.name] + t.heard+ if forms.contains(where: { $0.localizedCaseInsensitiveContains(q) || q.localizedCaseInsensitiveContains($0) }) {+ out += forms.filter { !out.contains($0) }+ }+ }+ return out+ }++ private var matches: [String] {+ let terms = searchTerms+ guard !terms.isEmpty else { return [] }+ return (session?.lines ?? []).filter { l in+ terms.contains { l.src.localizedCaseInsensitiveContains($0) || (l.dst ?? "").localizedCaseInsensitiveContains($0) }+ }.map(\.id)+ }++ private var currentIndex: Int { matches.isEmpty ? 0 : min(matchIndex, matches.count - 1) }++ private func step(_ d: Int) {+ guard !matches.isEmpty else { return }+ matchIndex = (currentIndex + d + matches.count) % matches.count+ }+private func segment(_ title: String, _ id: String) -> some View {Button { tab = id } label: {Text(title).font(.system(size: 13, weight: tab == id ? .semibold : .regular))@@ -187,10 +325,15 @@ struct NotesWindowView: View {private var elapsed: Double { store.liveStart.map { now.timeIntervalSince($0) } ?? 0 }private var statusLine: String {- let clock = live ? "正在记录 · \(NotesEngine.clock(elapsed))" : (session.map { TranscriptExport.header($0) } ?? "没有进行中的会议")- guard let at = engine.notes.updatedAt else { return clock }+ if live {+ var parts = [(heard == 0 ? "正在听 · " : "正在记录 · ") + NotesEngine.clock(elapsed)]+ if heard > 0 { parts.append("\(heard) 句") }+ if !engine.notes.isEmpty, lastCovered > 0 { parts.append("纪要已更新至 \(NotesEngine.clock(lastCovered))") }+ return parts.joined(separator: " · ")+ }+ let clock = session.map { TranscriptExport.header($0) } ?? "没有进行中的会议"+ guard let at = engine.notes.updatedAt, engine.state != .updating else { return clock }let ago = Int(now.timeIntervalSince(at))- if engine.state == .updating { return clock + " · 正在更新" }return clock + " · " + (ago < 10 ? "刚刚更新" : ago < 60 ? "\(ago) 秒前更新" : "\(ago / 60) 分钟前更新")}@@ -202,13 +345,13 @@ struct NotesWindowView: View {case .noKey where session?.lines.isEmpty == false || live:keyEntrycase .invalidKey:- notice("key 失效了(令牌被删除,或免费额度用完),纪要停在 \(NotesEngine.clock(lastCovered))。", tint: Palette.errorPale) {- SoftButton("换一个 key", dark: true) { model.openSettings(.ai) }+ notice("key 已失效(令牌被删或免费额度用尽),纪要停留在 \(NotesEngine.clock(lastCovered))。", tint: Palette.errorPale) {+ SoftButton("更换 key", dark: true) { model.openSettings(.ai) }}case .rateLimited:- notice("请求太多,Ling 让等一下,过一会儿自动再试。纪要停在 \(NotesEngine.clock(lastCovered))。", tint: Palette.fill) { EmptyView() }+ notice("请求过于频繁,稍后会自动重试。纪要停留在 \(NotesEngine.clock(lastCovered))。", tint: Palette.fill) { EmptyView() }case .failed:- notice("这次没整理好,下一轮会再试。", tint: Palette.fill) { EmptyView() }+ notice("这轮没整理好,下一轮会自动重试。", tint: Palette.fill) { EmptyView() }default:EmptyView()}@@ -230,8 +373,8 @@ struct NotesWindowView: View {private var keyEntry: some View {VStack(alignment: .leading, spacing: 10) {- Text("纪要需要一个 API key").font(.system(size: 15, weight: .bold))- Text("文字记录照常在记。填上 Ling 的 key 后,从这场会已经说过的内容开始整理。")+ Text("生成纪要需要 API key").font(.system(size: 15, weight: .bold))+ Text("文字记录仍在正常保存。填入 Ling 的 key 后,会从头开始整理整场会议的内容。").font(.system(size: 12)).foregroundStyle(Palette.secondary).lineSpacing(2)HStack(spacing: 8) {SecureField("sk-…", text: $keyDraft)@@ -242,7 +385,7 @@ struct NotesWindowView: View {.onSubmit(saveKey)SoftButton("保存并开始", dark: true, action: saveKey)}- Button("去 Ling 拿 key ↗") {+ Button("获取 Ling key ↗") {if let url = URL(string: "https://chat.ant-ling.com/open") { NSWorkspace.shared.open(url) }}.buttonStyle(.plain).font(.system(size: 12)).foregroundStyle(Palette.secondary)@@ -262,39 +405,54 @@ struct NotesWindowView: View {// MARK: Content- private var notesScroll: some View {- ScrollView {- VStack(alignment: .leading, spacing: 0) {- if engine.notes.isEmpty {- emptyNotes- } else {- NotesContentView(notes: engine.notes, fresh: engine.fresh, live: live,- updating: engine.state == .updating,- summaryJustChanged: engine.summaryChangedAt.map { now.timeIntervalSince($0) < 20 } ?? false,- onJump: { t in jumpTo = t; tab = "transcript" })- }+ /// Notes, or what is happening before there are any: listening, writing the first version.+ @ViewBuilder+ private var notesPane: some View {+ if !engine.notes.isEmpty {+ notesScroll+ } else if engine.state == .noKey || engine.state == .invalidKey {+ Spacer()+ } else if live && heard == 0 {+ VStack {+ Spacer()+ NotesListeningView()+ Spacer()+ Spacer()+ }+ .frame(maxWidth: .infinity)+ } else if live || engine.generatingID == session?.id {+ ScrollView {+ NotesGeneratingView(heard: heard).padding(.horizontal, 24).padding(.vertical, 12)+ }+ } else {+ VStack {+ Spacer()+ Text(session == nil ? "没有进行中的会议" : "这场会议还没有纪要")+ .font(.system(size: 13)).foregroundStyle(Palette.tertiary)+ Spacer()+ Spacer()}- .padding(.horizontal, 24).padding(.vertical, 12)+ .frame(maxWidth: .infinity)}}- @ViewBuilder- private var emptyNotes: some View {- if engine.state == .noKey { EmptyView() } else {- VStack(alignment: .leading, spacing: 8) {- Text(engine.state == .updating ? "正在整理第一版纪要…" : "开始说话后,大约半分钟出第一版纪要")- .font(.system(size: 14, weight: .semibold))- Text("之后每 45 秒更新一次;会议结束时再整理一遍完整版。")- .font(.system(size: 12)).foregroundStyle(Palette.tertiary)- }- .padding(18).frame(maxWidth: .infinity, alignment: .leading)- .background(RoundedRectangle(cornerRadius: 18).fill(Palette.raised))+ private var notesScroll: some View {+ ScrollView {+ NotesContentView(notes: engine.notes, fresh: engine.fresh, live: live,+ updating: engine.state == .updating,+ summaryJustChanged: engine.summaryChangedAt.map { now.timeIntervalSince($0) < 20 } ?? false,+ coveredUntil: lastCovered > 0 ? lastCovered : nil,+ endedAt: session?.lines.last?.t,+ onJump: { t in jumpTo = t; tab = "transcript" })+ .padding(.horizontal, 24).padding(.vertical, 12)}}private var transcript: some View {- TranscriptListView(lines: session?.lines ?? [], topics: engine.notes.topics, query: query,- live: live, jumpTo: jumpTo)+ let ms = matches+ return TranscriptListView(lines: session?.lines ?? [], topics: engine.notes.topics, terms: searchTerms,+ currentMatch: ms.isEmpty ? nil : ms[currentIndex], live: live,+ partial: model.liveSource, partialTime: elapsed, jumpTo: jumpTo)}@ViewBuilder@@ -320,35 +478,75 @@ struct NotesWindowView: View {private var card: some View {VStack(alignment: .leading, spacing: 10) {HStack(spacing: 6) {- if live { Circle().fill(Palette.accent).frame(width: 7, height: 7) }- Text(currentTopic.map { (live ? "正在讲 · " : "最后一个议题 · ") + "\(NotesEngine.clock($0.start)) 起" } ?? (live ? "正在记录" : "实时纪要"))- .font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ if catchUp {+ Text("收起之后 · \(NotesEngine.clock(collapsedAt)) – \(NotesEngine.clock(elapsed))")+ .font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.tertiary)+ } else {+ if live { LiveDot() }+ Text(currentTopic.map { (live ? "正在讲 · " : "最后一个议题 · ") + "\(NotesEngine.clock($0.start)) 起" } ?? (live ? "正在记录" : "实时纪要"))+ .font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ }Spacer()iconButton("arrow.up.left.and.arrow.down.right", help: "展开纪要") { setWidth(460, 760) }}if catchUp {- Text("你错过的 \(missedSpan)").font(.system(size: 15, weight: .bold))+ Text("这 \(span) 讲了").font(.system(size: 17, weight: .bold))ScrollView {- VStack(alignment: .leading, spacing: 6) {- ForEach(missed, id: \.self) { p in- HStack(alignment: .firstTextBaseline, spacing: 6) {- Circle().fill(Palette.ink.opacity(0.55)).frame(width: 4, height: 4)- Text(p).font(.system(size: 13)).lineSpacing(2)+ VStack(alignment: .leading, spacing: 12) {+ ForEach(added, id: \.topic.id) { item in+ VStack(alignment: .leading, spacing: 5) {+ HStack(alignment: .firstTextBaseline, spacing: 8) {+ Text(NotesEngine.clock(item.topic.start)).font(.system(size: 12).monospacedDigit())+ .foregroundStyle(Palette.tertiary).frame(width: 38, alignment: .leading)+ Text(item.topic.title).font(.system(size: 14, weight: .bold))+ }+ if !item.points.isEmpty {+ Text(item.points.joined(separator: ";")).font(.system(size: 13))+ .foregroundStyle(Palette.secondary).lineSpacing(2).padding(.leading, 46)+ .fixedSize(horizontal: false, vertical: true)+ }}}+ if added.isEmpty {+ Text("纪要里还没有新内容").font(.system(size: 13)).foregroundStyle(Palette.tertiary)+ }}+ .frame(maxWidth: .infinity, alignment: .leading)}HStack(spacing: 8) {- SoftButton("展开完整纪要", dark: true) { setWidth(460, 760) }- SoftButton("知道了") { catchUp = false; collapsedAt = elapsed }+ SoftButton("展开纪要", dark: true) { setWidth(460, 760) }+ SoftButton("看过了") {+ catchUp = false+ collapsedAt = elapsed+ seenItems = items(before: .infinity)+ setWidth(320, 230)+ }}} else {- Text(currentTopic?.title ?? "还没有纪要").font(.system(size: 17, weight: .bold)).lineLimit(2)- if let last = currentTopic?.points.last {+ Text(currentTopic?.title ?? (!live ? "还没有纪要" : heard == 0 ? "正在听" : "正在生成纪要…"))+ .font(.system(size: 17, weight: .bold)).lineLimit(2)+ if addedCount.points == 0 && addedCount.topics == 0, let last = currentTopic?.points.last {Text(last).font(.system(size: 13)).foregroundStyle(Palette.secondary).lineLimit(2)}Spacer(minLength: 0)- SoftButton("我刚走神了,错过什么?", dark: true) { catchUp = true }+ if addedCount.topics + addedCount.points > 0 {+ // Only says something when there is something new.+ Button { catchUp = true; setWidth(320, 420) } label: {+ HStack {+ Text(addedLabel).font(.system(size: 13, weight: .semibold)).lineLimit(1)+ Spacer(minLength: 4)+ Image(systemName: "chevron.right").font(.system(size: 12, weight: .bold))+ }+ .foregroundStyle(Palette.accentInk)+ .padding(.horizontal, 14).frame(height: 40)+ .background(RoundedRectangle(cornerRadius: 12).fill(Palette.accentPale))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ } else if collapsedAt > 0 || live {+ Text("收起 \(span) · " + (live ? "还在讲这个" : "没有新内容"))+ .font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ }}}.padding(.horizontal, 18).padding(.top, 30).padding(.bottom, 16)@@ -356,16 +554,29 @@ struct NotesWindowView: View {private var currentTopic: NoteTopic? { engine.notes.topics.last }- private var missed: [String] {- let topics = engine.notes.topics- let since = topics.filter { $0.start >= collapsedAt - 5 }- let pool = since.isEmpty ? Array(topics.suffix(1)) : since- let items = pool.flatMap { t in ["\(t.title):\(t.summary.isEmpty ? t.points.first ?? "" : t.summary)"] + t.points.prefix(2) }- return items.isEmpty ? ["这段时间还没有新的纪要"] : items+ /// Topics with what was added to them since the card was collapsed.+ private var added: [(topic: NoteTopic, points: [String])] {+ engine.notes.topics.compactMap { t in+ let points = t.points.filter { !seenItems.contains($0) }+ return seenItems.contains(t.title) && points.isEmpty ? nil : (t, points)+ }+ }++ private var addedCount: (topics: Int, points: Int) {+ let a = added+ return (a.filter { !seenItems.contains($0.topic.title) }.count, a.reduce(0) { $0 + $1.points.count })+ }++ private var addedLabel: String {+ let c = addedCount+ var parts: [String] = []+ if c.topics > 0 { parts.append("\(c.topics) 个议题") }+ if c.points > 0 { parts.append("\(c.points) 条要点") }+ return "收起后新增 " + parts.joined(separator: "、")}- private var missedSpan: String {+ private var span: String {let s = max(0, Int(elapsed - collapsedAt))- return s < 60 ? "\(s) 秒" : "\(s / 60) 分 \(s % 60) 秒"+ return s < 60 ? "\(s) 秒" : "\(s / 60) 分钟"}}diff --git a/Sources/LiveSubs/Settings.swift b/Sources/LiveSubs/Settings.swiftindex cadaa1c..d6da83e 100644--- a/Sources/LiveSubs/Settings.swift+++ b/Sources/LiveSubs/Settings.swift@@ -57,8 +57,9 @@ final class AppSettings: ObservableObject {@Published var displayMode: String {didSet { save() }}- /// Voice for speak-back: "system" or "ming" (Ming TTS through the Ling key).- @Published var speakVoice: String {+ /// The voice the room hears, per language ("en" → "ming:US_Emma", "system:<id>" or "clone").+ /// A language not listed uses `VoiceCatalog.defaultID`.+ @Published var speakVoices: [String: String] {didSet { save() }}/// Ling model for notes and translation.@@ -66,6 +67,11 @@ final class AppSettings: ObservableObject {didSet { save() }}+ /// Record per-sentence timings (never text) and show the 诊断 tab. On by default in dev builds.+ @Published var diagnostics: Bool {+ didSet { save() }+ }+var debug: Bool { defaults.bool(forKey: "debug") }init() {@@ -88,7 +94,8 @@ final class AppSettings: ObservableObject {toggleKey = Shortcut(stored: defaults.string(forKey: "toggleKey")) ?? .defaultToggleaiModel = defaults.string(forKey: "aiModel") ?? "Ling-3.1-flash"displayMode = defaults.string(forKey: "displayMode") ?? "notes"- speakVoice = defaults.string(forKey: "speakVoice") ?? "system"+ speakVoices = defaults.dictionary(forKey: "speakVoices") as? [String: String] ?? [:]+ diagnostics = defaults.object(forKey: "diagnostics") as? Bool ?? DevBuild.isDev}private func save() {@@ -108,7 +115,8 @@ final class AppSettings: ObservableObject {defaults.set(toggleKey.stored, forKey: "toggleKey")defaults.set(aiModel, forKey: "aiModel")defaults.set(displayMode, forKey: "displayMode")- defaults.set(speakVoice, forKey: "speakVoice")+ defaults.set(speakVoices, forKey: "speakVoices")+ defaults.set(diagnostics, forKey: "diagnostics")}/// Target language. "Follow system" uses the first system language thatdiff --git a/Sources/LiveSubs/SettingsWindow.swift b/Sources/LiveSubs/SettingsWindow.swiftindex 2177c92..16b8194 100644--- a/Sources/LiveSubs/SettingsWindow.swift+++ b/Sources/LiveSubs/SettingsWindow.swift@@ -3,24 +3,24 @@ import Carbon.HIToolboximport SwiftUIenum SettingsSection: String, CaseIterable, Identifiable {- case listen, speak, overlay, records, ai+ case overlay, speak, records, ai, diagnosticsvar id: String { rawValue }var title: String {switch self {- case .listen: "听"- case .speak: "我说话也翻译"case .overlay: "显示"+ case .speak: "同声传译"case .records: "会议记录"case .ai: "AI 服务"+ case .diagnostics: "诊断"}}var icon: String {switch self {- case .listen: "waveform"- case .speak: "mic"case .overlay: "captions.bubble"+ case .speak: "mic"case .records: "doc.text"case .ai: "key"+ case .diagnostics: "waveform.path.ecg"}}}@@ -144,7 +144,7 @@ struct ShortcutField: View {.contentShape(Rectangle())}.buttonStyle(.plain)- .help(recording ? "按 esc 取消" : "点一下,换成别的按键")+ .help(recording ? "按 esc 取消" : "点击更换按键")}if let error {Text(error).font(.system(size: 11)).foregroundStyle(Palette.accentInk)@@ -203,7 +203,7 @@ struct TalkKeyPermissionRow: View {@ObservedObject var model: AppModelvar body: some View {SettingsRow(title: "还差一步:允许“输入监控”",- detail: "按住右 ⌥ 要用到它。在系统设置里打开 \(appDisplayName),回到这里就生效") {+ detail: "“按住右 ⌥ 说话”需要此权限。请在系统设置中勾选 \(appDisplayName),返回此处即可生效") {SoftButton("去允许", dark: true) { model.allowTalkKey() }}}@@ -259,7 +259,7 @@ struct MicSetupCard: View {step(1, "安装", "输一次电脑密码", done: onDisk,active: installer.state == .downloading || installer.state == .installing,activeText: installer.state == .downloading ? "正在下载…" : "正在安装…")- step(2, "让系统认出它", "声音会断一下,约 1 秒", done: loaded,+ step(2, "让系统认出它", "声音会短暂中断约 1 秒", done: loaded,active: installer.state == .reloading, activeText: "正在让系统认出它…")step(3, "试音", "自动播一句,确认对方听得到", done: installer.passed,active: installer.state == .testing, activeText: "正在试音…")@@ -329,7 +329,7 @@ struct TestResultView: View {(Text("对方会听到:") + Text(result.text.isEmpty ? "一段声音" : "“\(result.text)”").bold()).font(.system(size: 12)).foregroundStyle(Palette.ink)} else {- Text(result.problem ?? "虚拟麦克风里没收到声音,再试一次").font(.system(size: 12)).foregroundStyle(Palette.accentInk)+ Text(result.problem ?? "虚拟麦克风未收到声音,请再试一次").font(.system(size: 12)).foregroundStyle(Palette.accentInk)}Spacer(minLength: 0)}@@ -352,11 +352,11 @@ struct SettingsView: View {VStack(alignment: .leading, spacing: 16) {Text(model.settingsSection.title).font(.system(size: 20, weight: .bold)).foregroundStyle(Palette.ink)switch model.settingsSection {- case .listen: listencase .speak: speakcase .overlay: overlaycase .records: recordscase .ai: AISettingsView(model: model, ling: model.ling, settings: settings)+ case .diagnostics: DiagnosticsView(diagnostics: model.diagnostics, model: settings.aiModel)}}.padding(.leading, 12).padding(.trailing, 28).padding(.top, 40).padding(.bottom, 28)@@ -369,8 +369,11 @@ struct SettingsView: View {private var sidebar: some View {VStack(alignment: .leading, spacing: 2) {- ForEach(SettingsSection.allCases) { s in+ ForEach(SettingsSection.allCases.filter { $0 != .diagnostics || settings.diagnostics }) { s inlet on = s == model.settingsSection+ if s == .diagnostics {+ Rectangle().fill(Palette.line).frame(height: 1).padding(.horizontal, 10).padding(.vertical, 6)+ }Button { model.settingsSection = s } label: {HStack(spacing: 10) {Image(systemName: s.icon).font(.system(size: 13))@@ -389,12 +392,25 @@ struct SettingsView: View {.buttonStyle(.plain)}Spacer()+ // Diagnostics is for chasing slowness: off it leaves no trace in the sidebar.+ HStack(spacing: 8) {+ Text("诊断").font(.system(size: 12)).foregroundStyle(settings.diagnostics ? Palette.ink : Palette.secondary)+ Toggle("诊断", isOn: Binding(get: { settings.diagnostics }, set: { model.setDiagnostics($0) }))+ .toggleStyle(.switch).labelsHidden().controlSize(.mini).tint(Palette.ink)+ Spacer()+ Text(Self.version).font(.system(size: 11).monospacedDigit()).foregroundStyle(Palette.tertiary)+ }+ .padding(.horizontal, 10).padding(.top, 10)+ .overlay(alignment: .top) { Rectangle().fill(Palette.line).frame(height: 1) }}.padding(.horizontal, 10).padding(.top, 44).padding(.bottom, 14)}+ private static let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? ""+// MARK: Sections+ /// Who is heard and what they're translated into: the top of the 显示 page.private var listen: some View {SettingsCard {SettingsRow(title: "听到") {@@ -419,14 +435,16 @@ struct SettingsView: View {private var speak: some View {VStack(alignment: .leading, spacing: 14) {+ Text("按住说话,松开后约 2 秒,对方听到译文").font(.system(size: 12)).foregroundStyle(Palette.secondary)+ .padding(.top, -8)SettingsCard { MicSetupCard(installer: installer, deviceName: model.virtualMic?.name) }SettingsCard {- SettingsRow(title: "我说话也翻译") {- Toggle("我说话也翻译", isOn: Binding(get: { settings.speakEnabled }, set: { model.enableSpeaking($0) }))+ SettingsRow(title: "把我的话翻译给对方听") {+ Toggle("把我说的翻译给对方", isOn: Binding(get: { settings.speakEnabled }, set: { model.enableSpeaking($0) })).toggleStyle(.switch).labelsHidden().controlSize(.small).tint(Palette.ink)}SettingsRow(title: "按住说话",- detail: settings.talkKey.isRightOption ? "只按右边的 ⌥;和别的键一起按不算" : nil) {+ detail: settings.talkKey.isRightOption ? "单独按住右侧 ⌥;与其他键同时按不会触发" : nil) {ShortcutField(model: model, role: .talk)}if settings.speakEnabled && model.talkNeedsPermission { TalkKeyPermissionRow(model: model) }@@ -442,15 +460,16 @@ struct SettingsView: View {settings.speakTo = $0}}- SettingsRow(title: "声音送到", divider: false) {+ SettingsRow(title: "声音输出到", divider: false) {PillMenu(value: outputName,options: [("", "虚拟麦克风(自动)")] + model.outputs.map { ($0.uid, $0.name) }) {settings.speakOutput = $0}}}- Text("在会议软件里,把麦克风选成「\(model.virtualMic?.name ?? "BlackHole 2ch")」。")+ Text("在会议软件中,将麦克风选为「\(model.virtualMic?.name ?? "BlackHole 2ch")」。").font(.system(size: 12)).foregroundStyle(Palette.secondary).padding(.horizontal, 4)+ VoiceSection(model: model, settings: settings, ling: model.ling).padding(.top, 6)}}@@ -461,8 +480,9 @@ struct SettingsView: View {private var overlay: some View {VStack(alignment: .leading, spacing: 14) {+ listenSettingsCard {- SettingsRow(title: "听的时候显示", detail: "选哪个都会照样记录、照样出纪要") {+ SettingsRow(title: "听的时候显示", detail: "选择任意模式都会正常保存记录、生成纪要") {Picker("显示方式", selection: Binding(get: { settings.displayMode }, set: { model.setDisplayMode($0) })) {Text("实时纪要").tag("notes")Text("字幕条").tag("bar")@@ -476,10 +496,10 @@ struct SettingsView: View {}Text("字幕条").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.secondary).padding(.top, 4)SettingsCard {- SettingsRow(title: "字幕条出现") {+ SettingsRow(title: "字幕条显示时机") {Picker("显示", selection: Binding(get: { settings.overlayAuto }, set: { model.setOverlayAuto($0) })) {- Text("说话时").tag(true)- Text("一直").tag(false)+ Text("有人说话时").tag(true)+ Text("始终显示").tag(false)}.pickerStyle(.segmented).labelsHidden().frame(width: 140)}@@ -493,7 +513,7 @@ struct SettingsView: View {.pickerStyle(.segmented).labelsHidden().frame(width: 140)}}- SettingsRow(title: "位置和大小", detail: "鼠标停住不动可拖动,拖右下角缩放", divider: false) {+ SettingsRow(title: "位置和大小", detail: "鼠标悬停可拖动位置,拖拽右下角可缩放大小", divider: false) {SoftButton("恢复默认") { model.overlay.resetPosition() }}}diff --git a/Sources/LiveSubs/Shortcuts.swift b/Sources/LiveSubs/Shortcuts.swiftindex b144d2c..4c4c2fb 100644--- a/Sources/LiveSubs/Shortcuts.swift+++ b/Sources/LiveSubs/Shortcuts.swift@@ -86,7 +86,7 @@ struct Shortcut: Equatable {/// most Mac keyboards. So a combination needs ⌃ or ⌘.var typingProblem: String? {if isRightOption { return nil }- if modifiers & (controlKey | cmdKey) == 0 { return "要带上 ⌃ 或 ⌘,不然会挡住打字" }+ if modifiers & (controlKey | cmdKey) == 0 { return "请包含 ⌃ 或 ⌘,否则会影响正常打字" }return nil}diff --git a/Sources/LiveSubs/SpeakEngine.swift b/Sources/LiveSubs/SpeakEngine.swiftindex 87f165b..2a5ef8b 100644--- a/Sources/LiveSubs/SpeakEngine.swift+++ b/Sources/LiveSubs/SpeakEngine.swift@@ -48,6 +48,16 @@ enum AudioDevices {}static var virtualMic: OutputDevice? { outputs().first(where: \.isVirtualMic) }++ /// The system output (speakers or headphones): voice previews play here, not into the room.+ static var defaultOutput: OutputDevice? {+ var id = AudioObjectID(0)+ var size = UInt32(MemoryLayout<AudioObjectID>.size)+ var addr = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDefaultOutputDevice,+ mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain)+ guard AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &addr, 0, nil, &size, &id) == noErr else { return nil }+ return outputs().first { $0.id == id }+ }}// MARK: - Speak engine@@ -63,7 +73,10 @@ final class SpeakEngine {var onUtterance: ((_ source: String, _ translation: String, _ from: String, _ to: String, _ secondsAgo: Double) -> Void)?var onStatus: ((String) -> Void)?/// Translator shared with the listening side.- var translate: ((_ text: String, _ from: String, _ to: String) async -> String?)?+ var translate: ((_ text: String, _ from: String, _ to: String, _ trace: TranslateTrace) async -> String?)?+ /// Diagnostics: key released → transcript → translation → voice finished.+ var onTiming: ((SentenceTiming) -> Void)?+ private var releasedAt: Date?/// Language the room speaks (for "follow the room").var roomLanguage: (() -> String?)?@@ -196,7 +209,7 @@ final class SpeakEngine {guard settings.speakEnabled, phase == .idle || phase == .speaking else { return }guard let format = analyzerFormat, let input = beginUtterance() else {Task { await prepare() }- onStatus?("语音识别还在准备,请再按一次")+ onStatus?("语音识别仍在准备中,请再按一次")return}debugLog("speak: press began")@@ -222,6 +235,7 @@ final class SpeakEngine {func pressEnded() {guard phase == .listening else { return }debugLog("speak: press ended")+ releasedAt = Date()// Keep the mic open a moment so the last syllable isn't cut off.DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] inMainActor.assumeIsolated { self?.finishUtterance() }@@ -298,8 +312,11 @@ final class SpeakEngine {guard let u = utterance else { phase = .idle; return }utterance = nilu.input.finish()+ let released = releasedAt ?? Date()+ releasedAt = nilTask {let text = await u.text.value+ let textAt = Date()finals = []volatile = ""guard !text.isEmpty else {@@ -312,10 +329,19 @@ final class SpeakEngine {onLive?(.translating, text, "")// Never speak the untranslated original into the room: if translation// fails, say so on the bar and send nothing.- guard let translated = await translate?(text, from, to) else {+ let trace = TranslateTrace()+ let result = await translate?(text, from, to, trace)+ let translatedAt = Date()+ @MainActor func timing(voice: Double?) -> SentenceTiming {+ SentenceTiming(at: textAt, side: "me", chars: text.count, recognize: textAt.timeIntervalSince(released),+ queue: trace.lingQueue, translate: translatedAt.timeIntervalSince(textAt), voice: voice,+ failed: trace.failedSeconds, via: result == nil ? "none" : trace.via, fallbacks: trace.fallbacks)+ }+ guard let translated = result else {debugLog("speak: translation failed, nothing sent")+ onTiming?(timing(voice: nil))phase = .idle- onLive?(.idle, text, "翻译失败,这句没有发出")+ onLive?(.idle, text, "翻译失败,这句话未发送")return}contentLog("SPEAK [\(from)→\(to)] \(text) => \(translated)")@@ -323,6 +349,7 @@ final class SpeakEngine {phase = .speakingonLive?(.speaking, text, translated)await speak(translated, language: to)+ onTiming?(timing(voice: Date().timeIntervalSince(translatedAt)))if phase == .speaking { phase = .idle }onLive?(.idle, text, translated)}@@ -330,7 +357,8 @@ final class SpeakEngine {// MARK: Voice output- private func voice(for code: String) -> AVSpeechSynthesisVoice? {+ private func voice(for code: String, identifier: String? = nil) -> AVSpeechSynthesisVoice? {+ if let identifier, let v = AVSpeechSynthesisVoice(identifier: identifier) { return v }let lang = code == "zh-CN" ? "zh-CN" : code == "zh-TW" ? "zh-TW" : codelet voices = AVSpeechSynthesisVoice.speechVoices().filter { $0.language.hasPrefix(lang) }return voices.max(by: { $0.quality.rawValue < $1.quality.rawValue }) ?? AVSpeechSynthesisVoice(language: lang)@@ -342,9 +370,9 @@ final class SpeakEngine {return all.first(where: \.isVirtualMic)}- private func synthesize(_ text: String, language: String) async -> [AVAudioPCMBuffer] {+ private func synthesize(_ text: String, language: String, voiceID: String?) async -> [AVAudioPCMBuffer] {let u = AVSpeechUtterance(string: text)- u.voice = voice(for: language)+ u.voice = voice(for: language, identifier: voiceID)return await withCheckedContinuation { cont invar buffers: [AVAudioPCMBuffer] = []var done = false@@ -361,12 +389,27 @@ final class SpeakEngine {}/// `device` overrides the chosen output (the virtual mic sound test).- /// Set by the app: Ming's voice as a PCM stream, when chosen and a key is set.- var mingVoice: ((String) -> AsyncThrowingStream<Data, Error>)?+ /// How a language is voiced: a PCM stream (Ming's built-in voices or the user's cloned one) or+ /// a voice on this Mac (nil: the best one for the language).+ enum VoiceRoute {+ case stream((String) -> AsyncThrowingStream<Data, Error>)+ case system(String?)+ }- func speak(_ text: String, language: String, device override: OutputDevice? = nil) async {- if let ming = mingVoice, await speakStream(ming(text), device: override ?? outputDevice()) { return }- let buffers = await synthesize(text, language: language)+ /// Set by the app: the voice chosen for a language.+ var route: ((String) -> VoiceRoute)?++ /// Returns after the audio has played. A stream that fails before any audio falls back to the+ /// Mac's voice, so the room always hears the sentence.+ func speak(_ text: String, language: String, device override: OutputDevice? = nil, route forced: VoiceRoute? = nil) async {+ var voiceID: String?+ switch forced ?? route?(language) ?? .system(nil) {+ case .stream(let make):+ if await speakStream(make(text), device: override ?? outputDevice()) { return }+ case .system(let id):+ voiceID = id+ }+ let buffers = await synthesize(text, language: language, voiceID: voiceID)guard let first = buffers.first else { return }if let url = debugOutputURL, let f = AudioFileWriter.open(url, format: first.format) {for b in buffers { try? f.write(from: b) }diff --git a/Sources/LiveSubs/Translator.swift b/Sources/LiveSubs/Translator.swiftindex a316331..fcaaa38 100644--- a/Sources/LiveSubs/Translator.swift+++ b/Sources/LiveSubs/Translator.swift@@ -63,32 +63,49 @@ final class TranslationService {init(ling: LingClient) { self.ling = ling }- func translate(_ text: String, source: String, target: String, kind: Kind) async -> String? {+ /// `trace`, when given, collects which providers were tried, how long each took and why it+ /// fell through (diagnostics; never the text).+ func translate(_ text: String, source: String, target: String, kind: Kind, trace: TranslateTrace? = nil) async -> String? {if source == target { return text }if kind != .draft, ling.usable {- if let out = await viaLing(text, source: source, target: target, kind: kind) {+ let started = Date()+ let (out, failure) = await viaLing(text, source: source, target: target, kind: kind, trace: trace)+ trace?.attempts.append(.init(provider: "ling", seconds: Date().timeIntervalSince(started), failure: out == nil ? failure : nil))+ if let out {debugLog("translate via=ling kind=\(kind)")return out}}if Date() >= googleBackoffUntil {+ let started = Date()do {let out = try await GoogleTranslator.translate(text, source: source, target: target)+ trace?.attempts.append(.init(provider: "google", seconds: Date().timeIntervalSince(started), failure: nil))if kind != .draft { debugLog("translate via=google kind=\(kind)") }return out} catch {debugLog("translate google failed: \(error)")+ var reason = "error"+ if case TranslateFailure.badResponse(let code) = error { reason = code == 429 ? "rateLimited" : "http\(code)" }+ if (error as? URLError)?.code == .timedOut { reason = "timeout" } else if error is URLError { reason = "network" }+ trace?.attempts.append(.init(provider: "google", seconds: Date().timeIntervalSince(started), failure: reason))if case TranslateFailure.badResponse(429) = error { googleBackoffUntil = Date().addingTimeInterval(10) }}+ } else {+ trace?.attempts.append(.init(provider: "google", seconds: 0, failure: "rateLimited"))}+ let started = Date()if let out = await viaApple(text, source: source, target: target) {+ trace?.attempts.append(.init(provider: "apple", seconds: Date().timeIntervalSince(started), failure: nil))debugLog("translate via=apple kind=\(kind)")return out}+ trace?.attempts.append(.init(provider: "apple", seconds: Date().timeIntervalSince(started), failure: "unavailable"))return nil}- private func viaLing(_ text: String, source: String, target: String, kind: Kind) async -> String? {+ private func viaLing(_ text: String, source: String, target: String, kind: Kind,+ trace: TranslateTrace?) async -> (String?, String) {let from = source == "auto" ? "the spoken language" : Self.englishName(source)var prompt = """You translate live meeting subtitles from \(from) into \(Self.englishName(target)).@@ -99,11 +116,12 @@ final class TranslationService {prompt += "\nSubtitle: " + textdo {let out = try await ling.chat(content: prompt, instruction: "Translate.", priority: kind == .speak ? .speak : .translate,- maxTokens: 400, timeout: kind == .speak ? 10 : 6)- return out.isEmpty ? nil : out+ maxTokens: 400, timeout: kind == .speak ? 10 : 6,+ onQueued: { [weak trace] in trace?.lingQueue += $0 })+ return (out.isEmpty ? nil : out, "empty")} catch {debugLog("translate ling failed: \(error)")- return nil+ return (nil, (error as? LingClient.Failure).map(LingClient.name) ?? "error")}}diff --git a/Sources/LiveSubs/Views.swift b/Sources/LiveSubs/Views.swiftindex 1ac8793..de5f0ff 100644--- a/Sources/LiveSubs/Views.swift+++ b/Sources/LiveSubs/Views.swift@@ -20,6 +20,8 @@ enum Palette {static let okPale = Color(red: 0.906, green: 0.961, blue: 0.925)static let error = Color(red: 0.706, green: 0.137, blue: 0.094)static let errorPale = Color(red: 0.992, green: 0.925, blue: 0.918)+ /// Headings over placeholder shapes while notes are being written.+ static let placeholder = Color(red: 0.722, green: 0.741, blue: 0.776)}struct LogoTile: View {@@ -133,7 +135,7 @@ struct MenuPanelView: View {HStack(alignment: .top, spacing: 12) {VStack(alignment: .leading, spacing: 4) {- Text("我说话也翻译").font(.system(size: 14, weight: .semibold)).foregroundStyle(Palette.ink)+ Text("同声传译").font(.system(size: 14, weight: .semibold)).foregroundStyle(Palette.ink)HStack(spacing: 5) {Text("按住").foregroundStyle(Palette.secondary)KeyCap(settings.talkKey.display)@@ -143,12 +145,12 @@ struct MenuPanelView: View {.font(.system(size: 12))}Spacer()- Toggle("我说话也翻译", isOn: Binding(get: { settings.speakEnabled }, set: { model.enableSpeaking($0) }))+ Toggle("同声传译", isOn: Binding(get: { settings.speakEnabled }, set: { model.enableSpeaking($0) })).toggleStyle(.switch).labelsHidden().tint(Palette.ink)}if settings.speakEnabled && model.virtualMic == nil {HStack {- Text("虚拟麦克风还没设置好,对方听不到").font(.system(size: 12)).foregroundStyle(Palette.accentInk)+ Text("虚拟麦克风尚未设置好,对方听不到你的声音").font(.system(size: 12)).foregroundStyle(Palette.accentInk)Spacer()SoftButton("设置") { model.openSettings(.speak) }}@@ -171,7 +173,7 @@ struct MenuPanelView: View {}if settings.displayMode == "notes" {HStack {- Text(model.ling.hasKey ? "纪要、文字记录和字幕都在一个窗口里" : "填上 API key 才有纪要;文字记录照常")+ Text(model.ling.hasKey ? "纪要、文字记录和字幕都在一个窗口里" : "填入 API key 后可生成纪要;文字记录照常保存").font(.system(size: 12)).foregroundStyle(Palette.secondary)Spacer()SoftButton("打开") { model.openNotesWindow() }@@ -182,8 +184,8 @@ struct MenuPanelView: View {Text("字幕条").font(.system(size: 12)).foregroundStyle(Palette.secondary)Spacer()Picker("字幕条", selection: Binding(get: { settings.overlayAuto }, set: { model.setOverlayAuto($0) })) {- Text("说话时显示").tag(true)- Text("一直显示").tag(false)+ Text("有人说话时显示").tag(true)+ Text("始终显示").tag(false)}.pickerStyle(.segmented).labelsHidden().frame(width: 170)}@@ -306,7 +308,7 @@ struct MainWindowView: View {}}if store.sessions.isEmpty {- Text("打开字幕后,每场会议会自动记在这里。")+ Text("开启字幕后,每场会议都会自动保存在这里。").font(.system(size: 12)).foregroundStyle(Palette.secondary).padding(.top, 8)Spacer()@@ -445,7 +447,7 @@ struct MainWindowView: View {VStack(spacing: 10) {LogoTile(size: 44)Text("还没有会议记录").font(.system(size: 15, weight: .semibold))- Text("打开字幕后,每场会议会自动保存一份双语稿子。")+ Text("开启字幕后,每场会议都会自动保存一份双语记录。").font(.system(size: 13)).foregroundStyle(Palette.secondary)}.frame(maxWidth: .infinity, maxHeight: .infinity)@@ -501,12 +503,14 @@ struct SessionNotesView: View {VStack(alignment: .leading, spacing: 0) {if let notes, !notes.isEmpty {NotesContentView(notes: notes, fresh: live ? engine.fresh : [], live: live, onJump: onJump)+ } else if generating || (live && ling.hasKey && !session.lines.isEmpty) {+ NotesGeneratingView(heard: session.lines.count)} else {VStack(alignment: .leading, spacing: 10) {Text(generating ? "正在整理纪要…" : live ? "纪要会在会议进行中自动生成" : "这场会议还没有纪要").font(.system(size: 15, weight: .bold))- Text(ling.hasKey ? "用 Ling 从文字记录整理总结、议题、结论和人名,大约半分钟。"- : "在 设置 › AI 服务 填上 Ling 的 API key 后就能生成。")+ Text(ling.hasKey ? "使用 Ling 将文字记录整理为总结、议题、结论和人名,约需半分钟。"+ : "前往 设置 › AI 服务 填入 Ling 的 API key 后即可生成。").font(.system(size: 13)).foregroundStyle(Palette.secondary)if !live {HStack(spacing: 8) {diff --git a/Sources/LiveSubs/VirtualMic.swift b/Sources/LiveSubs/VirtualMic.swiftindex 32d41b6..b8dd345 100644--- a/Sources/LiveSubs/VirtualMic.swift+++ b/Sources/LiveSubs/VirtualMic.swift@@ -128,7 +128,7 @@ final class VirtualMicInstaller: ObservableObject {let digest = SHA256.hash(data: try Data(contentsOf: tmp)).map { String(format: "%02x", $0) }.joined()guard digest == Self.packageSHA256 else {debugLog("virtual mic: checksum mismatch \(digest)")- state = .failed("安装包校验没通过,已停止")+ state = .failed("安装包校验未通过,已中止安装")return nil}let dir = FileManager.default.temporaryDirectory.appendingPathComponent("LiveSubsMic", isDirectory: true)@@ -153,7 +153,7 @@ final class VirtualMicInstaller: ObservableObject {guard let errorInfo else { return true }let code = errorInfo[NSAppleScript.errorNumber] as? Int ?? 0debugLog("virtual mic: privileged command error \(errorInfo)")- state = code == -128 ? .idle : .failed("没有完成,可以再试一次")+ state = code == -128 ? .idle : .failed("安装未完成,请再试一次")return false}@@ -163,7 +163,7 @@ final class VirtualMicInstaller: ObservableObject {}generation += 1guard isLoaded else {- state = .failed(isOnDisk ? "系统还没认出它,点“让系统认出它”再试一次" : "安装没有完成,可以再试一次")+ state = .failed(isOnDisk ? "系统还没认出它,点“让系统认出它”再试一次" : "安装未完成,请再试一次")return}debugLog("virtual mic: loaded")@@ -202,10 +202,10 @@ enum LoopbackTest {let text = loud ? await transcribe(buffers, locale: "en-US") : ""// Any real signal counts; the transcript is shown so people can judge it themselves.return .init(heard: loud, text: text, levels: levels,- problem: loud ? nil : buffers.isEmpty ? "虚拟麦克风没有送来声音,再试一次" : nil)+ problem: loud ? nil : buffers.isEmpty ? "虚拟麦克风未收到声音,请再试一次" : nil)}- private static func transcribe(_ buffers: [AVAudioPCMBuffer], locale: String) async -> String {+ static func transcribe(_ buffers: [AVAudioPCMBuffer], locale: String) async -> String {let t = SpeechTranscriber(locale: Locale(identifier: locale), transcriptionOptions: [],reportingOptions: [], attributeOptions: [])guard await AssetInventory.status(forModules: [t]) == .installed,diff --git a/Sources/LiveSubs/VoicePicker.swift b/Sources/LiveSubs/VoicePicker.swiftnew file mode 100644index 0000000..2fbca7d--- /dev/null+++ b/Sources/LiveSubs/VoicePicker.swift@@ -0,0 +1,397 @@+import AVFoundation+import SwiftUI++/// Settings › 同声传译 › 对方听到的声音: one voice per language the room may speak, each playable,+/// plus the user's own cloned voice.+struct VoiceSection: View {+ @ObservedObject var model: AppModel+ @ObservedObject var settings: AppSettings+ @ObservedObject var ling: LingClient++ @State private var tab: String?+ @State private var recording = false+ /// Bumped when the recording changes on disk.+ @State private var cloneVersion = 0++ private var roomKey: String { VoiceCatalog.key(for: model.speak.targetCode) }+ private var current: String { tab ?? roomKey }+ private var language: String { current == "zh" ? "zh-CN" : current }+ private var chosen: String? { model.voiceID(for: language) }+ private static let mainTabs = ["en", "zh", "ja"]++ var body: some View {+ VStack(alignment: .leading, spacing: 10) {+ HStack {+ Text("对方听到的声音").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.secondary)+ Spacer()+ tabs+ }+ Text("每种语言会记住你选的声音。对方当前在说\(title(roomKey))。")+ .font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ LazyVGrid(columns: [GridItem(.flexible(), spacing: 8), GridItem(.flexible(), spacing: 8)], spacing: 8) {+ ForEach(VoiceCatalog.options(for: language)) { v in card(v) }+ }+ cloneCard+ Text(footnote).font(.system(size: 12)).foregroundStyle(Palette.tertiary).lineSpacing(2)+ }+ .sheet(isPresented: $recording) {+ VoiceCloneSheet(model: model, settings: settings, language: language) { saved in+ recording = false+ if saved {+ cloneVersion += 1+ model.setVoice("clone", for: language)+ }+ }+ }+ }++ // MARK: Tabs++ private var tabs: some View {+ HStack(spacing: 2) {+ ForEach(Self.mainTabs, id: \.self) { k in tabButton(k, title(k)) }+ Menu {+ ForEach(VoiceCatalog.languages.filter { !Self.mainTabs.contains($0.key) }, id: \.key) { l in+ Button(l.title) { tab = l.key }+ }+ } label: {+ Text(Self.mainTabs.contains(current) ? "更多…" : title(current))+ .font(.system(size: 12, weight: Self.mainTabs.contains(current) ? .regular : .semibold))+ .foregroundStyle(Self.mainTabs.contains(current) ? Palette.secondary : Palette.ink)+ .padding(.horizontal, 10).frame(height: 24)+ .background(RoundedRectangle(cornerRadius: 7).fill(Self.mainTabs.contains(current) ? .clear : Color.white))+ }+ .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()+ }+ .padding(3)+ .background(RoundedRectangle(cornerRadius: 9).fill(Color(white: 0.925)))+ }++ private func tabButton(_ key: String, _ text: String) -> some View {+ let on = current == key+ return Button { tab = key } label: {+ Text(text).font(.system(size: 12, weight: on ? .semibold : .regular))+ .foregroundStyle(on ? Palette.ink : Palette.secondary)+ .padding(.horizontal, 10).frame(height: 24)+ .background(RoundedRectangle(cornerRadius: 7).fill(on ? Color.white : .clear)+ .shadow(color: .black.opacity(on ? 0.06 : 0), radius: 1, y: 1))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ }++ private func title(_ key: String) -> String {+ VoiceCatalog.languages.first { $0.key == key }?.title ?? targetName(key)+ }++ // MARK: Cards++ private func card(_ v: VoiceOption) -> some View {+ let selected = chosen == v.id+ let usable = !v.needsKey || ling.usable+ return Button { if usable { model.setVoice(v.id, for: language) } } label: {+ HStack(spacing: 10) {+ playButton(v.id, highlighted: selected, enabled: usable) { model.previewVoice(v.id, language: language) }+ VStack(alignment: .leading, spacing: 4) {+ Text(v.name).font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink).lineLimit(1)+ HStack(spacing: 4) {+ ForEach(usable ? v.tags : [v.tags.first ?? "", "需要 Ling key"], id: \.self) { tagView($0) }+ }+ }+ Spacer(minLength: 0)+ }+ .padding(.horizontal, 12).padding(.vertical, 10)+ .background(RoundedRectangle(cornerRadius: 12).fill(selected ? Palette.accentWash : Color.white))+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(selected ? Palette.accent : Palette.line, lineWidth: selected ? 2 : 1))+ .opacity(usable ? 1 : 0.55)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .accessibilityAddTraits(selected ? .isSelected : [])+ }++ private func tagView(_ text: String) -> some View {+ Text(text).font(.system(size: 11)).foregroundStyle(Palette.secondary)+ .padding(.horizontal, 6).padding(.vertical, 1)+ .background(RoundedRectangle(cornerRadius: 5).fill(Palette.fill))+ .fixedSize()+ }++ private func playButton(_ id: String, highlighted: Bool, enabled: Bool, action: @escaping () -> Void) -> some View {+ let playing = model.previewing == id+ return Button(action: action) {+ ZStack {+ Circle().fill(highlighted ? Palette.accent : Palette.fill)+ if playing {+ Spinner(size: 12, track: highlighted ? Color.white.opacity(0.4) : Palette.accentPale)+ } else {+ Image(systemName: "play.fill").font(.system(size: 10))+ .foregroundStyle(highlighted ? Color.white : Palette.ink)+ }+ }+ .frame(width: 30, height: 30)+ }+ .buttonStyle(.plain)+ .disabled(!enabled || playing)+ .help("试听")+ .accessibilityLabel("试听")+ }++ @ViewBuilder+ private var cloneCard: some View {+ let has = VoiceReference.exists && cloneVersion >= 0+ let selected = chosen == "clone"+ HStack(spacing: 10) {+ if has {+ playButton("clone", highlighted: selected, enabled: ling.usable) { model.previewVoice("clone", language: language) }+ } else {+ ZStack {+ Circle().fill(Palette.accentPale)+ Image(systemName: "mic").font(.system(size: 13)).foregroundStyle(Palette.accentInk)+ }+ .frame(width: 30, height: 30)+ }+ VStack(alignment: .leading, spacing: 3) {+ Text("我自己的声音").font(.system(size: 13, weight: .semibold))+ Text(has ? "已录好 · \(Int(VoiceReference.duration.rounded())) 秒 · \(cloneNote)"+ : "录制 15 秒原声,让对方听到你的音色;说外语时会保留你的口音,延迟约 3 秒")+ .font(.system(size: 12)).foregroundStyle(Palette.tertiary).lineLimit(2)+ }+ Spacer(minLength: 6)+ if has {+ if !selected {+ SoftButton("用这个") { model.setVoice("clone", for: language) }.disabled(!ling.usable)+ }+ Button("重录") { recording = true }.buttonStyle(.plain).font(.system(size: 12)).foregroundStyle(Palette.secondary)+ Button("删除") {+ VoiceReference.remove()+ for (k, v) in settings.speakVoices where v == "clone" { settings.speakVoices[k] = nil }+ cloneVersion += 1+ }+ .buttonStyle(.plain).font(.system(size: 12)).foregroundStyle(Palette.secondary)+ } else {+ SoftButton("录制") { recording = true }+ }+ }+ .padding(12)+ .background(RoundedRectangle(cornerRadius: 12).fill(selected ? Palette.accentWash : Color.white))+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(selected ? Palette.accent : Palette.line, lineWidth: selected ? 2 : 1))+ }++ private var cloneNote: String {+ let own = VoiceCatalog.key(for: settings.speakFromLang.locale)+ return own == current ? "说\(title(current))最像你,晚约 3 秒" : "说\(title(current))会带你的口音,晚约 3 秒"+ }++ private var footnote: String {+ if !ling.usable { return "未填写 Ling key 时仅可使用系统声音;填入 key 后可使用 Ming 语音或克隆你自己的声音。" }+ if chosen == "clone" { return "录音仅保存在本机,每次发言时随文字发送给 Ling 合成语音;Ling 不可用时自动切回系统声音。" }+ return "Ming 语音需使用 Ling key,延迟约 1.5 秒;Ling 不可用时自动切回系统声音。"+ }+}++// MARK: - Recording sheet++/// Read a passage for 15 s → transcribe it on this Mac → listen to the original and to the clone+/// speaking the room's language → keep it.+struct VoiceCloneSheet: View {+ @ObservedObject var model: AppModel+ @ObservedObject var settings: AppSettings+ let language: String+ let onDone: (Bool) -> Void++ @StateObject private var recorder = VoiceRecorder()+ @State private var consent = false+ @State private var player: AVAudioPlayer?+ @State private var clonePlaying = false++ private var ownLocale: String { settings.speakFromLang.locale }++ var body: some View {+ VStack(alignment: .leading, spacing: 16) {+ switch recorder.phase {+ case .ready: review+ default: record+ }+ }+ .padding(28)+ .frame(width: 560)+ .background(Color.white)+ .onDisappear { recorder.cancel(); player?.stop() }+ }++ // MARK: Record++ private var record: some View {+ VStack(alignment: .leading, spacing: 16) {+ VStack(alignment: .leading, spacing: 6) {+ Text("录制你的声音").font(.system(size: 18, weight: .bold))+ Text("请用平时开会的自然语气朗读以下段落,约 15 秒,在安静环境下录制效果最佳。")+ .font(.system(size: 13)).foregroundStyle(Palette.secondary)+ }+ Text(VoiceReference.passage(for: ownLocale))+ .font(.system(size: 16)).lineSpacing(7)+ .padding(.horizontal, 20).padding(.vertical, 16)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 14).fill(Palette.raised))+ .textSelection(.enabled)+ meter+ Toggle(isOn: $consent) {+ Text("这是我自己的声音。只在我说话时用它替我翻译。").font(.system(size: 12)).foregroundStyle(Palette.secondary)+ }+ .toggleStyle(.checkbox)+ .disabled(recorder.phase == .recording)+ HStack {+ SoftButton("取消") { recorder.cancel(); onDone(false) }+ Spacer()+ switch recorder.phase {+ case .recording:+ SoftButton("读完了", dark: true) { recorder.finish() }+ .disabled(recorder.seconds < VoiceRecorder.minSeconds)+ case .checking:+ HStack(spacing: 8) { Spinner(size: 14); Text("正在听写…").font(.system(size: 12)).foregroundStyle(Palette.secondary) }+ default:+ SoftButton(recorder.phase == .idle ? "开始录" : "再录一次", dark: true) {+ recorder.start(locale: ownLocale)+ }+ .disabled(!consent)+ }+ }+ }+ }++ @ViewBuilder+ private var meter: some View {+ switch recorder.phase {+ case .recording:+ HStack(spacing: 14) {+ LiveDot()+ Text(NotesEngine.clock(recorder.seconds)).font(.system(size: 14, weight: .semibold).monospacedDigit())+ LevelBars(level: recorder.level)+ Text("\(Int(VoiceRecorder.minSeconds))–\(Int(VoiceRecorder.maxSeconds)) 秒").font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ }+ .padding(.horizontal, 16).padding(.vertical, 12)+ .background(RoundedRectangle(cornerRadius: 12).fill(Palette.accentWash))+ case .failed(let why):+ Text(why).font(.system(size: 12)).foregroundStyle(Palette.error)+ .padding(12).frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 12).fill(Palette.errorPale))+ default:+ EmptyView()+ }+ }++ // MARK: Review++ private var review: some View {+ VStack(alignment: .leading, spacing: 16) {+ VStack(alignment: .leading, spacing: 6) {+ Text("录好了,先听听像不像").font(.system(size: 18, weight: .bold))+ Text("\(Int(recorder.seconds.rounded())) 秒 · 识别出的文字会与录音一起用于学习你的音色")+ .font(.system(size: 13)).foregroundStyle(Palette.secondary)+ }+ VStack(spacing: 0) {+ row(icon: playing ? "stop.fill" : "play.fill", accent: false, title: "你的原声", detail: recorder.transcript) {+ togglePlayOriginal()+ }+ Divider()+ row(icon: clonePlaying ? nil : "play.fill", accent: true,+ title: "用你的声音说\(targetTitle)", detail: VoiceCatalog.sample(for: language), tag: "对方会听到这个") {+ playClone()+ }+ }+ .overlay(RoundedRectangle(cornerRadius: 14).stroke(Palette.line, lineWidth: 1))+ if !model.ling.usable {+ Text("需先在“AI 服务”中填入 Ling key,才能使用你自己的声音。").font(.system(size: 12)).foregroundStyle(Palette.error)+ }+ Text("听起来不像或有杂音?换个安静的地方重录一次。录音仅保存在本机,可随时删除。")+ .font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ HStack {+ SoftButton("重录") { player?.stop(); recorder.start(locale: ownLocale) }+ Spacer()+ SoftButton("用这个声音", dark: true) { save() }+ }+ }+ }++ private var targetTitle: String {+ VoiceCatalog.languages.first { $0.key == VoiceCatalog.key(for: language) }?.title ?? targetName(language)+ }++ private var playing: Bool { player?.isPlaying ?? false }++ private func row(icon: String?, accent: Bool, title: String, detail: String, tag: String? = nil,+ action: @escaping () -> Void) -> some View {+ HStack(spacing: 12) {+ Button(action: action) {+ ZStack {+ Circle().fill(accent ? Palette.accent : Palette.fill)+ if let icon {+ Image(systemName: icon).font(.system(size: 10)).foregroundStyle(accent ? Color.white : Palette.ink)+ } else {+ Spinner(size: 12, track: Color.white.opacity(0.4))+ }+ }+ .frame(width: 32, height: 32)+ }+ .buttonStyle(.plain)+ .disabled(icon == nil)+ VStack(alignment: .leading, spacing: 2) {+ Text(title).font(.system(size: 13, weight: .semibold))+ Text(detail).font(.system(size: 12)).foregroundStyle(Palette.tertiary).lineLimit(1)+ }+ Spacer(minLength: 6)+ if let tag { Tag(tag, live: true) }+ }+ .padding(.horizontal, 14).padding(.vertical, 12)+ .background(accent ? Palette.accentWash : Color.clear)+ }++ private func togglePlayOriginal() {+ if let p = player, p.isPlaying { p.stop(); player = nil; return }+ player = try? AVAudioPlayer(contentsOf: recorder.url)+ player?.play()+ }++ private func playClone() {+ guard model.ling.usable, let data = try? Data(contentsOf: recorder.url) else { return }+ clonePlaying = true+ let ref = (audio: "data:audio/wav;base64," + data.base64EncodedString(), text: recorder.transcript)+ let lang = VoiceCatalog.mingLanguage(for: language)+ let ling = model.ling+ Task {+ await model.speak.speak(VoiceCatalog.sample(for: language), language: language, device: AudioDevices.defaultOutput,+ route: .stream { text in ling.speech(text, voice: nil, reference: ref, language: lang) })+ clonePlaying = false+ }+ }++ private func save() {+ do {+ try VoiceReference.save(wav: recorder.url, text: recorder.transcript)+ debugLog("voice clone saved \(Int(recorder.seconds)) s")+ onDone(true)+ } catch {+ debugLog("voice clone save failed: \(error.localizedDescription)")+ }+ }+}++/// A row of bars following the microphone level.+private struct LevelBars: View {+ let level: Float+ var body: some View {+ TimelineView(.animation(minimumInterval: 1 / 20)) { ctx in+ let t = ctx.date.timeIntervalSinceReferenceDate+ HStack(spacing: 4) {+ ForEach(0..<14, id: \.self) { i in+ let wobble = 0.55 + 0.45 * sin(t * 9 + Double(i) * 1.3)+ Capsule().fill(Palette.accent)+ .frame(width: 4, height: max(4, 28 * CGFloat(level) * CGFloat(wobble)))+ }+ }+ .frame(height: 28)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }+}diff --git a/Sources/LiveSubs/Voices.swift b/Sources/LiveSubs/Voices.swiftnew file mode 100644index 0000000..2d4a96c--- /dev/null+++ b/Sources/LiveSubs/Voices.swift@@ -0,0 +1,283 @@+import AVFoundation+import Foundation++// MARK: - Catalog++/// A voice the room can hear: one of Ming's (through the Ling key), a voice installed on this Mac,+/// or the user's own voice cloned from a recording.+struct VoiceOption: Identifiable, Equatable {+ enum Kind: Equatable {+ case ming(String)+ case system(String)+ case clone+ }+ /// Stored in settings: "ming:US_Emma", "system:<AVSpeechSynthesisVoice identifier>", "clone".+ let id: String+ let name: String+ let tags: [String]+ let kind: Kind++ var needsKey: Bool { if case .system = kind { return false } else { return true } }+}++/// Which voices to offer for each language the room may hear. Ming's are hand-picked natural ones+/// (two women, two men where it has them); for languages it has no native voice for, Emma and+/// George speak it with `language_id`. The Mac's own best female and male voices follow, so there is+/// always something without a key.+enum VoiceCatalog {+ /// Tabs in settings: (key, title). The key is the translation code without region ("zh" for zh-CN / zh-TW).+ static let languages: [(key: String, title: String)] = [+ ("en", "English"), ("zh", "中文"), ("ja", "日本語"), ("ko", "한국어"),+ ("es", "Español"), ("fr", "Français"), ("de", "Deutsch"), ("pt", "Português"),+ ]++ static func key(for code: String) -> String {+ let base = String(code.prefix(while: { $0 != "-" }))+ return base.isEmpty ? "en" : base+ }++ /// Ming's `language_id` for languages that need it (zh and en work without).+ static func mingLanguage(for code: String) -> String? {+ let k = key(for: code)+ return ["ja", "ko", "de", "fr", "es"].contains(k) ? k : nil+ }++ static func ming(for language: String) -> [VoiceOption] {+ func v(_ voice: String, _ name: String, _ tags: [String]) -> VoiceOption {+ VoiceOption(id: "ming:\(voice)", name: name, tags: tags, kind: .ming(voice))+ }+ switch key(for: language) {+ case "en":+ return [v("US_Emma", "Emma", ["女", "美式", "自然对话"]), v("UK_George", "George", ["男", "英式", "稳重"]),+ v("UK_Charlotte", "Charlotte", ["女", "英式", "平稳"])]+ case "zh":+ return [v("灵小雅", "小雅", ["女", "清亮", "播报"]), v("灵小棠", "小棠", ["女", "温和", "沉稳"]),+ v("灵小锋", "小锋", ["男", "温暖", "亲切"]), v("灵卓然", "卓然", ["男", "沉着", "清楚"])]+ case "ja", "ko", "de", "fr", "es":+ return [v("US_Emma", "Emma", ["女", "Ming"]), v("UK_George", "George", ["男", "Ming"])]+ default:+ return []+ }+ }++ /// The Mac's best installed female and male voice for the language (no novelty voices).+ static func system(for language: String) -> [VoiceOption] {+ let k = key(for: language)+ let prefix = language.hasPrefix("zh-TW") ? "zh-TW" : k == "zh" ? "zh-CN" : k+ let all = AVSpeechSynthesisVoice.speechVoices().filter {+ $0.language.hasPrefix(prefix) && !$0.voiceTraits.contains(.isNoveltyVoice)+ && !$0.voiceTraits.contains(.isPersonalVoice)+ }+ var out: [VoiceOption] = []+ for gender in [AVSpeechSynthesisVoiceGender.female, .male] {+ guard let best = all.filter({ $0.gender == gender }).max(by: { $0.quality.rawValue < $1.quality.rawValue }) else { continue }+ let quality = best.quality == .premium ? "高品质" : best.quality == .enhanced ? "增强" : "标准"+ out.append(VoiceOption(id: "system:\(best.identifier)", name: best.name,+ tags: [gender == .female ? "女" : "男", "本机", quality], kind: .system(best.identifier)))+ }+ return out+ }++ static func options(for language: String) -> [VoiceOption] { ming(for: language) + system(for: language) }++ /// What a language uses until the user picks: Ming's first voice with a key, else the Mac's.+ static func defaultID(for language: String, hasKey: Bool) -> String? {+ (hasKey ? ming(for: language).first : nil)?.id ?? system(for: language).first?.id+ }++ static let cloneOption = VoiceOption(id: "clone", name: "我自己的声音", tags: [], kind: .clone)++ /// A short line to try a voice with, in the language it will speak.+ static func sample(for language: String) -> String {+ switch key(for: language) {+ case "zh": "谢谢大家。我们来看一下上线时间表,并确定谁负责麦克风测试。"+ case "ja": "皆さん、ありがとうございます。発売スケジュールを確認しましょう。"+ case "ko": "감사합니다. 출시 일정을 함께 확인해 보겠습니다."+ case "es": "Gracias a todos. Revisemos el calendario de lanzamiento."+ case "fr": "Merci à tous. Regardons ensemble le calendrier de lancement."+ case "de": "Danke an alle. Schauen wir uns den Zeitplan für den Start an."+ case "pt": "Obrigado a todos. Vamos ver o cronograma de lançamento."+ default: "Thanks everyone. Let's look at the launch timeline and decide who owns the microphone tests."+ }+ }+}++// MARK: - The user's own voice++/// The recording Ming clones the user's voice from: `voice/reference.wav` (16 kHz mono, ≤ 30 s) and+/// `voice/reference.txt` (what it says, as transcribed on this Mac) under Application Support. Never+/// leaves the Mac except inside a speech request to Ling.+enum VoiceReference {+ static var folder: URL {+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+ .appendingPathComponent(DevBuild.supportFolder).appendingPathComponent("voice")+ }+ static var audioURL: URL { folder.appendingPathComponent("reference.wav") }+ static var textURL: URL { folder.appendingPathComponent("reference.txt") }++ static var exists: Bool {+ FileManager.default.fileExists(atPath: audioURL.path) && !(text ?? "").isEmpty+ }+ static var text: String? { try? String(contentsOf: textURL, encoding: .utf8) }++ static var duration: Double {+ guard let f = try? AVAudioFile(forReading: audioURL) else { return 0 }+ return Double(f.length) / f.fileFormat.sampleRate+ }++ /// What Ming needs: the clip as a data URI and its transcript.+ static func reference() -> (audio: String, text: String)? {+ guard let data = try? Data(contentsOf: audioURL), let text, !text.isEmpty else { return nil }+ return ("data:audio/wav;base64," + data.base64EncodedString(), text)+ }++ static func save(wav: URL, text: String) throws {+ let fm = FileManager.default+ try fm.createDirectory(at: folder, withIntermediateDirectories: true)+ try fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: folder.path)+ if fm.fileExists(atPath: audioURL.path) { try fm.removeItem(at: audioURL) }+ try fm.copyItem(at: wav, to: audioURL)+ try Data(text.utf8).write(to: textURL)+ for url in [audioURL, textURL] {+ try? fm.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)+ var u = url+ var values = URLResourceValues()+ values.isExcludedFromBackup = true+ try? u.setResourceValues(values)+ }+ }++ static func remove() {+ try? FileManager.default.removeItem(at: folder)+ }++ /// The passage to read, in the user's own language.+ static func passage(for locale: String) -> String {+ switch VoiceCatalog.key(for: locale) {+ case "zh": "大家好,我是这次会议的主持人。今天我们主要讨论新产品的上线计划,包括时间安排、测试范围和市场推广。请大家先看一下屏幕上的议程。"+ case "ja": "皆さん、こんにちは。今日の会議では、新製品の発売計画について話し合います。スケジュール、テストの範囲、そしてマーケティングについて順番に確認しましょう。"+ default: "Hello everyone, thanks for joining. Today we'll walk through the launch plan for the new product: the schedule, what we still need to test, and how we'll tell people about it. Let's start with the agenda on the screen."+ }+ }+}++/// Records the microphone for the voice clone: 16 kHz mono into a temporary WAV, with a level for+/// the meter. Stops by itself at 30 s.+@MainActor+final class VoiceRecorder: ObservableObject {+ enum Phase: Equatable { case idle, recording, checking, ready, failed(String) }++ @Published private(set) var phase: Phase = .idle+ @Published private(set) var seconds: Double = 0+ @Published private(set) var level: Float = 0+ /// What the recording says (transcribed on this Mac), used as the clone's reference text.+ @Published private(set) var transcript = ""++ static let maxSeconds = 30.0+ static let minSeconds = 8.0++ private let engine = AVAudioEngine()+ private nonisolated(unsafe) var file: AVAudioFile?+ private nonisolated(unsafe) var converter: AVAudioConverter?+ private var timer: Timer?+ private var started = Date()+ private(set) var url = FileManager.default.temporaryDirectory.appendingPathComponent("livesubs-voice-\(UUID().uuidString).wav")+ private let format = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 16000, channels: 1, interleaved: true)!+ private var locale = "zh-CN"++ func start(locale: String) {+ stopEngine()+ self.locale = locale+ transcript = ""+ try? FileManager.default.removeItem(at: url)+ let input = engine.inputNode+ let inFormat = input.outputFormat(forBus: 0)+ guard inFormat.sampleRate > 0,+ let f = try? AVAudioFile(forWriting: url, settings: format.settings, commonFormat: .pcmFormatInt16, interleaved: true),+ let conv = AVAudioConverter(from: inFormat, to: format) else {+ phase = .failed("麦克风没收到声音,请检查麦克风权限")+ return+ }+ file = f+ converter = conv+ let outFormat = format+ input.installTap(onBus: 0, bufferSize: 4096, format: inFormat) { [weak self] buffer, _ in+ guard let self, let conv = self.converter, let file = self.file else { return }+ let ratio = outFormat.sampleRate / buffer.format.sampleRate+ guard let out = AVAudioPCMBuffer(pcmFormat: outFormat, frameCapacity: AVAudioFrameCount(Double(buffer.frameLength) * ratio) + 32) else { return }+ var fed = false+ conv.convert(to: out, error: nil) { _, status in+ if fed { status.pointee = .noDataNow; return nil }+ fed = true+ status.pointee = .haveData+ return buffer+ }+ try? file.write(from: out)+ var peak: Float = 0+ if let ch = buffer.floatChannelData?[0] {+ for i in 0..<Int(buffer.frameLength) { peak = max(peak, abs(ch[i])) }+ }+ Task { @MainActor in self.level = min(1, peak * 2.5) }+ }+ do {+ try engine.start()+ } catch {+ input.removeTap(onBus: 0)+ phase = .failed("无法打开麦克风:\(error.localizedDescription)")+ return+ }+ started = Date()+ seconds = 0+ phase = .recording+ timer?.invalidate()+ let t = Timer(timeInterval: 0.1, repeats: true) { [weak self] _ in+ MainActor.assumeIsolated {+ guard let self else { return }+ self.seconds = Date().timeIntervalSince(self.started)+ if self.seconds >= Self.maxSeconds { self.finish() }+ }+ }+ timer = t+ RunLoop.main.add(t, forMode: .common)+ }++ /// Stops recording and transcribes it; `ready` when it is long enough and recognisable.+ func finish() {+ guard phase == .recording else { return }+ stopEngine()+ guard seconds >= Self.minSeconds else {+ phase = .failed("录音太短了,请至少朗读 \(Int(Self.minSeconds)) 秒")+ return+ }+ phase = .checking+ let url = url, locale = locale+ Task {+ let text = await Self.transcribe(url, locale: locale)+ self.transcript = text+ self.phase = text.count >= 6 ? .ready : .failed("没听清录音内容,请换个安静的地方再录一次")+ }+ }++ func cancel() {+ stopEngine()+ phase = .idle+ try? FileManager.default.removeItem(at: url)+ }++ private func stopEngine() {+ timer?.invalidate()+ timer = nil+ if engine.isRunning { engine.stop() }+ engine.inputNode.removeTap(onBus: 0)+ file = nil+ converter = nil+ level = 0+ }++ private static func transcribe(_ url: URL, locale: String) async -> String {+ guard let f = try? AVAudioFile(forReading: url),+ let buf = AVAudioPCMBuffer(pcmFormat: f.processingFormat, frameCapacity: AVAudioFrameCount(f.length)),+ (try? f.read(into: buf)) != nil else { return "" }+ return await LoopbackTest.transcribe([buf], locale: locale)+ }+}diff --git a/tools/README.md b/tools/README.mdindex 429050c..dd68dd4 100644--- a/tools/README.md+++ b/tools/README.md@@ -13,7 +13,7 @@- 字幕条:`frame` 把位置写进日志,`place:x,y,宽,字号` 摆到指定位置- 说话同传:`speakOn` / `speakOff` 开关,`speakFile:<音频>` 把文件当作麦克风输入,`speakOut:<路径>` 把译文语音另存一份- 导出:`export:<目录>`-- `mouse move|drag|dclick ...`:模拟鼠标移动、拖动、双击,坐标原点在主屏左下角。+- `mouse move|drag|dclick|click|scroll ...`:模拟鼠标移动、拖动、双击、单击、滚轮(`scroll x y 行数`,正数往上翻),坐标原点在主屏左下角。- `key`:模拟按住说话键。`key right [秒]` 单按右 ⌥;`key <keyCode> <Carbon 修饰键> [秒]` 按组合键(如 `key 122 0` 是 F1);不带参数是 ⌥ Space。- `toggle-key`:模拟按一下 ⌃⌥S。- `winall <pid>`:列出某个进程的窗口 ID,配合 `screencapture -l <ID>` 截图。diff --git a/tools/mouse.swift b/tools/mouse.swiftindex 84a52d4..401d4d1 100644--- a/tools/mouse.swift+++ b/tools/mouse.swift@@ -1,6 +1,7 @@import Foundationimport CoreGraphics-// usage: mouse move x y | mouse drag x1 y1 x2 y2 | mouse dclick x y (Cocoa coords, origin bottom-left of main screen)+// usage: mouse move x y | mouse drag x1 y1 x2 y2 | mouse dclick x y | mouse click x y | mouse scroll x y lines+// (Cocoa coords, origin bottom-left of main screen; scroll lines > 0 scrolls the content up, toward older lines)let a = CommandLine.argumentslet H = CGDisplayBounds(CGMainDisplayID()).heightfunc p(_ x: String, _ y: String) -> CGPoint { CGPoint(x: Double(x)!, y: Double(H) - Double(y)!) }@@ -20,5 +21,15 @@ case "dclick":let s = p(a[2], a[3]); post(.mouseMoved, s); usleep(600_000)post(.leftMouseDown, s, clicks: 1); post(.leftMouseUp, s, clicks: 1); usleep(50_000)post(.leftMouseDown, s, clicks: 2); post(.leftMouseUp, s, clicks: 2)+case "click":+ let s = p(a[2], a[3]); post(.mouseMoved, s); usleep(300_000)+ post(.leftMouseDown, s); post(.leftMouseUp, s)+case "scroll":+ post(.mouseMoved, p(a[2], a[3])); usleep(200_000)+ let n = Int32(a[4])!+ for _ in 0..<abs(n) {+ CGEvent(scrollWheelEvent2Source: nil, units: .line, wheelCount: 1, wheel1: n > 0 ? 3 : -3, wheel2: 0, wheel3: 0)!.post(tap: .cghidEventTap)+ usleep(30_000)+ }default: break}