知了 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: hold the right ⌥ key to talk, let both shortcuts be changed with clash checks
wquguru26ec2644e9d7
diff --git a/AGENTS.md b/AGENTS.mdindex 6d358d4..1f578b3 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -8,9 +8,10 @@ Live Subs is a macOS menu bar app that turns whatever the Mac is playing (stream- Listening: system audio (Core Audio process tap, our own process excluded) → spoken-language detection across installed on-device models → on-device transcription (`SpeechAnalyzer` / `SpeechTranscriber`) → translation (Google endpoint) → subtitle bar. Every confirmed sentence goes into the live meeting record.- Language detection compares confidence: the same 3–6 s clip after a pause is transcribed by every installed model; a winner needs confidence ≥ 0.6 and a 0.08 lead; the first detection or a 0.30 lead switches at once, otherwise two agreeing detections. After a switch the last 8 s are replayed into the new model.- "Follow system" translates into the first system language that differs from the source language.-- Subtitle bar: shows only while someone talks (auto) or always; tucks into a dot after 2/4/8 s of quiet; fades to 15% and stays click-through while the pointer passes over it; editable after the pointer rests 0.6 s (drag to move, drag the corner to scale, double-click resets); ⌃⌥S hides/shows. Position, width and size are remembered per display.-- Speaking: hold ⌥ Space → microphone → one `SpeechAnalyzer` per press, finished with `finalizeAndFinishThroughEndOfInput` → translate into the room's language → system voice → the chosen output device (a virtual microphone). The virtual microphone is BlackHole 2ch, installed from the app: download the official notarized package, check its pinned SHA-256, run `installer` and restart `coreaudiod` in one standard administrator prompt (the package only copies the driver and asks for a reboot; Core Audio loads a new HAL plug-in only when it restarts). Then a loopback sound test: speak a fixed English phrase into the device, record its input side, transcribe it (`LoopbackTest`). The checklist UI (`MicSetupCard`) is shared by onboarding step 3 and settings. We never bundle the GPL driver.+- Subtitle bar: shows only while someone talks (auto) or always; tucks into a dot after 2/4/8 s of quiet; fades to 15% and stays click-through while the pointer passes over it; editable after the pointer rests 0.6 s (drag to move, drag the corner to scale, double-click resets); ⌃⌥S (changeable) hides/shows. Position, width and size are remembered per display.+- Speaking: hold the right ⌥ key alone (a listen-only event tap, needs Input Monitoring; any other key while held cancels the press as a chord) or a user-chosen combination (Carbon hotkey, no permission) → microphone → one `SpeechAnalyzer` per press, finished with `finalizeAndFinishThroughEndOfInput` → translate into the room's language → system voice → the chosen output device (a virtual microphone). The virtual microphone is BlackHole 2ch, installed from the app: download the official notarized package, check its pinned SHA-256, run `installer` and restart `coreaudiod` in one standard administrator prompt (the package only copies the driver and asks for a reboot; Core Audio loads a new HAL plug-in only when it restarts). Then a loopback sound test: speak a fixed English phrase into the device, record its input side, transcribe it (`LoopbackTest`). The checklist UI (`MicSetupCard`) is shared by onboarding step 3 and settings. We never bundle the GPL driver.- Meeting records: one folder per meeting, `session.json` + `system.m4a` (+ `mic.m4a`); empty meetings are dropped; export to Markdown, Word (`.docx` via `NSAttributedString`) and SRT. Speaker labels are only "对方" (system audio) and "你" (microphone): no diarization yet.+- Shortcuts (`Shortcuts.swift`): talk and subtitle-bar toggle are recorded in settings (`ShortcutField`). A combination must include ⌃ or ⌘ (⌥/⇧ alone types characters; bare F keys are brightness/volume), must not be a system shortcut (`CopySymbolicHotKeys`) or held by another app (Carbon refuses to register it).- Nothing the user does needs the Terminal. When a feature request fits none of the above, push back before adding UI.## Design@@ -23,7 +24,7 @@ Live Subs is a macOS menu bar app that turns whatever the Mac is playing (stream## Layout- `Package.swift`: SwiftPM, macOS 26+, Swift 5 language mode, no dependencies.-- `Sources/LiveSubs`: the app. Engine files are UI-free: `SystemAudioTap`, `AudioRouter` (resample, feed, ring buffer, recording), `LanguageDetector`, `ListenEngine`, `SpeakEngine` (also the Carbon `HotKey`), `Translator`, `VirtualMic`, `SessionStore` (+ exports). UI: `Overlay` (subtitle bar), `Views` (panel, main window), `SettingsWindow` (settings + the virtual mic checklist), `Onboarding` (+ sample player, brand mark), `AppModel` (wiring, status item, windows, debug control, `@main`). `DMGBackground` draws the installer background; `DevBuild` tells dev from release.+- `Sources/LiveSubs`: the app. Engine files are UI-free: `SystemAudioTap`, `AudioRouter` (resample, feed, ring buffer, recording), `LanguageDetector`, `ListenEngine`, `SpeakEngine`, `Shortcuts` (Carbon `HotKey`, right-⌥ `RightOptionKey`), `Translator`, `VirtualMic`, `SessionStore` (+ exports). UI: `Overlay` (subtitle bar), `Views` (panel, main window), `SettingsWindow` (settings + the virtual mic checklist), `Onboarding` (+ sample player, brand mark), `AppModel` (wiring, status item, windows, debug control, `@main`). `DMGBackground` draws the installer background; `DevBuild` tells dev from release.- `Sources/LiveSubsIcon`: CLI that renders the icon set (`--dev` adds the DEV band).- `Resources/`: `Info.plist`, `sample/` (the 7 s onboarding clip, made by `scripts/make-sample.sh`), `dmg/DS_Store` (installer window layout).- `scripts/build.sh`: builds `build/LiveSubs.app`. Without `RELEASE=1` it is a **dev build**: "Live Subs Dev", bundle id `com.wquguru.cicada.dev`, `LiveSubsDev` = `branch @ commit[+]` in Info.plist; "DEV" beside the menu bar glyph, a DEV badge and the stamp in the panel, a DEV band on the icon, its own settings, permissions, `~/Library/Application Support/LiveSubs Dev` and log `/tmp/livesubs-dev-debug.log`. Both builds are signed ad hoc with a fixed designated requirement (the bundle id) so rebuilding keeps the system-audio and microphone permissions. Don't change the release bundle id `com.wquguru.cicada`: permissions are tied to it.@@ -40,7 +41,7 @@ scripts/package.sh # DMG + zip + checksums in build/scripts/make-sample.sh # regenerate the onboarding sample clip```-Debug control: dev builds always accept commands on the distributed notification `com.wquguru.cicada.debug` (release builds only with `defaults write com.wquguru.cicada debug -bool true`, which also logs transcript text). Send them with `tools/lsctl` (`start`, `stop`, `open`, `panel`, `onboarding:<step>`, `samplePlay`, `speakFile:<audio>`, `settings:<listen|speak|overlay|records>`, `micTest`, `micNext`, `place:x,y,w,font`, `frame`, `overlayState`, `export:<dir>` …).+Debug control: dev builds always accept commands on the distributed notification `com.wquguru.cicada.debug` (release builds only with `defaults write com.wquguru.cicada debug -bool true`, which also logs transcript text). Send them with `tools/lsctl` (`start`, `stop`, `open`, `panel`, `onboarding:<step>`, `samplePlay`, `speakFile:<audio>`, `settings:<listen|speak|overlay|records>`, `micTest`, `micNext`, `talkKey:<right|keyCode:mods>`, `toggleKey:<keyCode:mods>`, `shortcuts`, `place:x,y,w,font`, `frame`, `overlayState`, `export:<dir>` …).Release: `scripts/release.sh <x.y.z>` (clean `main`, a `## x.y.z — <today>` section in `CHANGELOG.md`) bumps `Resources/Info.plist`, commits, tags `v<x.y.z>` and pushes; `.github/workflows/release.yml` (runner `macos-26`) builds the tag, checks it matches Info.plist and publishes the DMG, zip and checksums with notes from `scripts/release_notes.sh`. `build.yml` runs on pull requests and on demand only: macOS minutes are expensive for a private repo.@@ -48,7 +49,7 @@ Only Command Line Tools are required (no Xcode project). Do not add an `.xcodepr## Verifying changes-Run the app and check the behaviour, not just the build. The pattern used so far: dev build, `tools/lsctl` to drive it, `afplay Resources/sample/sample.m4a` (or `say -o` clips) as the "someone talking" input, read `/tmp/livesubs-dev-debug.log`, screenshot windows with `screencapture -l <id>` (`tools/winall`). Synthetic mouse/key events (`tools/mouse`, `tools/key`, `tools/toggle-key`) need the terminal to have Accessibility access. The real microphone, the BlackHole install (password) and a Mac without permissions need a person.+Run the app and check the behaviour, not just the build. The pattern used so far: dev build, `tools/lsctl` to drive it, `afplay Resources/sample/sample.m4a` (or `say -o` clips) as the "someone talking" input, read `/tmp/livesubs-dev-debug.log`, screenshot windows with `screencapture -l <id>` (`tools/winall`). Synthetic mouse/key events (`tools/mouse`, `tools/key`, `tools/toggle-key`) need the terminal to have Accessibility access. Synthetic keys reach every app: another app's launcher may take ⌥ Space. The real microphone, the BlackHole install (password), granting Input Monitoring and a Mac without permissions need a person.TODO: unit tests for the pure parts (language-code mapping, detection scoring, SRT/Markdown export). Swift Testing under Command Line Tools needs extra framework search paths (see cameo's `scripts/test.sh`).@@ -57,6 +58,6 @@ TODO: unit tests for the pure parts (language-code mapping, detection scoring, S- Keep files small and single-purpose; match the existing naming and comment density (comments say why).- UI and engine state are `@MainActor`; audio callbacks never touch app state directly (they hand buffers to `AudioRouter`'s queue).- No third-party dependencies; system frameworks only.-- User data: `~/Library/Application Support/LiveSubs/Sessions` and `UserDefaults` (`sourceMode`, `target`, `speakEnabled`, `speakFrom`, `speakTo`, `speakOutput`, `recordAudio`, `overlayAuto`, `overlayHideAfter`, `overlay.<screen>`, `lastDetected`, `onboarded`).+- User data: `~/Library/Application Support/LiveSubs/Sessions` and `UserDefaults` (`sourceMode`, `target`, `speakEnabled`, `speakFrom`, `speakTo`, `speakOutput`, `recordAudio`, `overlayAuto`, `overlayHideAfter`, `overlay.<screen>`, `lastDetected`, `onboarded`, `talkKey`, `toggleKey` as `keyCode:carbonModifiers`).- Add a line to `CHANGELOG.md` with every user-visible change. Keep `README.md` and `README.zh-CN.md` in step.- Commit in coherent batches with a short imperative subject.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b7c3b0d..5be1ddc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,8 @@ the release workflow publishes it as the release notes.- Fixed: installing the virtual microphone looked like it failed ("系统还没识别到"). The package installed fine, but macOS only loads a new audio driver after its audio service restarts; the same password prompt now restarts it. If the driver is already there but not loaded, the app offers "让系统认出它" instead of reinstalling.- New: a sound test for the virtual microphone: the app plays a sentence into it, listens back and shows what the room will hear.- New: a settings window with a sidebar (听 / 我说话也翻译 / 字幕条 / 会议记录) replaces the settings sheet; the virtual microphone is set up from a three-step checklist there and in the first-run guide.+- Changed: hold the right ⌥ key on its own to talk, instead of ⌥ Space (which other apps' launchers often use, and which types a space). Pressing another key while holding it cancels, so ⌥ + letter still types. It needs the "输入监控" permission; the app asks for it.+- New: both shortcuts (talk, hide/show the subtitle bar) can be changed in settings: click and press new keys. Combinations without ⌃ or ⌘, system shortcuts and ones another app already uses are refused with a reason.## 2.0.0 — 2026-11-01diff --git a/README.md b/README.mdindex e9a7805..d1cb005 100644--- a/README.md+++ b/README.md@@ -33,7 +33,7 @@ Live Subs listens to what your Mac is playing — a livestream, a video, a meeti- **Detects the language for you** — every installed on-device speech model listens to the same few seconds; the most confident one wins, usually within half a second.- **Translates into your language** — follows your system languages by default (English audio on an English Mac goes to your next language), or pick one.- **Stays out of the way** — the subtitle bar appears only while someone talks, tucks into a small dot when it's quiet, and turns see-through when your pointer passes over it, so you can still click what's underneath. Rest the pointer on it to drag or resize; ⌃⌥S hides it.-- **Speak back** — hold ⌥ Space and talk; the room hears your words translated, through a virtual microphone you install from the app.+- **Speak back** — hold the right ⌥ key and talk; the room hears your words translated, through a virtual microphone you install from the app.- **Meeting records** — every session is saved as a bilingual transcript (with the audio, on your Mac only) and exports to Markdown, Word or SRT.- **Private by design** — audio capture, language detection and speech recognition all run on-device.@@ -64,7 +64,7 @@ The first launch walks you through three steps: turn on **system audio recording1. Play anything with sound. Subtitles appear at the bottom of the screen.2. Click the menu bar icon to change the heard language (auto by default), the language to translate into, or how the subtitle bar behaves.-3. To speak back: turn on **我说话也翻译**, choose **BlackHole 2ch** as the microphone in your meeting app, then hold ⌥ Space while you talk.+3. To speak back: turn on **我说话也翻译**, choose **BlackHole 2ch** as the microphone in your meeting app, then hold the right ⌥ key while you talk (allow "Input Monitoring" when asked). Both shortcuts can be changed in settings.4. **会议记录** in the panel opens your transcripts: search, switch between bilingual / original / translation, export.### Uninstalldiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 8c3c82f..8612b93 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -37,7 +37,7 @@ Live Subs 听电脑里正在播放的声音,比如直播、视频、会议或- 鼠标经过时字幕条会变透明,下面的按钮照样能点;- 鼠标停住不动,就可以拖动、缩放字幕条;- ⌃⌥S 随时隐藏或显示。-- **说话也能翻译**:按住 ⌥ Space 说话,会议里的人听到的是翻译后的语音。这需要一个虚拟麦克风,在 App 里一键安装。+- **说话也能翻译**:按住右边的 ⌥ 键说话,会议里的人听到的是翻译后的语音。这需要一个虚拟麦克风,在 App 里一键安装。- **会议记录**:每场会议都自动存成双语稿子(录音只存在本机),可以导出 Markdown、Word 或 SRT。- **隐私**:声音采集、语言识别、语音识别都在本机完成。@@ -75,7 +75,7 @@ Live Subs 听电脑里正在播放的声音,比如直播、视频、会议或3. 想让对方听到你的翻译:- 打开 **我说话也翻译**;- 在会议软件里把麦克风选成 **BlackHole 2ch**;- - 说话时按住 ⌥ Space。+ - 说话时按住右边的 ⌥ 键(第一次会请你允许“输入监控”)。两个快捷键都能在设置里换。4. 面板里的 **会议记录** 可以看所有稿子:能搜索,能切换双语、原文、译文,也能导出。### 卸载diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swiftindex 1835a21..e92b0b1 100644--- a/Sources/LiveSubs/AppModel.swift+++ b/Sources/LiveSubs/AppModel.swift@@ -10,8 +10,9 @@ final class AppModel: ObservableObject {let settings = AppSettings()let store = SessionStore()let overlay = OverlayController()- let hotkey = HotKey()- let toggleKey = HotKey(id: 2, keyCode: kVK_ANSI_S, modifiers: controlKey | optionKey)+ let talkCombo = HotKey(id: 1, shortcut: .defaultTalk)+ let talkRight = RightOptionKey()+ let toggleKey = HotKey(id: 2, shortcut: .defaultToggle)lazy var listen = ListenEngine(settings: settings)lazy var speak = SpeakEngine(settings: settings)@@ -28,6 +29,11 @@ final class AppModel: ObservableObject {@Published var liveSource = ""@Published var liveTranslation = ""@Published var onboardingStep = 1+ /// Hold right ⌥ is chosen but "输入监控" isn't allowed yet.+ @Published var talkNeedsPermission = false+ @Published var toggleKeyTaken = false+ private var permissionPoll: Timer?+ private var shortcutsSuspended = falselet installer = VirtualMicInstaller()let sample = SamplePlayer()var openOnboarding: (() -> Void)?@@ -81,12 +87,19 @@ final class AppModel: ObservableObject {self?.recordSaid(src, dst, from: from, to: to, secondsAgo: ago)}- hotkey.onDown = { [weak self] in+ let began: () -> Void = { [weak self] inDispatchQueue.main.async { MainActor.assumeIsolated { self?.speak.pressBegan() } }}- hotkey.onUp = { [weak self] in+ let ended: () -> Void = { [weak self] inDispatchQueue.main.async { MainActor.assumeIsolated { self?.speak.pressEnded() } }}+ talkCombo.onDown = began+ talkCombo.onUp = ended+ talkRight.onDown = began+ talkRight.onUp = ended+ talkRight.onCancel = { [weak self] in+ DispatchQueue.main.async { MainActor.assumeIsolated { self?.speak.pressCancelled() } }+ }overlay.onCollapsed = { [weak self] inself?.listen.clearDisplay()self?.overlay.setSubtitle(source: "", translation: "")@@ -97,7 +110,7 @@ final class AppModel: ObservableObject {toggleKey.onDown = { [weak self] inDispatchQueue.main.async { MainActor.assumeIsolated { self?.overlay.toggleManual() } }}- toggleKey.register()+ applyToggleKey()refreshOutputs()}@@ -243,15 +256,94 @@ final class AppModel: ObservableObject {AVCaptureDevice.requestAccess(for: .audio) { granted inif !granted { debugLog("microphone permission denied") }}- hotkey.register()+ if settings.talkKey.isRightOption && !RightOptionKey.allowed { RightOptionKey.requestAccess() }+ applyTalkKey()refreshOutputs()Task { await speak.prepare() }} else {- hotkey.unregister()+ applyTalkKey()Task { await speak.teardownAnalyzer() }}}+ // MARK: Shortcuts++ enum ShortcutRole { case talk, toggle }++ /// Arms the talk key for the current setting. Right ⌥ waits for "输入监控" and+ /// arms itself as soon as it's allowed (no relaunch).+ func applyTalkKey() {+ talkCombo.unregister()+ talkRight.stop()+ var needsPermission = false+ if settings.speakEnabled && !shortcutsSuspended {+ if settings.talkKey.isRightOption {+ needsPermission = !talkRight.start()+ } else {+ talkCombo.register(settings.talkKey)+ }+ }+ if talkNeedsPermission != needsPermission { talkNeedsPermission = needsPermission }+ if needsPermission, permissionPoll == nil {+ permissionPoll = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in+ MainActor.assumeIsolated {+ guard let self else { return }+ if RightOptionKey.allowed || !self.settings.speakEnabled || !self.settings.talkKey.isRightOption {+ self.permissionPoll?.invalidate()+ self.permissionPoll = nil+ self.applyTalkKey()+ }+ }+ }+ }+ }++ func applyToggleKey() {+ toggleKey.unregister()+ guard !shortcutsSuspended else { return }+ let ok = toggleKey.register(settings.toggleKey)+ if toggleKeyTaken == ok { toggleKeyTaken = !ok }+ }++ func allowTalkKey() {+ RightOptionKey.requestAccess()+ RightOptionKey.openSystemSettings()+ }++ /// While a shortcut field is recording, our own shortcuts must not swallow the keys.+ func suspendShortcuts(_ on: Bool) {+ shortcutsSuspended = on+ applyTalkKey()+ applyToggleKey()+ }++ /// 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 let p = s.typingProblem { return p }+ let other = role == .talk ? settings.toggleKey : settings.talkKey+ if s == other { return "和另一个快捷键重复了" }+ if s.isSystemShortcut { return "\(s.display) 是系统快捷键,换一个吧" }+ if !s.isRightOption {+ // Probe: Carbon refuses a combo another app already registered.+ let probe = HotKey(id: 9, shortcut: s)+ let free = probe.register()+ probe.unregister()+ if !free { return "\(s.display) 已被其他应用占用,换一个吧" }+ }+ switch role {+ case .talk:+ settings.talkKey = s+ if s.isRightOption && settings.speakEnabled && !RightOptionKey.allowed { RightOptionKey.requestAccess() }+ case .toggle:+ settings.toggleKey = s+ }+ applyTalkKey()+ applyToggleKey()+ objectWillChange.send()+ return nil+ }+func speakFromChanged() {objectWillChange.send()if settings.speakEnabled { Task { await speak.prepare() } }@@ -339,6 +431,12 @@ final class AppModel: ObservableObject {openSettings(settingsSection)case "micTest": installer.runTest()case "micNext": installer.next()+ case "talkKey", "toggleKey":+ let s = arg == "right" ? Shortcut.rightOption : Shortcut(stored: arg)+ let refusal = s.map { setShortcut($0, for: parts[0] == "talkKey" ? .talk : .toggle) } ?? "bad shortcut"+ debugLog("\(parts[0]) \(arg): \(refusal ?? "ok")")+ case "shortcuts":+ debugLog("shortcuts talk=\(settings.talkKey.display) armed=\(talkRight.isRunning || talkCombo.isRegistered) needsPermission=\(talkNeedsPermission) inputMonitoring=\(RightOptionKey.allowed) toggle=\(settings.toggleKey.display) taken=\(toggleKeyTaken)")case "speakOn": enableSpeaking(true)case "speakOff": enableSpeaking(false)case "speakOut": speak.debugOutputURL = arg.isEmpty ? nil : URL(fileURLWithPath: arg)diff --git a/Sources/LiveSubs/Onboarding.swift b/Sources/LiveSubs/Onboarding.swiftindex a977a29..8d7e004 100644--- a/Sources/LiveSubs/Onboarding.swift+++ b/Sources/LiveSubs/Onboarding.swift@@ -364,9 +364,17 @@ struct OnboardingView: View {HStack(alignment: .top, spacing: 24) {title("想让对方听懂你?", "按住说\(settings.speakFromLang.name),对方听到翻译后的语音。")Spacer()- HStack(alignment: .bottom, spacing: 6) {- key("⌥", "option", width: 58)- key("", "space", width: 120)+ VStack(alignment: .trailing, spacing: 6) {+ HStack(alignment: .bottom, spacing: 6) {+ if settings.talkKey.isRightOption {+ key("⌥", "右边 option", width: 96)+ } else {+ ForEach(Array(settings.talkKey.keys.enumerated()), id: \.offset) {+ key($0.element, "", width: $0.element.count > 2 ? 96 : 52)+ }+ }+ }+ Text("可以在设置里换").font(.system(size: 11)).foregroundStyle(Palette.tertiary)}}VStack(spacing: 0) {@@ -380,6 +388,10 @@ struct OnboardingView: View {.toggleStyle(.switch).labelsHidden().tint(Palette.ink)}.padding(.horizontal, 22).padding(.vertical, 14)+ if settings.speakEnabled && model.talkNeedsPermission {+ Divider().padding(.horizontal, 22)+ TalkKeyPermissionRow(model: model).padding(.horizontal, 6).padding(.vertical, 4)+ }}.background(RoundedRectangle(cornerRadius: 18).fill(Color.white)).overlay(RoundedRectangle(cornerRadius: 18).stroke(Palette.line, lineWidth: 1))diff --git a/Sources/LiveSubs/Overlay.swift b/Sources/LiveSubs/Overlay.swiftindex a27aa76..1fb20b9 100644--- a/Sources/LiveSubs/Overlay.swift+++ b/Sources/LiveSubs/Overlay.swift@@ -191,7 +191,7 @@ final class OverlayController {}}- /// ⌃⌥S: hide everything now, or bring the bar back.+ /// The toggle shortcut (⌃⌥S by default): hide everything now, or bring the bar back.func toggleManual() {guard isShown else { return }if manualHidden || !expanded {diff --git a/Sources/LiveSubs/Settings.swift b/Sources/LiveSubs/Settings.swiftindex 77bd0bf..449c8fe 100644--- a/Sources/LiveSubs/Settings.swift+++ b/Sources/LiveSubs/Settings.swift@@ -44,6 +44,15 @@ final class AppSettings: ObservableObject {didSet { save() }}+ /// Hold to talk: the right ⌥ key (default) or a key combination.+ @Published var talkKey: Shortcut {+ didSet { save() }+ }+ /// Hide / show the subtitle bar.+ @Published var toggleKey: Shortcut {+ didSet { save() }+ }+var debug: Bool { defaults.bool(forKey: "debug") }init() {@@ -62,6 +71,8 @@ final class AppSettings: ObservableObject {recordAudio = defaults.object(forKey: "recordAudio") as? Bool ?? trueoverlayAuto = defaults.object(forKey: "overlayAuto") as? Bool ?? trueoverlayHideAfter = defaults.object(forKey: "overlayHideAfter") as? Double ?? 4+ talkKey = Shortcut(stored: defaults.string(forKey: "talkKey")) ?? .defaultTalk+ toggleKey = Shortcut(stored: defaults.string(forKey: "toggleKey")) ?? .defaultToggle}private func save() {@@ -77,6 +88,8 @@ final class AppSettings: ObservableObject {defaults.set(recordAudio, forKey: "recordAudio")defaults.set(overlayAuto, forKey: "overlayAuto")defaults.set(overlayHideAfter, forKey: "overlayHideAfter")+ defaults.set(talkKey.stored, forKey: "talkKey")+ defaults.set(toggleKey.stored, forKey: "toggleKey")}/// Target language. "Follow system" uses the first system language thatdiff --git a/Sources/LiveSubs/SettingsWindow.swift b/Sources/LiveSubs/SettingsWindow.swiftindex 04a4bcf..9b9ea0d 100644--- a/Sources/LiveSubs/SettingsWindow.swift+++ b/Sources/LiveSubs/SettingsWindow.swift@@ -1,4 +1,5 @@import AppKit+import Carbon.HIToolboximport SwiftUIenum SettingsSection: String, CaseIterable, Identifiable {@@ -101,6 +102,113 @@ struct SoftButton: View {}}+// MARK: - Shortcut field++/// Shows a shortcut as key caps; click it, then press the new keys (esc cancels).+/// The talk key also accepts the right ⌥ on its own.+struct ShortcutField: View {+ @ObservedObject var model: AppModel+ let role: AppModel.ShortcutRole+ @State private var recording = false+ @State private var error: String?+ @State private var monitor: Any?+ @State private var rightDown = false++ private var current: Shortcut { role == .talk ? model.settings.talkKey : model.settings.toggleKey }+ private var standard: Shortcut { role == .talk ? .defaultTalk : .defaultToggle }++ var body: some View {+ VStack(alignment: .trailing, spacing: 4) {+ HStack(spacing: 6) {+ if current != standard && !recording {+ Button { error = model.setShortcut(standard, for: role) } label: {+ Image(systemName: "arrow.counterclockwise").font(.system(size: 11, weight: .semibold))+ .foregroundStyle(Palette.secondary).frame(width: 24, height: 24).contentShape(Rectangle())+ }+ .buttonStyle(.plain).help("恢复默认(\(standard.display))")+ }+ Button { recording ? stop() : start() } label: {+ HStack(spacing: 4) {+ if recording {+ Text(role == .talk ? "按下组合键,或单按右 ⌥" : "按下新的组合键")+ .font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.accentInk)+ } else {+ ForEach(Array(current.keys.enumerated()), id: \.offset) { KeyCap($0.element) }+ }+ }+ .padding(.horizontal, 8).frame(height: 28)+ .background(RoundedRectangle(cornerRadius: 7).fill(recording ? Palette.accentPale : Palette.ground))+ .overlay(RoundedRectangle(cornerRadius: 7).stroke(recording ? Palette.accent : .clear, lineWidth: 1))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .help(recording ? "按 esc 取消" : "点一下,换成别的按键")+ }+ if let error {+ Text(error).font(.system(size: 11)).foregroundStyle(Palette.accentInk)+ }+ }+ .onDisappear { stop() }+ // Another app grabbed the keys (its launcher came up): stop waiting for them.+ .onReceive(NotificationCenter.default.publisher(for: NSApplication.didResignActiveNotification)) { _ in stop() }+ }++ private func start() {+ error = nil+ recording = true+ rightDown = false+ model.suspendShortcuts(true)+ monitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .flagsChanged]) { e in+ handle(e)+ return nil+ }+ }++ private func stop() {+ if let monitor { NSEvent.removeMonitor(monitor) }+ monitor = nil+ guard recording else { return }+ recording = false+ model.suspendShortcuts(false)+ }++ private func handle(_ e: NSEvent) {+ let flags = e.modifierFlags.intersection(.deviceIndependentFlagsMask)+ switch e.type {+ case .keyDown:+ if e.keyCode == UInt16(kVK_Escape) && flags.isEmpty { stop(); return }+ commit(Shortcut(keyCode: e.keyCode, flags: flags))+ case .flagsChanged:+ if role == .talk && e.keyCode == UInt16(kVK_RightOption) {+ // Right ⌥ pressed and released with nothing else: that's the choice.+ if e.modifierFlags.rawValue & 0x40 != 0 { rightDown = true } else if rightDown { commit(.rightOption) }+ } else {+ rightDown = false+ }+ default:+ break+ }+ }++ private func commit(_ s: Shortcut) {+ error = model.setShortcut(s, for: role)+ stop()+ }+}++/// "输入监控" is missing for the right ⌥ key: one line and a button.+struct TalkKeyPermissionRow: View {+ @ObservedObject var model: AppModel+ var body: some View {+ SettingsRow(title: "还差一步:允许“输入监控”",+ detail: "按住右 ⌥ 要用到它。在系统设置里打开 \(appDisplayName),回到这里就生效") {+ SoftButton("去允许", dark: true) { model.allowTalkKey() }+ }+ }+}++let appDisplayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String ?? "Live Subs"+// MARK: - Virtual microphone checklist/// The one place the virtual mic is set up: onboarding step 3 and the settings window.@@ -314,7 +422,11 @@ struct SettingsView: View {Toggle("我说话也翻译", isOn: Binding(get: { settings.speakEnabled }, set: { model.enableSpeaking($0) })).toggleStyle(.switch).labelsHidden().controlSize(.small).tint(Palette.ink)}- SettingsRow(title: "按住说话") { KeyCap(HotKey.display) }+ SettingsRow(title: "按住说话",+ detail: settings.talkKey.isRightOption ? "只按右边的 ⌥;和别的键一起按不算" : nil) {+ ShortcutField(model: model, role: .talk)+ }+ if settings.speakEnabled && model.talkNeedsPermission { TalkKeyPermissionRow(model: model) }SettingsRow(title: "我说的语言") {PillMenu(value: settings.speakFromLang.name, options: sourceLanguages.map { ($0.locale, $0.name) }) {settings.speakFrom = $0@@ -364,7 +476,9 @@ struct SettingsView: View {.pickerStyle(.segmented).labelsHidden().frame(width: 140)}}- SettingsRow(title: "随时显示 / 隐藏") { KeyCap("⌃ ⌥ S") }+ SettingsRow(title: "随时显示 / 隐藏", detail: model.toggleKeyTaken ? "被其他应用占用了,点右边换一个" : nil) {+ ShortcutField(model: model, role: .toggle)+ }SettingsRow(title: "位置和大小", detail: "鼠标停住不动可拖动,拖右下角缩放", divider: false) {SoftButton("恢复默认") { model.overlay.resetPosition() }}diff --git a/Sources/LiveSubs/Shortcuts.swift b/Sources/LiveSubs/Shortcuts.swiftnew file mode 100644index 0000000..b144d2c--- /dev/null+++ b/Sources/LiveSubs/Shortcuts.swift@@ -0,0 +1,254 @@+import AppKit+import Carbon.HIToolbox++// MARK: - Shortcut++/// A key plus Carbon modifiers, or the right ⌥ key on its own (push to talk).+struct Shortcut: Equatable {+ var keyCode: Int+ var modifiers: Int++ static let rightOption = Shortcut(keyCode: kVK_RightOption, modifiers: 0)+ static let defaultTalk = rightOption+ static let defaultToggle = Shortcut(keyCode: kVK_ANSI_S, modifiers: controlKey | optionKey)++ var isRightOption: Bool { self == .rightOption }++ var stored: String { "\(keyCode):\(modifiers)" }++ init(keyCode: Int, modifiers: Int) {+ self.keyCode = keyCode+ self.modifiers = modifiers+ }++ init?(stored: String?) {+ let p = (stored ?? "").split(separator: ":").compactMap { Int($0) }+ guard p.count == 2 else { return nil }+ self.init(keyCode: p[0], modifiers: p[1])+ }++ init(keyCode: UInt16, flags: NSEvent.ModifierFlags) {+ var m = 0+ if flags.contains(.control) { m |= controlKey }+ if flags.contains(.option) { m |= optionKey }+ if flags.contains(.shift) { m |= shiftKey }+ if flags.contains(.command) { m |= cmdKey }+ self.init(keyCode: Int(keyCode), modifiers: m)+ }++ /// Key caps in display order, e.g. ["⌃", "⌥", "S"].+ var keys: [String] {+ if isRightOption { return ["右 ⌥"] }+ var k: [String] = []+ if modifiers & controlKey != 0 { k.append("⌃") }+ if modifiers & optionKey != 0 { k.append("⌥") }+ if modifiers & shiftKey != 0 { k.append("⇧") }+ if modifiers & cmdKey != 0 { k.append("⌘") }+ k.append(Shortcut.keyName(keyCode))+ return k+ }++ var display: String { keys.joined(separator: " ") }++ private static let functionKeys: [Int: String] = [+ kVK_F1: "F1", kVK_F2: "F2", kVK_F3: "F3", kVK_F4: "F4", kVK_F5: "F5", kVK_F6: "F6",+ kVK_F7: "F7", kVK_F8: "F8", kVK_F9: "F9", kVK_F10: "F10", kVK_F11: "F11", kVK_F12: "F12",+ kVK_F13: "F13", kVK_F14: "F14", kVK_F15: "F15", kVK_F16: "F16", kVK_F17: "F17",+ kVK_F18: "F18", kVK_F19: "F19", kVK_F20: "F20",+ ]+ private static let named: [Int: String] = [+ kVK_Space: "Space", kVK_Return: "↩", kVK_Tab: "⇥", kVK_Delete: "⌫", kVK_ForwardDelete: "⌦",+ kVK_Escape: "esc", kVK_LeftArrow: "←", kVK_RightArrow: "→", kVK_UpArrow: "↑", kVK_DownArrow: "↓",+ kVK_Home: "↖", kVK_End: "↘", kVK_PageUp: "⇞", kVK_PageDown: "⇟", kVK_RightOption: "右 ⌥",+ ]++ /// The character the key types on the current layout (US letters on non-Latin layouts).+ static func keyName(_ code: Int) -> String {+ if let f = functionKeys[code] { return f }+ if let n = named[code] { return n }+ guard let source = TISCopyCurrentASCIICapableKeyboardLayoutInputSource()?.takeRetainedValue(),+ let ptr = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) else { return "#\(code)" }+ let data = Unmanaged<CFData>.fromOpaque(ptr).takeUnretainedValue() as Data+ var dead: UInt32 = 0+ var chars = [UniChar](repeating: 0, count: 4)+ var length = 0+ let status = data.withUnsafeBytes { raw -> OSStatus in+ guard let layout = raw.bindMemory(to: UCKeyboardLayout.self).baseAddress else { return -1 }+ return UCKeyTranslate(layout, UInt16(code), UInt16(kUCKeyActionDisplay), 0, UInt32(LMGetKbdType()),+ OptionBits(kUCKeyTranslateNoDeadKeysBit), &dead, chars.count, &length, &chars)+ }+ guard status == noErr, length > 0 else { return "#\(code)" }+ return String(utf16CodeUnits: chars, count: length).uppercased()+ }++ /// Why this can't be a global shortcut, or nil. ⌥ or ⇧ alone types characters in+ /// every app (⌥ Space is a non-breaking space). Bare F keys are brightness/volume on+ /// most Mac keyboards. So a combination needs ⌃ or ⌘.+ var typingProblem: String? {+ if isRightOption { return nil }+ if modifiers & (controlKey | cmdKey) == 0 { return "要带上 ⌃ 或 ⌘,不然会挡住打字" }+ return nil+ }++ /// The system already uses it (Spotlight, input sources, Mission Control, screenshots …).+ var isSystemShortcut: Bool {+ var unmanaged: Unmanaged<CFArray>?+ guard CopySymbolicHotKeys(&unmanaged) == noErr, let list = unmanaged?.takeRetainedValue() as? [[String: Any]] else {+ return false+ }+ let mask = controlKey | optionKey | shiftKey | cmdKey+ return list.contains { hk in+ guard (hk["kHISymbolicHotKeyEnabled"] as? Bool) ?? false,+ let code = (hk["kHISymbolicHotKeyCode"] as? NSNumber)?.intValue,+ let mods = (hk["kHISymbolicHotKeyModifiers"] as? NSNumber)?.intValue else { return false }+ return code == keyCode && mods & mask == modifiers & mask+ }+ }+}++// MARK: - Key combination (Carbon)++/// A global key combination via Carbon. Needs no permission, reports press and+/// release, and fails with `eventHotKeyExistsErr` if another app holds the same combo.+final class HotKey {+ var onDown: (() -> Void)?+ var onUp: (() -> Void)?+ private(set) var shortcut: Shortcut+ private var ref: EventHotKeyRef?+ private var handler: EventHandlerRef?+ private let id: UInt32++ init(id: UInt32, shortcut: Shortcut) {+ self.id = id+ self.shortcut = shortcut+ var types = [+ EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed)),+ EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyReleased)),+ ]+ let me = Unmanaged.passUnretained(self).toOpaque()+ InstallEventHandler(GetApplicationEventTarget(), { _, event, user in+ guard let event, let user else { return noErr }+ let hk = Unmanaged<HotKey>.fromOpaque(user).takeUnretainedValue()+ var hkID = EventHotKeyID()+ GetEventParameter(event, EventParamName(kEventParamDirectObject), EventParamType(typeEventHotKeyID),+ nil, MemoryLayout<EventHotKeyID>.size, nil, &hkID)+ guard hkID.id == hk.id else { return OSStatus(eventNotHandledErr) }+ if GetEventKind(event) == UInt32(kEventHotKeyPressed) { hk.onDown?() } else { hk.onUp?() }+ return noErr+ }, 2, &types, me, &handler)+ }++ deinit {+ unregister()+ if let handler { RemoveEventHandler(handler) }+ }++ var isRegistered: Bool { ref != nil }++ /// Registers `shortcut` (replacing any current one). Returns false if another app holds it.+ @discardableResult+ func register(_ shortcut: Shortcut? = nil) -> Bool {+ unregister()+ if let shortcut { self.shortcut = shortcut }+ let hkID = EventHotKeyID(signature: OSType(0x4C535542), id: id) // 'LSUB'+ let status = RegisterEventHotKey(UInt32(self.shortcut.keyCode), UInt32(self.shortcut.modifiers), hkID,+ GetApplicationEventTarget(), 0, &ref)+ if status != noErr {+ debugLog("hotkey \(self.shortcut.display) not registered: \(status)")+ ref = nil+ return false+ }+ return true+ }++ func unregister() {+ if let ref { UnregisterEventHotKey(ref) }+ ref = nil+ }+}++// MARK: - Right ⌥ on its own++/// Hold the right ⌥ key to talk. A modifier on its own can't be a Carbon hotkey, so this+/// listens to key events with a listen-only event tap, which needs "输入监控" (Input+/// Monitoring). Pressing any other key while holding it is a chord (⌥ + letter types+/// accented characters), so the press is cancelled instead of sent.+final class RightOptionKey {+ var onDown: (() -> Void)?+ var onUp: (() -> Void)?+ var onCancel: (() -> Void)?++ private var tap: CFMachPort?+ private var source: CFRunLoopSource?+ private var active = false++ // Device-dependent modifier bits (IOLLEvent.h).+ private static let rightAlt: UInt64 = 0x40+ private static let otherModifiers: UInt64 = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x2000 // ctrl, shift, cmd, left alt, right ctrl++ static var allowed: Bool { CGPreflightListenEventAccess() }++ /// Shows the system prompt the first time; afterwards only System Settings can grant it.+ static func requestAccess() { _ = CGRequestListenEventAccess() }++ static func openSystemSettings() {+ if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent") {+ NSWorkspace.shared.open(url)+ }+ }++ var isRunning: Bool { tap != nil }++ @discardableResult+ func start() -> Bool {+ if tap != nil { return true }+ guard RightOptionKey.allowed else { return false }+ let mask = (1 << CGEventType.flagsChanged.rawValue) | (1 << CGEventType.keyDown.rawValue)+ let me = Unmanaged.passUnretained(self).toOpaque()+ guard let t = CGEvent.tapCreate(tap: .cgSessionEventTap, place: .tailAppendEventTap, options: .listenOnly,+ eventsOfInterest: CGEventMask(mask), callback: { _, type, event, user in+ if let user { Unmanaged<RightOptionKey>.fromOpaque(user).takeUnretainedValue().handle(type, event) }+ return Unmanaged.passUnretained(event)+ }, userInfo: me) else {+ debugLog("right option: event tap not created")+ return false+ }+ tap = t+ source = CFMachPortCreateRunLoopSource(nil, t, 0)+ CFRunLoopAddSource(CFRunLoopGetMain(), source, .commonModes)+ CGEvent.tapEnable(tap: t, enable: true)+ debugLog("right option: listening")+ return true+ }++ func stop() {+ if active { active = false; onCancel?() }+ if let tap { CGEvent.tapEnable(tap: tap, enable: false) }+ if let source { CFRunLoopRemoveSource(CFRunLoopGetMain(), source, .commonModes) }+ tap = nil+ source = nil+ }++ private func handle(_ type: CGEventType, _ event: CGEvent) {+ switch type {+ case .tapDisabledByTimeout, .tapDisabledByUserInput:+ if let tap { CGEvent.tapEnable(tap: tap, enable: true) }+ case .flagsChanged:+ let flags = event.flags.rawValue+ let isRight = event.getIntegerValueField(.keyboardEventKeycode) == Int64(kVK_RightOption)+ if isRight, flags & RightOptionKey.rightAlt != 0 {+ // Only a clean press starts talking, not ⌘ + right ⌥ and the like.+ if !active, flags & RightOptionKey.otherModifiers == 0 { active = true; onDown?() }+ } else if isRight {+ if active { active = false; onUp?() }+ } else if active {+ active = false+ onCancel?()+ }+ case .keyDown:+ if active { active = false; onCancel?() }+ default:+ break+ }+ }+}diff --git a/Sources/LiveSubs/SpeakEngine.swift b/Sources/LiveSubs/SpeakEngine.swiftindex f596166..017e0a6 100644--- a/Sources/LiveSubs/SpeakEngine.swift+++ b/Sources/LiveSubs/SpeakEngine.swift@@ -50,53 +50,6 @@ enum AudioDevices {static var virtualMic: OutputDevice? { outputs().first(where: \.isVirtualMic) }}-// MARK: - Push-to-talk hotkey--/// A global hold-to-talk hotkey via Carbon. Unlike NSEvent global monitors it-/// needs no Accessibility / Input Monitoring permission and reports release.-final class HotKey {- static let display = "⌥ Space"- var onDown: (() -> Void)?- var onUp: (() -> Void)?- private var ref: EventHotKeyRef?- private var handler: EventHandlerRef?- private let id: UInt32- private let keyCode: UInt32- private let modifiers: UInt32-- init(id: UInt32 = 1, keyCode: Int = kVK_Space, modifiers: Int = optionKey) {- self.id = id- self.keyCode = UInt32(keyCode)- self.modifiers = UInt32(modifiers)- var types = [- EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed)),- EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyReleased)),- ]- let me = Unmanaged.passUnretained(self).toOpaque()- InstallEventHandler(GetApplicationEventTarget(), { _, event, user in- guard let event, let user else { return noErr }- let hk = Unmanaged<HotKey>.fromOpaque(user).takeUnretainedValue()- var hkID = EventHotKeyID()- GetEventParameter(event, EventParamName(kEventParamDirectObject), EventParamType(typeEventHotKeyID),- nil, MemoryLayout<EventHotKeyID>.size, nil, &hkID)- guard hkID.id == hk.id else { return OSStatus(eventNotHandledErr) }- if GetEventKind(event) == UInt32(kEventHotKeyPressed) { hk.onDown?() } else { hk.onUp?() }- return noErr- }, 2, &types, me, &handler)- }-- func register() {- guard ref == nil else { return }- let hkID = EventHotKeyID(signature: OSType(0x4C535542), id: id) // 'LSUB'- RegisterEventHotKey(keyCode, modifiers, hkID, GetApplicationEventTarget(), 0, &ref)- }-- func unregister() {- if let ref { UnregisterEventHotKey(ref) }- ref = nil- }-}-// MARK: - Speak engine/// Hold to talk: microphone → on-device transcription → translation →@@ -246,14 +199,29 @@ final class SpeakEngine {onStatus?("语音识别还在准备,请再按一次")return}+ debugLog("speak: press began")pressStarted = Date()phase = .listeningonLive?(.listening, "", "")startMic(format: format, input: input)}+ /// The talk key turned out to be part of a chord: drop what was heard, send nothing.+ func pressCancelled() {+ guard phase == .listening else { return }+ stopMic()+ utterance?.input.finish()+ utterance = nil+ finals = []+ volatile = ""+ phase = .idle+ onLive?(.idle, "", "")+ debugLog("speak: press cancelled (chord)")+ }+func pressEnded() {guard phase == .listening else { return }+ debugLog("speak: press ended")// 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() }diff --git a/Sources/LiveSubs/Views.swift b/Sources/LiveSubs/Views.swiftindex 20701ab..21384d6 100644--- a/Sources/LiveSubs/Views.swift+++ b/Sources/LiveSubs/Views.swift@@ -126,7 +126,7 @@ struct MenuPanelView: View {Text("我说话也翻译").font(.system(size: 14, weight: .semibold)).foregroundStyle(Palette.ink)HStack(spacing: 5) {Text("按住").foregroundStyle(Palette.secondary)- KeyCap(HotKey.display)+ KeyCap(settings.talkKey.display)Text("说\(settings.speakFromLang.name) → \(targetName(model.speak.targetCode))").foregroundStyle(Palette.secondary).lineLimit(1)}@@ -173,7 +173,7 @@ struct MenuPanelView: View {HStack(spacing: 5) {Text("随时显示 / 隐藏").foregroundStyle(Palette.secondary)Spacer()- KeyCap("⌃ ⌥ S")+ KeyCap(settings.toggleKey.display)}.font(.system(size: 12))}diff --git a/tools/README.md b/tools/README.mdindex ebee40e..429050c 100644--- a/tools/README.md+++ b/tools/README.md@@ -9,11 +9,12 @@- 开关字幕:`start` / `stop`- 打开界面:`open`(主窗口)、`panel`(菜单栏面板)、`settings[:speak]`(设置,可指定栏目)- 虚拟麦克风:`micTest` 试音(往虚拟麦克风播一句再听回来,结果写进日志),`micNext` 做清单里的下一步+ - 快捷键:`talkKey:right` 或 `talkKey:<keyCode>:<Carbon 修饰键>` 换说话键(被拒的原因写进日志),`toggleKey:…` 同理,`shortcuts` 把当前状态写进日志- 字幕条:`frame` 把位置写进日志,`place:x,y,宽,字号` 摆到指定位置- 说话同传:`speakOn` / `speakOff` 开关,`speakFile:<音频>` 把文件当作麦克风输入,`speakOut:<路径>` 把译文语音另存一份- 导出:`export:<目录>`- `mouse move|drag|dclick ...`:模拟鼠标移动、拖动、双击,坐标原点在主屏左下角。-- `key`:模拟按住 ⌥ Space 1.5 秒。+- `key`:模拟按住说话键。`key right [秒]` 单按右 ⌥;`key <keyCode> <Carbon 修饰键> [秒]` 按组合键(如 `key 122 0` 是 F1);不带参数是 ⌥ Space。- `toggle-key`:模拟按一下 ⌃⌥S。- `winall <pid>`:列出某个进程的窗口 ID,配合 `screencapture -l <ID>` 截图。- `transcribe <音频> <locale>`:用本机模型转写一个文件,用来核对输出。diff --git a/tools/key.swift b/tools/key.swiftindex 8ae1a67..09ca4ff 100644--- a/tools/key.swift+++ b/tools/key.swift@@ -1,5 +1,33 @@import CoreGraphicsimport Foundation-let d = CGEvent(keyboardEventSource: nil, virtualKey: 49, keyDown: true)!; d.flags = .maskAlternate; d.post(tap: .cghidEventTap)-usleep(1_500_000)-let u = CGEvent(keyboardEventSource: nil, virtualKey: 49, keyDown: false)!; u.flags = .maskAlternate; u.post(tap: .cghidEventTap)++// Hold a key or the right ⌥ alone, as the talk key would be held.+// key ⌥ Space for 1.5 s (the old default)+// key right [seconds] right ⌥ on its own+// key <keyCode> <carbonModifiers> [seconds] e.g. key 49 4096 → ⌃ Space+let args = CommandLine.arguments+let hold = useconds_t((Double(args.count > 3 ? args[3] : (args.count == 3 && args[1] == "right" ? args[2] : "1.5")) ?? 1.5) * 1_000_000)++if args.count > 1 && args[1] == "right" {+ let down = CGEvent(keyboardEventSource: nil, virtualKey: 61, keyDown: true)!+ down.type = .flagsChanged+ down.flags = CGEventFlags(rawValue: CGEventFlags.maskAlternate.rawValue | 0x40)+ down.post(tap: .cghidEventTap)+ usleep(hold)+ let up = CGEvent(keyboardEventSource: nil, virtualKey: 61, keyDown: false)!+ up.type = .flagsChanged+ up.flags = CGEventFlags(rawValue: 0)+ up.post(tap: .cghidEventTap)+ exit(0)+}++let code = CGKeyCode(args.count > 1 ? Int(args[1]) ?? 49 : 49)+let carbon = args.count > 2 ? Int(args[2]) ?? 2048 : 2048+var flags = CGEventFlags()+if carbon & 256 != 0 { flags.insert(.maskCommand) }+if carbon & 512 != 0 { flags.insert(.maskShift) }+if carbon & 2048 != 0 { flags.insert(.maskAlternate) }+if carbon & 4096 != 0 { flags.insert(.maskControl) }+let d = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: true)!; d.flags = flags; d.post(tap: .cghidEventTap)+usleep(hold)+let u = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: false)!; u.flags = flags; u.post(tap: .cghidEventTap)