@sonicloud/dsh-sonicloud-device 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/CHANGELOG.zh.md +35 -0
  3. package/LICENSE +25 -0
  4. package/README.md +139 -2
  5. package/cordis.patch.yml +3 -0
  6. package/dist/build.json +5 -0
  7. package/dist/client.js +20621 -0
  8. package/docs/contributing/development.md +200 -0
  9. package/docs/specs/ci-cd.md +128 -0
  10. package/docs/specs/mouse-settings.md +255 -0
  11. package/docs/specs/smart-mouse-plugin.md +239 -0
  12. package/native/COPYING.LGPLv2.1 +502 -0
  13. package/native/LICENSE.hidapi-bsd +26 -0
  14. package/native/README.md +15 -0
  15. package/native/SOURCE.json +16 -0
  16. package/native/THIRD_PARTY_LICENSES.txt +69 -0
  17. package/native/darwin-arm64/README.md +71 -0
  18. package/native/darwin-arm64/libavcodec.62.28.102.dylib +0 -0
  19. package/native/darwin-arm64/libavcodec.62.dylib +0 -0
  20. package/native/darwin-arm64/libavutil.60.26.102.dylib +0 -0
  21. package/native/darwin-arm64/libavutil.60.dylib +0 -0
  22. package/native/darwin-arm64/libuMouseSdk.0.4.20.dylib +0 -0
  23. package/native/darwin-arm64/libuMouseSdk.0.dylib +0 -0
  24. package/native/darwin-arm64/libuMouseSdk.dylib +0 -0
  25. package/native/desktop/CompatibilityPolicy.swift +17 -0
  26. package/native/desktop/VoicePanel.cs +197 -0
  27. package/native/desktop/VoicePanel.swift +322 -0
  28. package/native/desktop/darwin-arm64/Sonicloud Voice.app/Contents/Info.plist +10 -0
  29. package/native/desktop/darwin-arm64/Sonicloud Voice.app/Contents/MacOS/sonicloud-voice +0 -0
  30. package/native/desktop/windows.ps1 +9 -0
  31. package/native/win32-x64/README.md +70 -0
  32. package/native/win32-x64/avcodec-58.dll +0 -0
  33. package/native/win32-x64/avutil-56.dll +0 -0
  34. package/native/win32-x64/msvcp140.dll +0 -0
  35. package/native/win32-x64/uMouseSdk.dll +0 -0
  36. package/native/win32-x64/vcruntime140.dll +0 -0
  37. package/native/win32-x64/vcruntime140_1.dll +0 -0
  38. package/package.json +74 -4
  39. package/src/asr/auth.mjs +80 -0
  40. package/src/asr/config.mjs +6 -0
  41. package/src/asr/languages.mjs +28 -0
  42. package/src/asr/stream.mjs +149 -0
  43. package/src/client/assets/contact-wechat.jpg +0 -0
  44. package/src/client/assets/sonicloud.png +0 -0
  45. package/src/client/assets/sonicloud.svg +3 -0
  46. package/src/desktop/presentation.mjs +87 -0
  47. package/src/devices/actions.mjs +46 -0
  48. package/src/devices/config.mjs +9 -0
  49. package/src/devices/diagnostics.mjs +52 -0
  50. package/src/devices/manager.mjs +335 -0
  51. package/src/devices/native-worker.mjs +64 -0
  52. package/src/devices/native.mjs +86 -0
  53. package/src/devices/queue.mjs +32 -0
  54. package/src/devices/recognition.mjs +23 -0
  55. package/src/devices/store.mjs +44 -0
  56. package/src/devices/translate.mjs +44 -0
  57. package/src/host/ai-conversation.mjs +83 -0
  58. package/src/host/index.mjs +96 -0
  59. package/src/host/store.mjs +24 -0
  60. package/src/shared/devices.mjs +69 -0
  61. package/src/shared/languages.mjs +111 -0
  62. package/src/shared/mouse-settings.mjs +22 -0
  63. package/src/shared/remote.mjs +55 -0
  64. package/src/shared/transcript.mjs +16 -0
@@ -0,0 +1,71 @@
1
+ # uMouseSdk 0.4.20 —— 鼠标/领夹麦设备接入 SDK(macOS arm64)
2
+
3
+ 从系统层接入 uMouse 家族设备(USB 2.4G 接收器 / BLE 蓝牙,自动偏好 USB),
4
+ 完成 SN 识别、多设备管理、按键/语音音频/电量/会议事件解析与上抛。
5
+ 内置 SBC / SyPcm / YiChip / ADPCM(TLW 包格式 + 连续流双模式自识别)音频解码。
6
+
7
+ 权威接口文档:`include/umouse_sdk.h`(390 行,含完整注释与**事件 JSON 协议规范**,
8
+ 集成前必读其头部协议说明段——deviceInfo / keyEvent / dpiChanged / meeting 系列 /
9
+ lavalierMicStatus/Battery(领夹麦 0x12/0x13)/ warning 信封的格式定义都在其中)。
10
+
11
+ ## 文件清单
12
+
13
+ - `libuMouseSdk.dylib` → `libuMouseSdk.0.dylib` → `libuMouseSdk.0.4.20.dylib`(主库)
14
+ - **最小化 FFmpeg 闭包(仅 2 个文件,LGPL 2.1+,无 GPL 组件)**:
15
+ `libavcodec.62.dylib` + `libavutil.60.dylib`——按 SDK 实际使用的解码器
16
+ (`sbc`、`adpcm_ima_wav`)定制裁剪构建,依赖表仅系统库,**必须与主库同目录**
17
+ (已改写为 @loader_path 互查,无需 rpath、无需 brew 环境)。
18
+ 本目录不含 x264/x265/vpx/dav1d/SvtAv1/mp3lame/opus/ssl/crypto
19
+ (旧版分发包曾整串携带 brew 全功能 FFmpeg,其中 x264/x265 为 GPL 组件)。
20
+
21
+ ### 第三方许可与重建方法
22
+
23
+ FFmpeg 以 **LGPL-2.1-or-later** 许可随包分发(动态链接,宿主无需开源)。
24
+ 最小构建的完整复现命令(源码 FFmpeg 8.1.2,与库版本 62.28.102/60.26.102 对应):
25
+
26
+ ```bash
27
+ ./configure --enable-shared --disable-static --disable-programs --disable-doc \
28
+ --disable-debug --disable-network --disable-autodetect \
29
+ --disable-avdevice --disable-avfilter --disable-avformat \
30
+ --disable-swscale --disable-swresample \
31
+ --disable-gpl --disable-version3 --disable-everything \
32
+ --enable-decoder=sbc,adpcm_ima_wav --enable-parser=sbc
33
+ ```
34
+
35
+ 如需向最终用户提供许可文本,请附 FFmpeg 官方 LICENSE/LGPL-2.1 文本。
36
+
37
+ ## 最小集成流程(C ABI)
38
+
39
+ ```c
40
+ #include "umouse_sdk.h"
41
+
42
+ um_sdk_init(1); // 装载默认设备规则(debug 日志开关)
43
+ um_register_connected(on_connected); // 设备上线(device_id = SN)
44
+ um_register_disconnected(on_disconnected);
45
+ um_register_message(on_message); // 事件 JSON(协议见头文件)
46
+ um_register_audio(on_audio); // 解码后 PCM(16k mono s16le)
47
+ um_sdk_start(); // 启动监测(可省略,init 后自动)
48
+
49
+ // 语音链路由调用方实现:audio 回调 PCM → 自有识别管线;
50
+ // keyEvent(语音键抬起) → 结束识别。
51
+ ```
52
+
53
+ ## 关键 API 组
54
+
55
+ - 生命周期:`um_sdk_init` / `um_sdk_start` / `um_sdk_close` / `um_sdk_version`
56
+ - 事件注册:`um_register_connected/disconnected/message/audio/raw_frame`
57
+ - 设备规则(RAW 接入自定义硬件):`um_device_rule_*` / `um_set_usb_config` /
58
+ `um_set_ble_config` / `um_usb_add_match` / `um_register_ble_match_device`
59
+ - 运行时控制:`um_set_work_mode[_for]`(RAW/FULL)、`um_set_channel_pref[_for]`
60
+ (0=自动 USB 优先 / 1=仅 USB / 2=仅 BLE)、`um_set_device_limit`、
61
+ `um_set_audio_source`(多设备音频出口选定)、`um_meeting_create/pause/resume`
62
+ - 诊断:`um_enable_crash_report`
63
+
64
+ ## 平台行为要点(macOS)
65
+
66
+ - BLE 设备识别:CoreBluetooth 无 MAC,SDK 以厂商服务 UUID + 家族 MAC 桥
67
+ (ioreg)+ 已知设备集合三路提名,接管时以私有特征订阅确证;配对坏态
68
+ (pairingBroken 警告)仅对确证过/家族 MAC 的端点上抛。
69
+ - 首次运行会请求蓝牙授权;设备重新配对后开/关一次电源即可被配对扫描自举找回。
70
+ - 多设备:默认每规则 4 台、全局 8 台;BLE 多活链超过 2 条会上抛 bleLinkHigh
71
+ 预警(射频调度劣化实测阈值)。
@@ -0,0 +1,17 @@
1
+ import Foundation
2
+
3
+ struct CompatibilityContext: Equatable {
4
+ let pid: Int32
5
+ let bundle: String
6
+ let title: String?
7
+ let document: String?
8
+ let activity: [UInt32]
9
+ }
10
+
11
+ enum CompatibilityPolicy {
12
+ // All foreground applications use the same target and input-activity guards.
13
+ static func canPaste(_ captured: CompatibilityContext, _ current: CompatibilityContext, sameWindow: Bool) -> Bool {
14
+ return captured.pid > 0 && sameWindow && captured == current
15
+ }
16
+ static func canRestoreClipboard(written: Int, current: Int) -> Bool { written == current }
17
+ }
@@ -0,0 +1,197 @@
1
+ using System;
2
+ using System.Collections.Generic;
3
+ using System.Drawing;
4
+ using System.Drawing.Drawing2D;
5
+ using System.Text.RegularExpressions;
6
+ using System.Linq;
7
+ using System.Threading;
8
+ using System.Windows.Automation;
9
+ using System.Windows.Automation.Text;
10
+ using System.Windows.Forms;
11
+ using System.Web.Script.Serialization;
12
+
13
+ namespace Sonicloud {
14
+ sealed class Insertion {
15
+ AutomationElement element;
16
+ string original;
17
+ int[] runtime;
18
+ int start, length;
19
+ static bool Read(AutomationElement target, out string value, out int offset, out int count) {
20
+ value = ""; offset = count = 0;
21
+ object vp, tp;
22
+ if (target.Current.IsPassword || !target.TryGetCurrentPattern(ValuePattern.Pattern, out vp)
23
+ || ((ValuePattern)vp).Current.IsReadOnly || !target.TryGetCurrentPattern(TextPattern.Pattern, out tp)) return false;
24
+ value = ((ValuePattern)vp).Current.Value;
25
+ var pattern = (TextPattern)tp;
26
+ var selected = pattern.GetSelection();
27
+ if (selected.Length != 1) return false;
28
+ var before = pattern.DocumentRange.Clone();
29
+ before.MoveEndpointByRange(TextPatternRangeEndpoint.End, selected[0], TextPatternRangeEndpoint.Start);
30
+ offset = before.GetText(-1).Length; count = selected[0].GetText(-1).Length;
31
+ // UIA text/value views must agree before making any replacement.
32
+ return pattern.DocumentRange.GetText(-1) == value && offset + count <= value.Length;
33
+ }
34
+ public static Insertion Capture() {
35
+ try {
36
+ var target = AutomationElement.FocusedElement;
37
+ string value; int offset, count;
38
+ if (target == null || !Read(target, out value, out offset, out count)) return null;
39
+ return new Insertion { element = target, runtime = target.GetRuntimeId(), original = value, start = offset, length = count };
40
+ } catch { return null; }
41
+ }
42
+ public bool Insert(string text) {
43
+ try {
44
+ var current = AutomationElement.FocusedElement;
45
+ string value; int offset, count;
46
+ if (current == null || !current.GetRuntimeId().SequenceEqual(runtime)
47
+ || !Read(current, out value, out offset, out count) || value != original || offset != start || count != length) return false;
48
+ ((ValuePattern)element.GetCurrentPattern(ValuePattern.Pattern)).SetValue(original.Substring(0, start) + text + original.Substring(start + length));
49
+ // Setting value succeeded; caret placement is best effort, never repeat insertion.
50
+ try {
51
+ var range = ((TextPattern)element.GetCurrentPattern(TextPattern.Pattern)).DocumentRange;
52
+ range.MoveEndpointByRange(TextPatternRangeEndpoint.End, range, TextPatternRangeEndpoint.Start);
53
+ range.Move(TextUnit.Character, start + text.Length); range.Select();
54
+ } catch { }
55
+ return true;
56
+ } catch { return false; }
57
+ }
58
+ }
59
+ static class CapsuleShape {
60
+ public static GraphicsPath Create(RectangleF bounds, float radius) {
61
+ var path = new GraphicsPath(); var diameter = radius * 2;
62
+ path.AddArc(bounds.Left, bounds.Top, diameter, diameter, 180, 90);
63
+ path.AddArc(bounds.Right - diameter, bounds.Top, diameter, diameter, 270, 90);
64
+ path.AddArc(bounds.Right - diameter, bounds.Bottom - diameter, diameter, diameter, 0, 90);
65
+ path.AddArc(bounds.Left, bounds.Bottom - diameter, diameter, diameter, 90, 90);
66
+ path.CloseFigure(); return path;
67
+ }
68
+ }
69
+ sealed class SingleLineText : Control {
70
+ public SingleLineText() { SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); }
71
+ protected override void OnPaint(PaintEventArgs e) {
72
+ TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, ForeColor,
73
+ TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.NoPadding);
74
+ }
75
+ protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); Invalidate(); }
76
+ }
77
+ sealed class Waveform : Control {
78
+ public double Phase;
79
+ public Waveform() { SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); }
80
+ protected override void OnPaint(PaintEventArgs e) {
81
+ e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
82
+ using (var brush = new SolidBrush(Color.SeaGreen)) {
83
+ for (int i = 0; i < 5; i++) {
84
+ float height = (float)(7 + 18 * (0.5 + 0.5 * Math.Sin(Phase * (1 + i % 3 * 0.12) + i * 0.9)));
85
+ using (var bar = CapsuleShape.Create(new RectangleF(i * 5, (Height - height) / 2, 3, height), 1.5f)) e.Graphics.FillPath(brush, bar);
86
+ }
87
+ }
88
+ }
89
+ }
90
+ public sealed class VoicePanel : Form {
91
+ readonly SingleLineText text = new SingleLineText();
92
+ readonly Waveform waveform = new Waveform();
93
+ readonly Button close = new Button(), copy = new Button();
94
+ readonly JavaScriptSerializer json = new JavaScriptSerializer { MaxJsonLength = 300000 };
95
+ readonly System.Windows.Forms.Timer pulse = new System.Windows.Forms.Timer { Interval = 40 };
96
+ string session = "", preview = "", phase = "", message = "";
97
+ bool active;
98
+ Insertion insertion;
99
+ Screen screen;
100
+ protected override bool ShowWithoutActivation { get { return true; } }
101
+ protected override CreateParams CreateParams {
102
+ get { var p = base.CreateParams; p.ExStyle |= 0x08000000 | 0x00000080; return p; }
103
+ }
104
+ protected override void WndProc(ref Message m) {
105
+ if (m.Msg == 0x21) { m.Result = new IntPtr(3); return; }
106
+ base.WndProc(ref m);
107
+ }
108
+ VoicePanel() {
109
+ FormBorderStyle = FormBorderStyle.None; ShowInTaskbar = false; TopMost = true;
110
+ BackColor = Color.White; Font = new Font("Microsoft YaHei UI", 10);
111
+ AccessibleName = "声云语音";
112
+ text.AccessibleName = "语音识别结果";
113
+ close.Text = ""; close.FlatStyle = FlatStyle.Flat; close.FlatAppearance.BorderSize = 0;
114
+ var icon = new Bitmap(16, 16);
115
+ using (var graphics = Graphics.FromImage(icon))
116
+ using (var pen = new Pen(Color.DimGray, 1.8f)) {
117
+ graphics.SmoothingMode = SmoothingMode.AntiAlias;
118
+ pen.StartCap = pen.EndCap = LineCap.Round;
119
+ graphics.DrawLine(pen, 3, 3, 12, 12); graphics.DrawLine(pen, 12, 3, 3, 12);
120
+ }
121
+ close.Image = icon; close.AccessibleName = "取消";
122
+ copy.Text = "复制结果";
123
+ Controls.AddRange(new Control[] { text, waveform, close, copy });
124
+ close.Click += delegate {
125
+ if (active) Emit(new Dictionary<string, object> { { "event", "cancel" }, { "sessionId", session } });
126
+ active = false; insertion = null; preview = message = ""; Hide();
127
+ };
128
+ copy.Click += delegate { try { Clipboard.SetText(preview); copy.Text = "已复制"; } catch { copy.Text = "复制失败"; } };
129
+ pulse.Tick += delegate { waveform.Phase += 0.25; waveform.Invalidate(); };
130
+ VisibleChanged += delegate { pulse.Enabled = Visible && active; };
131
+ Microsoft.Win32.SystemEvents.DisplaySettingsChanged += DisplayChanged;
132
+ FormClosed += delegate { pulse.Dispose(); close.Image.Dispose(); Microsoft.Win32.SystemEvents.DisplaySettingsChanged -= DisplayChanged; };
133
+ }
134
+ void DisplayChanged(object sender, EventArgs e) { if (!IsDisposed && Visible) BeginInvoke((Action)Render); }
135
+ void Render() {
136
+ var display = Screen.AllScreens.FirstOrDefault(s => screen != null && s.DeviceName == screen.DeviceName) ?? Screen.PrimaryScreen;
137
+ var area = display.WorkingArea; var width = Math.Min(720, area.Width - 48); var height = 48;
138
+ Bounds = new Rectangle(area.Left + (area.Width - width) / 2, area.Bottom - height - 24, width, height);
139
+ using (var outline = CapsuleShape.Create(new RectangleF(0, 0, width, height), height / 2f)) {
140
+ var previous = Region; Region = new Region(outline); if (previous != null) previous.Dispose();
141
+ }
142
+ waveform.SetBounds(20, (height - 26) / 2, 23, 26);
143
+ close.SetBounds(width - 44, (height - 28) / 2, 28, 28); copy.SetBounds(width - 146, (height - 32) / 2, 96, 32);
144
+ waveform.Visible = active; copy.Visible = !active && preview.Length > 0; close.AccessibleName = active ? "取消" : "关闭";
145
+ int left = active ? 54 : 22, right = copy.Visible ? copy.Left : close.Left;
146
+ text.SetBounds(left, 0, Math.Max(0, right - left - 12), height);
147
+ string status = message.Length > 0 ? message : phase == "finishing" ? "正在整理…" : phase == "translating" ? "正在翻译…" : "";
148
+ string displayText = (status + " " + preview).Trim();
149
+ text.Text = Regex.Replace(displayText, @"[\r\n\t\u0085\u2028\u2029]+", " ");
150
+ pulse.Enabled = active;
151
+ Show();
152
+ }
153
+ static string Get(Dictionary<string, object> item, string key) { object value; return item.TryGetValue(key, out value) ? Convert.ToString(value) : ""; }
154
+ void Emit(Dictionary<string, object> value) { Console.WriteLine(json.Serialize(value)); Console.Out.Flush(); }
155
+ void HandleCommand(Dictionary<string, object> item) {
156
+ string command = Get(item, "command"), incoming = Get(item, "sessionId"); bool ok = true, inserted = false;
157
+ if (command == "begin") {
158
+ session = incoming; preview = message = ""; phase = "connecting"; active = true;
159
+ insertion = Get(item, "action") == "speechSearch" || Get(item, "action") == "ai_input" ? null : Insertion.Capture();
160
+ screen = Screen.FromPoint(Cursor.Position); copy.Text = "复制结果"; Render();
161
+ } else if (incoming.Length > 0 && incoming != session) ok = false;
162
+ else if (command == "result" && active) {
163
+ preview = Get(item, "text"); inserted = insertion != null && insertion.Insert(preview);
164
+ insertion = null; active = false;
165
+ if (inserted) Hide(); else { message = "未回填,可复制结果"; Render(); }
166
+ } else if (command == "event") {
167
+ switch (Get(item, "type")) {
168
+ case "preview": if (active) { preview = Get(item, "text"); Render(); } break;
169
+ case "phase": if (active) { phase = Get(item, "phase"); Render(); } break;
170
+ case "notice": message = Get(item, "message"); Render(); break;
171
+ case "failed": active = false; insertion = null; message = Get(item, "message"); Render(); break;
172
+ case "cancelled": case "finished": active = false; insertion = null; preview = message = ""; Hide(); break;
173
+ }
174
+ } else ok = false;
175
+ object id; if (item.TryGetValue("id", out id)) Emit(new Dictionary<string, object> { { "id", id }, { "ok", ok }, { "value", inserted } });
176
+ }
177
+ [STAThread] public static void Run() {
178
+ Application.EnableVisualStyles();
179
+ using (var form = new VoicePanel()) {
180
+ var handle = form.Handle;
181
+ var input = new Thread(() => {
182
+ string line;
183
+ while ((line = Console.ReadLine()) != null) {
184
+ if (line.Length > 300000) continue;
185
+ try {
186
+ var item = new JavaScriptSerializer { MaxJsonLength = 300000 }.Deserialize<Dictionary<string, object>>(line);
187
+ form.BeginInvoke((Action)(() => form.HandleCommand(item)));
188
+ } catch { }
189
+ }
190
+ if (!form.IsDisposed) form.BeginInvoke((Action)(() => Application.ExitThread()));
191
+ });
192
+ input.IsBackground = true; input.Start();
193
+ Application.Run();
194
+ }
195
+ }
196
+ }
197
+ }
@@ -0,0 +1,322 @@
1
+ import AppKit
2
+ import ApplicationServices
3
+ import QuartzCore
4
+
5
+ func emit(_ value: [String: Any]) {
6
+ guard let data = try? JSONSerialization.data(withJSONObject: value) else { return }
7
+ FileHandle.standardOutput.write(data + Data([10]))
8
+ }
9
+ func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? {
10
+ var value: CFTypeRef?
11
+ return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil
12
+ }
13
+ func focus() -> AXUIElement? {
14
+ guard let value = attribute(AXUIElementCreateSystemWide(), kAXFocusedUIElementAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() else { return nil }
15
+ return (value as! AXUIElement)
16
+ }
17
+ func selection(_ element: AXUIElement) -> CFRange? {
18
+ guard let raw = attribute(element, kAXSelectedTextRangeAttribute), CFGetTypeID(raw) == AXValueGetTypeID() else { return nil }
19
+ let value = raw as! AXValue
20
+ var range = CFRange()
21
+ return AXValueGetType(value) == .cfRange && AXValueGetValue(value, .cfRange, &range) ? range : nil
22
+ }
23
+ // Capture readable text/selection when available; pasting does not require AX write support.
24
+ final class InputSnapshot {
25
+ let element: AXUIElement?
26
+ let value: String?
27
+ let range: CFRange?
28
+ init?() {
29
+ element = focus()
30
+ if let target = element {
31
+ guard (attribute(target, kAXSubroleAttribute) as? String) != "AXSecureTextField",
32
+ (attribute(target, kAXEnabledAttribute) as? Bool) != false else { return nil }
33
+ value = attribute(target, kAXValueAttribute) as? String
34
+ range = selection(target)
35
+ } else { value = nil; range = nil }
36
+ }
37
+ func unchanged() -> Bool {
38
+ let current = focus()
39
+ if let target = element {
40
+ guard let current = current, CFEqual(current, target),
41
+ (attribute(current, kAXSubroleAttribute) as? String) != "AXSecureTextField",
42
+ (attribute(current, kAXEnabledAttribute) as? Bool) != false else { return false }
43
+ if let value = value, (attribute(current, kAXValueAttribute) as? String) != value { return false }
44
+ if let range = range {
45
+ guard let selected = selection(current), selected.location == range.location, selected.length == range.length else { return false }
46
+ }
47
+ } else if current != nil { return false }
48
+ return true
49
+ }
50
+ }
51
+ // Default insertion uses guarded system paste. Event counters contain no keyboard text.
52
+ final class ClipboardInsertion {
53
+ static var restoreClipboard: (() -> Void)?
54
+ static var transaction: UUID?
55
+ let context: CompatibilityContext
56
+ let window: AXUIElement
57
+ let input: InputSnapshot
58
+ static func current() -> (CompatibilityContext, AXUIElement)? {
59
+ guard AXIsProcessTrusted(), let app = NSWorkspace.shared.frontmostApplication,
60
+ app.processIdentifier != ProcessInfo.processInfo.processIdentifier,
61
+ let raw = attribute(AXUIElementCreateApplication(app.processIdentifier), kAXFocusedWindowAttribute),
62
+ CFGetTypeID(raw) == AXUIElementGetTypeID() else { return nil }
63
+ let window = raw as! AXUIElement
64
+ guard (attribute(window, kAXMinimizedAttribute) as? Bool) != true else { return nil }
65
+ let events: [CGEventType] = [.keyDown, .flagsChanged, .leftMouseDown, .rightMouseDown, .otherMouseDown, .scrollWheel]
66
+ let context = CompatibilityContext(pid: app.processIdentifier, bundle: app.bundleIdentifier ?? "",
67
+ title: attribute(window, kAXTitleAttribute) as? String,
68
+ document: attribute(window, kAXDocumentAttribute) as? String,
69
+ activity: events.map { CGEventSource.counterForEventType(.combinedSessionState, eventType: $0) })
70
+ return (context, window)
71
+ }
72
+ init?() {
73
+ guard let (context, window) = Self.current(), let input = InputSnapshot() else { return nil }
74
+ self.context = context; self.window = window; self.input = input
75
+ }
76
+ func unchanged() -> Bool {
77
+ guard let (now, focusedWindow) = Self.current() else { return false }
78
+ return input.unchanged() && CompatibilityPolicy.canPaste(context, now, sameWindow: CFEqual(window, focusedWindow))
79
+ }
80
+ func insert(_ text: String, completion: @escaping (Bool) -> Void) {
81
+ guard unchanged(), let source = CGEventSource(stateID: .privateState),
82
+ let down = CGEvent(keyboardEventSource: source, virtualKey: 9, keyDown: true),
83
+ let up = CGEvent(keyboardEventSource: source, virtualKey: 9, keyDown: false) else { completion(false); return }
84
+ Self.restoreClipboard?(); Self.restoreClipboard = nil
85
+ let transaction = UUID(); Self.transaction = transaction
86
+ let pasteboard = NSPasteboard.general
87
+ let originalChange = pasteboard.changeCount
88
+ var originals: [NSPasteboardItem] = []
89
+ for item in pasteboard.pasteboardItems ?? [] {
90
+ let saved = NSPasteboardItem()
91
+ for type in item.types {
92
+ guard let data = item.data(forType: type) else { completion(false); return }
93
+ saved.setData(data, forType: type)
94
+ }
95
+ originals.append(saved)
96
+ }
97
+ // Recheck after copying promised clipboard data, which may take time.
98
+ guard unchanged(), pasteboard.changeCount == originalChange else { completion(false); return }
99
+ let payload = NSPasteboardItem()
100
+ payload.setString(text, forType: .string)
101
+ payload.setData(Data(), forType: NSPasteboard.PasteboardType("org.nspasteboard.TransientType"))
102
+ pasteboard.clearContents()
103
+ guard pasteboard.writeObjects([payload]) else {
104
+ pasteboard.clearContents(); if !originals.isEmpty { pasteboard.writeObjects(originals) }
105
+ completion(false); return
106
+ }
107
+ let writtenChange = pasteboard.changeCount
108
+ down.flags = .maskCommand; up.flags = .maskCommand
109
+ down.postToPid(context.pid); up.postToPid(context.pid)
110
+ // Keep the payload until the target has handled Paste. Restore only our own write;
111
+ // never overwrite something the user or another application copied in the meantime.
112
+ var restored = false
113
+ let restore = {
114
+ guard !restored else { return }
115
+ restored = true
116
+ if CompatibilityPolicy.canRestoreClipboard(written: writtenChange, current: pasteboard.changeCount) {
117
+ pasteboard.clearContents(); if !originals.isEmpty { pasteboard.writeObjects(originals) }
118
+ }
119
+ }
120
+ Self.restoreClipboard = restore
121
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
122
+ restore()
123
+ if Self.transaction == transaction { Self.restoreClipboard = nil; Self.transaction = nil }
124
+ completion(true)
125
+ }
126
+ }
127
+ }
128
+ // Draw only the capsule; no rectangular visual-effect backing is allowed outside it.
129
+ final class CapsuleView: NSView {
130
+ override var isOpaque: Bool { false }
131
+ override func draw(_ dirtyRect: NSRect) {
132
+ let outline = NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5),
133
+ xRadius: bounds.height / 2, yRadius: bounds.height / 2)
134
+ NSColor.windowBackgroundColor.withAlphaComponent(0.97).setFill(); outline.fill()
135
+ NSColor(calibratedWhite: 0.97, alpha: 1).setStroke(); outline.lineWidth = 1; outline.stroke()
136
+ }
137
+ }
138
+ final class WaveformView: NSView {
139
+ private let bars = (0..<5).map { _ in CALayer() }
140
+ private var running = false
141
+ override init(frame frameRect: NSRect) {
142
+ super.init(frame: frameRect)
143
+ wantsLayer = true
144
+ setAccessibilityElement(true); setAccessibilityLabel("语音处理中")
145
+ for bar in bars { bar.backgroundColor = NSColor.systemGreen.cgColor; bar.cornerRadius = 1.5; layer?.addSublayer(bar) }
146
+ }
147
+ required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
148
+ override func layout() {
149
+ super.layout()
150
+ CATransaction.begin(); CATransaction.setDisableActions(true)
151
+ for (index, bar) in bars.enumerated() {
152
+ let height: CGFloat = [10, 18, 26, 18, 10][index]
153
+ bar.frame = NSRect(x: CGFloat(index) * 5, y: (bounds.height - height) / 2, width: 3, height: height)
154
+ }
155
+ CATransaction.commit()
156
+ }
157
+ func animate(_ enabled: Bool) {
158
+ let enabled = enabled && !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
159
+ guard enabled != running else { return }
160
+ running = enabled
161
+ for (index, bar) in bars.enumerated() {
162
+ bar.removeAnimation(forKey: "voice-wave")
163
+ if enabled {
164
+ let animation = CABasicAnimation(keyPath: "transform.scale.y")
165
+ animation.fromValue = 0.3; animation.toValue = 1
166
+ animation.duration = 0.32 + Double(index % 3) * 0.07
167
+ animation.beginTime = CACurrentMediaTime() - Double(index) * 0.12
168
+ animation.autoreverses = true; animation.repeatCount = .infinity
169
+ animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
170
+ bar.add(animation, forKey: "voice-wave")
171
+ }
172
+ }
173
+ }
174
+ }
175
+ final class Panel: NSPanel {
176
+ override var canBecomeKey: Bool { false }
177
+ override var canBecomeMain: Bool { false }
178
+ }
179
+ final class VoiceUI: NSObject {
180
+ let panel = Panel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
181
+ let text = NSTextField(labelWithString: "")
182
+ let waveform = WaveformView(frame: .zero)
183
+ let closeButton = NSButton(title: "", target: nil, action: nil)
184
+ let copyButton = NSButton(title: "复制结果", target: nil, action: nil)
185
+ var session = "", preview = "", phase = "connecting", message = ""
186
+ var active = false
187
+ var insertion: ClipboardInsertion?
188
+ var resultPending = false
189
+ var screen: NSScreen?
190
+ override init() {
191
+ super.init()
192
+ panel.level = .statusBar
193
+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary]
194
+ panel.hidesOnDeactivate = false
195
+ panel.isFloatingPanel = true
196
+ panel.isReleasedWhenClosed = false
197
+ panel.hasShadow = true
198
+ panel.backgroundColor = .clear
199
+ panel.isOpaque = false
200
+ let content = CapsuleView()
201
+ panel.contentView = content
202
+ text.font = .systemFont(ofSize: 15)
203
+ text.lineBreakMode = .byTruncatingHead
204
+ text.maximumNumberOfLines = 1
205
+ text.cell?.usesSingleLineMode = true
206
+ text.cell?.wraps = false
207
+ text.cell?.isScrollable = false
208
+ text.setAccessibilityLabel("语音识别结果")
209
+ for view in [waveform, text, closeButton, copyButton] { content.addSubview(view) }
210
+ closeButton.image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "取消")?.withSymbolConfiguration(NSImage.SymbolConfiguration(pointSize: 14, weight: .medium))
211
+ closeButton.imagePosition = .imageOnly
212
+ closeButton.isBordered = false
213
+ closeButton.contentTintColor = .secondaryLabelColor
214
+ closeButton.target = self; closeButton.action = #selector(close)
215
+ copyButton.target = self; copyButton.action = #selector(copyResult)
216
+ copyButton.isHidden = true
217
+ NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in self?.position() }
218
+ }
219
+ func position() {
220
+ let display = NSScreen.screens.first(where: { $0 == screen }) ?? NSScreen.main ?? NSScreen.screens.first
221
+ guard let frame = display?.visibleFrame else { return }
222
+ let width = min(720, max(280, frame.width - 48)), height: CGFloat = 48
223
+ panel.setFrame(NSRect(x: frame.midX - width / 2, y: frame.minY + 24, width: width, height: height), display: true)
224
+ waveform.frame = NSRect(x: 20, y: (height - 26) / 2, width: 23, height: 26)
225
+ closeButton.frame = NSRect(x: width - 44, y: (height - 28) / 2, width: 28, height: 28)
226
+ copyButton.frame = NSRect(x: width - 146, y: (height - 32) / 2, width: 96, height: 32)
227
+ let left: CGFloat = active ? 54 : 22
228
+ let right = copyButton.isHidden ? closeButton.frame.minX : copyButton.frame.minX
229
+ let textHeight = ceil(text.intrinsicContentSize.height)
230
+ text.frame = NSRect(x: left, y: (height - textHeight) / 2, width: max(0, right - left - 12), height: textHeight)
231
+ panel.contentView?.needsDisplay = true
232
+ panel.invalidateShadow()
233
+ }
234
+ func render() {
235
+ waveform.isHidden = !active
236
+ waveform.animate(active)
237
+ closeButton.setAccessibilityLabel(active ? "取消" : "关闭")
238
+ closeButton.toolTip = active ? "取消" : "关闭"
239
+ copyButton.isHidden = active || preview.isEmpty
240
+ let status = message.isEmpty ? (["finishing": "正在整理…", "translating": "正在翻译…"][phase] ?? "") : message
241
+ let fullText = [status, preview].filter { !$0.isEmpty }.joined(separator: " ")
242
+ text.stringValue = fullText.components(separatedBy: .newlines).joined(separator: " ").replacingOccurrences(of: "\t", with: " ")
243
+ text.toolTip = fullText
244
+ position(); panel.orderFrontRegardless()
245
+ }
246
+ func hide() { waveform.animate(false); panel.orderOut(nil) }
247
+ @objc func close() {
248
+ if active { emit(["event": "cancel", "sessionId": session]) }
249
+ active = false; insertion = nil; preview = ""; message = ""; hide()
250
+ }
251
+ @objc func copyResult() {
252
+ NSPasteboard.general.clearContents()
253
+ NSPasteboard.general.setString(preview, forType: .string)
254
+ copyButton.title = "已复制"
255
+ }
256
+ func finishInsertion(_ inserted: Bool, changed: Bool) {
257
+ insertion = nil; active = false; resultPending = false
258
+ if inserted { preview = ""; message = ""; hide() }
259
+ else {
260
+ message = !AXIsProcessTrusted() ? "请授权辅助功能以回填;可复制结果"
261
+ : changed ? "输入目标已变化或不支持写入,可复制结果" : "此输入框不支持自动回填,可复制结果"
262
+ render()
263
+ }
264
+ }
265
+ func shutdown() {
266
+ ClipboardInsertion.restoreClipboard?(); ClipboardInsertion.restoreClipboard = nil
267
+ NSApplication.shared.terminate(nil)
268
+ }
269
+ func handle(_ command: [String: Any]) {
270
+ let name = command["command"] as? String ?? ""
271
+ let incoming = command["sessionId"] as? String ?? ""
272
+ var success = true
273
+ let inserted = false
274
+ if name == "begin" {
275
+ session = incoming; preview = ""; message = ""; phase = "connecting"; active = true
276
+ screen = NSScreen.screens.first(where: { NSMouseInRect(NSEvent.mouseLocation, $0.frame, false) })
277
+ insertion = ["speechSearch", "ai_input"].contains(command["action"] as? String ?? "") ? nil : ClipboardInsertion()
278
+ resultPending = false
279
+ copyButton.title = "复制结果"; render()
280
+ } else if !incoming.isEmpty && incoming != session { success = false }
281
+ else if name == "result" && active && !resultPending {
282
+ preview = command["text"] as? String ?? ""
283
+ if let compatibility = insertion {
284
+ resultPending = true
285
+ compatibility.insert(preview) { didInsert in
286
+ if self.session == incoming && self.active {
287
+ self.finishInsertion(didInsert, changed: true)
288
+ }
289
+ if let id = command["id"] { emit(["id": id, "ok": true, "value": didInsert]) }
290
+ }
291
+ return
292
+ }
293
+ finishInsertion(inserted, changed: insertion != nil)
294
+ } else if name == "event" {
295
+ switch command["type"] as? String {
296
+ case "preview": if active { preview = command["text"] as? String ?? ""; render() }
297
+ case "phase": if active { phase = command["phase"] as? String ?? phase; render() }
298
+ case "failed": active = false; insertion = nil; message = command["message"] as? String ?? "语音处理失败"; render()
299
+ case "notice": message = command["message"] as? String ?? ""; render()
300
+ case "finished", "cancelled": active = false; insertion = nil; preview = ""; message = ""; hide()
301
+ default: break
302
+ }
303
+ } else { success = false }
304
+ if let id = command["id"] { emit(["id": id, "ok": success, "value": inserted]) }
305
+ }
306
+ }
307
+ @main
308
+ struct VoiceApplication {
309
+ static func main() {
310
+ let application = NSApplication.shared
311
+ application.setActivationPolicy(.accessory)
312
+ let ui = VoiceUI()
313
+ DispatchQueue.global(qos: .userInitiated).async {
314
+ while let line = readLine() {
315
+ guard line.utf8.count <= 300000, let data = line.data(using: .utf8), let command = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { continue }
316
+ DispatchQueue.main.async { ui.handle(command) }
317
+ }
318
+ DispatchQueue.main.async { ui.shutdown() }
319
+ }
320
+ application.run()
321
+ }
322
+ }
@@ -0,0 +1,10 @@
1
+ <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>
2
+ <key>CFBundleIdentifier</key><string>com.sonicloud.voice-panel</string>
3
+ <key>CFBundleName</key><string>Sonicloud Voice</string>
4
+ <key>CFBundleExecutable</key><string>sonicloud-voice</string>
5
+ <key>CFBundlePackageType</key><string>APPL</string>
6
+ <key>CFBundleVersion</key><string>1</string>
7
+ <key>LSUIElement</key><true/>
8
+ <key>NSHighResolutionCapable</key><true/>
9
+ <key>LSMinimumSystemVersion</key><string>11.0</string>
10
+ </dict></plist>
@@ -0,0 +1,9 @@
1
+ $ErrorActionPreference = 'Stop'
2
+ [Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
3
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
4
+ Add-Type -AssemblyName System.Windows.Forms, System.Drawing, UIAutomationClient, UIAutomationTypes, System.Web.Extensions
5
+ $references = @('System.Windows.Forms', 'System.Drawing', 'System.Web.Extensions', 'System.Core', 'WindowsBase',
6
+ [System.Windows.Automation.AutomationElement].Assembly.Location,
7
+ [System.Windows.Automation.Text.TextPatternRangeEndpoint].Assembly.Location)
8
+ Add-Type -Path (Join-Path $PSScriptRoot 'VoicePanel.cs') -ReferencedAssemblies $references
9
+ [Sonicloud.VoicePanel]::Run()