@sonicloud/dsh-sonicloud-device 0.1.3 → 0.1.5
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.
- package/CHANGELOG.md +37 -1
- package/CHANGELOG.zh.md +37 -1
- package/README.md +18 -14
- package/README.zh.md +9 -5
- package/dist/build.json +1 -1
- package/dist/client.js +2112 -120
- package/docs/contributing/development.md +7 -5
- package/docs/specs/ci-cd.md +5 -4
- package/docs/specs/mouse-settings.md +1 -1
- package/docs/specs/multilingual.md +98 -0
- package/docs/specs/smart-mouse-plugin.md +6 -3
- package/locale/de.json +7 -0
- package/locale/en.json +7 -0
- package/locale/es.json +7 -0
- package/locale/fr.json +7 -0
- package/locale/ja.json +7 -0
- package/locale/pt.json +7 -0
- package/locale/ru.json +7 -0
- package/locale/zh.json +7 -0
- package/native/desktop/VOICE_SOURCE.json +2 -2
- package/native/desktop/VoicePanel.cs +70 -33
- package/native/desktop/VoicePanel.swift +58 -21
- package/native/desktop/darwin-arm64/Sonicloud Voice.app/Contents/MacOS/sonicloud-voice +0 -0
- package/native/screenshot/README.md +9 -4
- package/native/screenshot/SOURCE.json +48 -17
- package/native/screenshot/darwin-arm64/screentool-macos-1.2.2.zip +0 -0
- package/native/screenshot/helper-i18n/de.json +85 -0
- package/native/screenshot/helper-i18n/es.json +85 -0
- package/native/screenshot/helper-i18n/fr.json +85 -0
- package/native/screenshot/patches/{hide-cloud-actions.patch → macos/hide-cloud-actions.patch} +84 -76
- package/native/screenshot/patches/macos/mac-clang-compat.patch +14 -0
- package/native/screenshot/patches/macos/mac-color-panel.patch +40 -0
- package/native/screenshot/patches/macos/mac-permissions.patch +549 -0
- package/native/screenshot/patches/macos/mac-ui-focus.patch +658 -0
- package/native/screenshot/patches/macos/upstream-files.json +77 -0
- package/native/screenshot/patches/upstream-files.json +12 -8
- package/native/screenshot/win32-x64/i18n/de.json +85 -0
- package/native/screenshot/win32-x64/i18n/es.json +85 -0
- package/native/screenshot/win32-x64/i18n/fr.json +85 -0
- package/native/screenshot/win32-x64/screenhelper.exe +0 -0
- package/package.json +5 -3
- package/src/asr/auth.mjs +9 -8
- package/src/asr/config.mjs +1 -1
- package/src/asr/stream.mjs +25 -24
- package/src/desktop/presentation.mjs +18 -12
- package/src/desktop/screenshot-shortcut-worker.mjs +188 -0
- package/src/desktop/screenshot-shortcut.mjs +266 -0
- package/src/desktop/screenshot-worker.mjs +49 -32
- package/src/desktop/screenshot.mjs +46 -26
- package/src/devices/actions.mjs +7 -6
- package/src/devices/config.mjs +2 -1
- package/src/devices/diagnostics.mjs +4 -3
- package/src/devices/manager.mjs +77 -43
- package/src/devices/native-worker.mjs +4 -3
- package/src/devices/native.mjs +9 -8
- package/src/devices/queue.mjs +4 -3
- package/src/devices/recognition.mjs +5 -4
- package/src/devices/store.mjs +3 -2
- package/src/devices/translate.mjs +11 -10
- package/src/host/ai-conversation.mjs +8 -7
- package/src/host/index.mjs +13 -3
- package/src/host/locale.mjs +44 -0
- package/src/shared/devices.mjs +13 -12
- package/src/shared/i18n.mjs +47 -0
- package/src/shared/locales/de.json +181 -0
- package/src/shared/locales/en.json +181 -0
- package/src/shared/locales/es.json +181 -0
- package/src/shared/locales/fr.json +181 -0
- package/src/shared/locales/ja.json +181 -0
- package/src/shared/locales/pt.json +181 -0
- package/src/shared/locales/ru.json +181 -0
- package/src/shared/locales/zh.json +181 -0
- package/src/shared/remote.mjs +7 -1
- package/src/shared/screenshot-shortcut.mjs +50 -0
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { message as msg, nativeDictionary, resolveLocale, safeMessage } from '../shared/i18n.mjs';
|
|
1
2
|
import { spawn } from 'node:child_process';
|
|
2
3
|
import { createInterface } from 'node:readline';
|
|
3
4
|
import { fileURLToPath } from 'node:url';
|
|
@@ -7,10 +8,10 @@ import { chmodSync, existsSync } from 'node:fs';
|
|
|
7
8
|
export class DesktopPresentation {
|
|
8
9
|
constructor({ platform = process.platform, arch = process.arch, launch = spawn, timeoutMs = 10000 } = {}) {
|
|
9
10
|
Object.assign(this, { platform, arch, launch, timeoutMs });
|
|
10
|
-
this.requests = new Map(); this.sequence = 0;
|
|
11
|
+
this.requests = new Map(); this.sequence = 0; this.locale = 'en';
|
|
11
12
|
}
|
|
12
13
|
start() {
|
|
13
|
-
if (this.closed) throw new Error('
|
|
14
|
+
if (this.closed) throw new Error(msg('error.closed'));
|
|
14
15
|
if (this.child) return;
|
|
15
16
|
const root = new URL('../../native/desktop/', import.meta.url);
|
|
16
17
|
let file, args = [];
|
|
@@ -21,7 +22,7 @@ export class DesktopPresentation {
|
|
|
21
22
|
}
|
|
22
23
|
else if (this.platform === 'win32') {
|
|
23
24
|
file = 'powershell.exe'; args = ['-NoProfile', '-NonInteractive', '-STA', '-ExecutionPolicy', 'Bypass', '-File', fileURLToPath(new URL('windows.ps1', root))];
|
|
24
|
-
} else throw new Error('
|
|
25
|
+
} else throw new Error(msg('error.panel'));
|
|
25
26
|
const child = this.launch(file, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
|
|
26
27
|
this.child = child;
|
|
27
28
|
const lines = createInterface({ input: child.stdout });
|
|
@@ -33,19 +34,24 @@ export class DesktopPresentation {
|
|
|
33
34
|
if (pending) {
|
|
34
35
|
clearTimeout(pending.timer); this.requests.delete(message.id);
|
|
35
36
|
if (message.ok) pending.resolve(message.value);
|
|
36
|
-
else pending.reject(new Error(message.message || '
|
|
37
|
+
else pending.reject(new Error(message.message || msg('error.panel')));
|
|
37
38
|
}
|
|
38
39
|
});
|
|
39
40
|
const failed = () => {
|
|
40
41
|
if (this.child !== child) return;
|
|
41
42
|
this.child = undefined; lines.close();
|
|
42
|
-
for (const { reject, timer } of this.requests.values()) { clearTimeout(timer); reject(new Error('
|
|
43
|
+
for (const { reject, timer } of this.requests.values()) { clearTimeout(timer); reject(new Error(msg('error.panel'))); }
|
|
43
44
|
this.requests.clear();
|
|
44
45
|
if (!this.closed) this.onFault?.();
|
|
45
46
|
};
|
|
46
47
|
child.once('error', failed); child.once('exit', failed);
|
|
47
48
|
child.stdin.on('error', failed);
|
|
48
49
|
child.stderr.resume();
|
|
50
|
+
this.setLocale(this.locale);
|
|
51
|
+
}
|
|
52
|
+
setLocale(locale) {
|
|
53
|
+
this.locale = resolveLocale(locale);
|
|
54
|
+
this.send({ command: 'locale', language: this.locale, dictionary: nativeDictionary(this.locale) });
|
|
49
55
|
}
|
|
50
56
|
send(message) {
|
|
51
57
|
if (!this.child || this.closed) return;
|
|
@@ -56,7 +62,7 @@ export class DesktopPresentation {
|
|
|
56
62
|
const id = ++this.sequence;
|
|
57
63
|
return new Promise((resolve, reject) => {
|
|
58
64
|
const timer = setTimeout(() => {
|
|
59
|
-
this.requests.delete(id); reject(new Error('
|
|
65
|
+
this.requests.delete(id); reject(new Error(msg('error.timeout')));
|
|
60
66
|
if (killOnTimeout) this.child?.kill();
|
|
61
67
|
}, this.timeoutMs);
|
|
62
68
|
this.requests.set(id, { resolve, reject, timer }); this.send({ ...message, id });
|
|
@@ -67,27 +73,27 @@ export class DesktopPresentation {
|
|
|
67
73
|
await this.request({ command: 'begin', sessionId: run.id, action: run.action });
|
|
68
74
|
}
|
|
69
75
|
async permissions(action = 'check') {
|
|
70
|
-
if (!['check', 'accessibility', 'refresh'].includes(action)) throw new Error('
|
|
71
|
-
if (this.closed) throw new Error('
|
|
76
|
+
if (!['check', 'accessibility', 'refresh'].includes(action)) throw new Error(msg('error.permission'));
|
|
77
|
+
if (this.closed) throw new Error(msg('error.closed'));
|
|
72
78
|
if (this.platform !== 'darwin') return { supported: false, accessibility: true, helperApp: '' };
|
|
73
79
|
const value = await this.request({ command: 'permissions', action }, { killOnTimeout: false });
|
|
74
80
|
if (!value || value.supported !== true || typeof value.accessibility !== 'boolean' || typeof value.helperApp !== 'string')
|
|
75
|
-
throw new Error('
|
|
81
|
+
throw new Error(msg('error.permission'));
|
|
76
82
|
return value;
|
|
77
83
|
}
|
|
78
84
|
event(event) {
|
|
79
|
-
if (event.type === 'devices' || event.type === 'request' || event.type === 'result') return;
|
|
85
|
+
if (event.type === 'devices' || event.type === 'screenshotShortcut' || event.type === 'request' || event.type === 'result') return;
|
|
80
86
|
if (event.sessionId && event.sessionId !== this.sessionId) return;
|
|
81
87
|
// Do not launch a native window for background device discovery messages.
|
|
82
88
|
if (!this.child) return;
|
|
83
|
-
this.send({ command: 'event', ...event });
|
|
89
|
+
this.send({ command: 'event', ...event, ...(event.message ? { message: safeMessage(event.message) } : {}) });
|
|
84
90
|
}
|
|
85
91
|
async complete(run, text) {
|
|
86
92
|
return this.request({ command: 'result', sessionId: run.id, text });
|
|
87
93
|
}
|
|
88
94
|
async close() {
|
|
89
95
|
this.closed = true;
|
|
90
|
-
for (const { reject, timer } of this.requests.values()) { clearTimeout(timer); reject(new Error('
|
|
96
|
+
for (const { reject, timer } of this.requests.values()) { clearTimeout(timer); reject(new Error(msg('error.closed'))); }
|
|
91
97
|
this.requests.clear();
|
|
92
98
|
const child = this.child; this.child = undefined;
|
|
93
99
|
if (child) await new Promise(resolve => {
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import koffi from 'koffi';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { normalizeShortcut } from '../shared/screenshot-shortcut.mjs';
|
|
5
|
+
import { message as msg } from '../shared/i18n.mjs';
|
|
6
|
+
|
|
7
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
8
|
+
const WIN_KEYS = { ArrowLeft: 0x25, ArrowUp: 0x26, ArrowRight: 0x27, ArrowDown: 0x28, Home: 0x24, End: 0x23,
|
|
9
|
+
PageUp: 0x21, PageDown: 0x22, Insert: 0x2d, Delete: 0x2e, Backspace: 8, Space: 0x20, Tab: 9, Enter: 13, Escape: 27 };
|
|
10
|
+
const WIN_SCAN_CODES = { KeyA: 0x1e, KeyB: 0x30, KeyC: 0x2e, KeyD: 0x20, KeyE: 0x12, KeyF: 0x21,
|
|
11
|
+
KeyG: 0x22, KeyH: 0x23, KeyI: 0x17, KeyJ: 0x24, KeyK: 0x25, KeyL: 0x26, KeyM: 0x32,
|
|
12
|
+
KeyN: 0x31, KeyO: 0x18, KeyP: 0x19, KeyQ: 0x10, KeyR: 0x13, KeyS: 0x1f, KeyT: 0x14,
|
|
13
|
+
KeyU: 0x16, KeyV: 0x2f, KeyW: 0x11, KeyX: 0x2d, KeyY: 0x15, KeyZ: 0x2c,
|
|
14
|
+
Digit1: 0x02, Digit2: 0x03, Digit3: 0x04, Digit4: 0x05, Digit5: 0x06, Digit6: 0x07,
|
|
15
|
+
Digit7: 0x08, Digit8: 0x09, Digit9: 0x0a, Digit0: 0x0b };
|
|
16
|
+
const MAC_KEYS = { KeyA: 0, KeyS: 1, KeyD: 2, KeyF: 3, KeyH: 4, KeyG: 5, KeyZ: 6, KeyX: 7, KeyC: 8,
|
|
17
|
+
KeyV: 9, KeyB: 11, KeyQ: 12, KeyW: 13, KeyE: 14, KeyR: 15, KeyY: 16, KeyT: 17, Digit1: 18, Digit2: 19,
|
|
18
|
+
Digit3: 20, Digit4: 21, Digit6: 22, Digit5: 23, Digit9: 25, Digit7: 26, Digit8: 28, Digit0: 29,
|
|
19
|
+
KeyO: 31, KeyU: 32, KeyI: 34, KeyP: 35, Enter: 36, KeyL: 37, KeyJ: 38, KeyK: 40, KeyN: 45,
|
|
20
|
+
KeyM: 46, Tab: 48, Space: 49, Backspace: 51, Escape: 53, F5: 96, F6: 97, F7: 98, F3: 99, F8: 100,
|
|
21
|
+
F9: 101, F11: 103, F10: 109, Insert: 114, Home: 115, PageUp: 116, Delete: 117, F4: 118, End: 119,
|
|
22
|
+
F2: 120, PageDown: 121, F1: 122, ArrowLeft: 123, ArrowRight: 124, ArrowDown: 125, ArrowUp: 126 };
|
|
23
|
+
|
|
24
|
+
function windowsApi() {
|
|
25
|
+
const user = koffi.load('user32.dll'), kernel = koffi.load('kernel32.dll');
|
|
26
|
+
const point = koffi.struct({ x: 'int32', y: 'int32' });
|
|
27
|
+
const message = koffi.struct({ hwnd: 'void *', message: 'uint32', wParam: 'uintptr_t', lParam: 'intptr_t',
|
|
28
|
+
time: 'uint32', pt: point, lPrivate: 'uint32' });
|
|
29
|
+
const foreground = user.func('void *__stdcall GetForegroundWindow()');
|
|
30
|
+
const thread = user.func('uint32 __stdcall GetWindowThreadProcessId(void *window, void *processId)');
|
|
31
|
+
const layout = user.func('void *__stdcall GetKeyboardLayout(uint32 threadId)');
|
|
32
|
+
const map = user.func('uint32 __stdcall MapVirtualKeyExW(uint32 code, uint32 mapType, void *layout)');
|
|
33
|
+
return {
|
|
34
|
+
register: user.func('int __stdcall RegisterHotKey(void *window, int id, uint32 modifiers, uint32 key)'),
|
|
35
|
+
unregister: user.func('int __stdcall UnregisterHotKey(void *window, int id)'),
|
|
36
|
+
peek: user.func('PeekMessageW', 'int', [koffi.out(koffi.pointer(message)), 'void *', 'uint32', 'uint32', 'uint32']),
|
|
37
|
+
lastError: kernel.func('uint32 __stdcall GetLastError()'),
|
|
38
|
+
physicalKey: scanCode => { const window = foreground(); return map(scanCode, 3, layout(window ? thread(window, null) : 0)); },
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function createWindowsHotkeyAdapter({ onTrigger = () => {}, api = windowsApi() } = {}) {
|
|
43
|
+
let current, nextId = 0x5300, closed = false;
|
|
44
|
+
const drain = deliver => {
|
|
45
|
+
for (let i = 0; i < 64; i++) {
|
|
46
|
+
const event = {};
|
|
47
|
+
if (!api.peek(event, null, 0x0312, 0x0312, 1)) break;
|
|
48
|
+
if (deliver && current && Number(event.wParam) === current.id) onTrigger(current.generation);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
return {
|
|
52
|
+
set(input, generation) {
|
|
53
|
+
if (closed) throw new Error(msg('shortcut.unavailable'));
|
|
54
|
+
const binding = normalizeShortcut(input, 'win32');
|
|
55
|
+
if (current && same(current.binding, binding)) { current.generation = generation; drain(false); return; }
|
|
56
|
+
let candidate;
|
|
57
|
+
if (binding) {
|
|
58
|
+
if (++nextId > 0xbfff) throw new Error(msg('shortcut.unavailable'));
|
|
59
|
+
const flags = binding.modifiers.reduce((value, key) => value | { Alt: 1, Control: 2, Shift: 4 }[key], 0) | 0x4000;
|
|
60
|
+
const key = WIN_SCAN_CODES[binding.code] && api.physicalKey ? api.physicalKey(WIN_SCAN_CODES[binding.code])
|
|
61
|
+
: binding.code.startsWith('Key') ? binding.code.charCodeAt(3)
|
|
62
|
+
: binding.code.startsWith('Digit') ? binding.code.charCodeAt(5)
|
|
63
|
+
: /^F\d+$/.test(binding.code) ? 0x6f + Number(binding.code.slice(1)) : WIN_KEYS[binding.code];
|
|
64
|
+
if (!key) throw new Error(msg('shortcut.invalid'));
|
|
65
|
+
if (!api.register(null, nextId, flags, key))
|
|
66
|
+
throw new Error(msg(api.lastError() === 1409 ? 'shortcut.conflict' : 'shortcut.unavailable'));
|
|
67
|
+
candidate = { binding, generation, id: nextId };
|
|
68
|
+
}
|
|
69
|
+
if (current && !api.unregister(null, current.id)) {
|
|
70
|
+
if (candidate) api.unregister(null, candidate.id);
|
|
71
|
+
throw new Error(msg('shortcut.unavailable'));
|
|
72
|
+
}
|
|
73
|
+
current = candidate; drain(false);
|
|
74
|
+
},
|
|
75
|
+
poll() { if (!closed) drain(true); },
|
|
76
|
+
close() { if (closed) return; closed = true; if (current) api.unregister(null, current.id); current = undefined; drain(false); },
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function suppressDockActivation() {
|
|
81
|
+
// [NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited](=2)。
|
|
82
|
+
// worker 与宿主是同一个 app bundle 二进制:Carbon 热键注册会让 LaunchServices
|
|
83
|
+
// 把本进程登记为第二个可激活应用(Dock 出现双图标,并干扰宿主的激活状态,
|
|
84
|
+
// 2026-11-30 实测宿主 renderer 被 kill)。本进程是纯后台热键监听者,注册前
|
|
85
|
+
// 显式禁止激活。仅真 macApi 路径调用(测试注入 mock,不加载 dylib)。
|
|
86
|
+
const objc = koffi.load('/usr/lib/libobjc.dylib');
|
|
87
|
+
const getClass = objc.func('void *objc_getClass(const char *name)');
|
|
88
|
+
const registerSel = objc.func('void *sel_registerName(const char *name)');
|
|
89
|
+
const send0 = objc.func('void *objc_msgSend(void *self, void *sel)');
|
|
90
|
+
const sendLong = objc.func('void *objc_msgSend(void *self, void *sel, long policy)');
|
|
91
|
+
const app = send0(getClass('NSApplication'), registerSel('sharedApplication'));
|
|
92
|
+
if (app) sendLong(app, registerSel('setActivationPolicy:'), 2);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function macApi() {
|
|
96
|
+
suppressDockActivation();
|
|
97
|
+
const carbon = koffi.load('/System/Library/Frameworks/Carbon.framework/Carbon');
|
|
98
|
+
const hotkeyId = koffi.struct({ signature: 'uint32', id: 'uint32' });
|
|
99
|
+
const eventType = koffi.struct({ eventClass: 'uint32', eventKind: 'uint32' });
|
|
100
|
+
return {
|
|
101
|
+
target: carbon.func('void *GetApplicationEventTarget()'),
|
|
102
|
+
register: carbon.func('RegisterEventHotKey', 'int32', ['uint32', 'uint32', hotkeyId, 'void *', 'uint32', koffi.out(koffi.pointer('void *'))]),
|
|
103
|
+
unregister: carbon.func('int32 UnregisterEventHotKey(void *hotkey)'),
|
|
104
|
+
receive: carbon.func('ReceiveNextEvent', 'int32', ['uint32', koffi.pointer(eventType), 'double', 'uint8', koffi.out(koffi.pointer('void *'))]),
|
|
105
|
+
kind: carbon.func('uint32 GetEventKind(void *event)'),
|
|
106
|
+
parameter: carbon.func('GetEventParameter', 'int32', ['void *', 'uint32', 'uint32', 'void *', 'uintptr_t', 'void *', koffi.out(koffi.pointer(hotkeyId))]),
|
|
107
|
+
release: carbon.func('void ReleaseEvent(void *event)'),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function createMacHotkeyAdapter({ onTrigger = () => {}, api = macApi() } = {}) {
|
|
112
|
+
const signature = 0x53434c44, target = api.target();
|
|
113
|
+
const types = [{ eventClass: 0x6b657962, eventKind: 5 }, { eventClass: 0x6b657962, eventKind: 6 }];
|
|
114
|
+
let current, nextId = 0, held = false, closed = false;
|
|
115
|
+
const drain = deliver => {
|
|
116
|
+
for (let i = 0; i < 64; i++) {
|
|
117
|
+
const output = [null];
|
|
118
|
+
const rc = api.receive(types.length, types, 0, 1, output);
|
|
119
|
+
if (rc === -9875) break;
|
|
120
|
+
if (rc !== 0 || !output[0]) throw new Error(msg('shortcut.unavailable'));
|
|
121
|
+
const event = output[0];
|
|
122
|
+
try {
|
|
123
|
+
const id = {}, kind = api.kind(event);
|
|
124
|
+
if (!deliver || !current || api.parameter(event, 0x2d2d2d2d, 0x686b6964, null, 8, null, id) !== 0
|
|
125
|
+
|| id.signature !== signature || id.id !== current.id) continue;
|
|
126
|
+
if (kind === 6) held = false;
|
|
127
|
+
else if (kind === 5 && !held) { held = true; onTrigger(current.generation); }
|
|
128
|
+
} finally { api.release(event); }
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
return {
|
|
132
|
+
set(input, generation) {
|
|
133
|
+
if (closed) throw new Error(msg('shortcut.unavailable'));
|
|
134
|
+
const binding = normalizeShortcut(input, 'darwin');
|
|
135
|
+
if (current && same(current.binding, binding)) { current.generation = generation; held = false; drain(false); return; }
|
|
136
|
+
let candidate;
|
|
137
|
+
if (binding) {
|
|
138
|
+
const id = ++nextId, ref = [null];
|
|
139
|
+
const modifiers = binding.modifiers.reduce((value, key) => value | { Meta: 256, Shift: 512, Alt: 2048, Control: 4096 }[key], 0);
|
|
140
|
+
// Carbon 默认允许共享热键;exclusive 才能在保存时发现其他进程占用。
|
|
141
|
+
const rc = api.register(MAC_KEYS[binding.code], modifiers, { signature, id }, target, 1, ref);
|
|
142
|
+
if (rc !== 0 || !ref[0]) throw new Error(msg(rc === -9878 ? 'shortcut.conflict' : 'shortcut.unavailable'));
|
|
143
|
+
candidate = { binding, generation, id, ref: ref[0] };
|
|
144
|
+
}
|
|
145
|
+
if (current && api.unregister(current.ref) !== 0) {
|
|
146
|
+
if (candidate) api.unregister(candidate.ref);
|
|
147
|
+
throw new Error(msg('shortcut.unavailable'));
|
|
148
|
+
}
|
|
149
|
+
current = candidate; held = false; drain(false);
|
|
150
|
+
},
|
|
151
|
+
poll() { if (!closed) drain(true); },
|
|
152
|
+
close() { if (closed) return; closed = true; if (current) api.unregister(current.ref); current = undefined; held = false; drain(false); },
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function createNativeShortcutAdapter({ platform = process.platform, ...options } = {}) {
|
|
157
|
+
if (platform === 'win32') return createWindowsHotkeyAdapter(options);
|
|
158
|
+
if (platform === 'darwin') return createMacHotkeyAdapter(options);
|
|
159
|
+
throw new Error(msg('shortcut.unavailable'));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function runWorker() {
|
|
163
|
+
let adapter, timer, closed = false;
|
|
164
|
+
const send = value => { if (process.connected) { try { process.send(value, () => {}); } catch {} } };
|
|
165
|
+
const close = (code = 0) => {
|
|
166
|
+
if (closed) return;
|
|
167
|
+
closed = true; clearInterval(timer);
|
|
168
|
+
try { adapter?.close(); } catch {}
|
|
169
|
+
if (process.connected) process.disconnect();
|
|
170
|
+
process.exitCode = code;
|
|
171
|
+
};
|
|
172
|
+
try {
|
|
173
|
+
adapter = createNativeShortcutAdapter({ onTrigger: generation => send({ type: 'trigger', generation }) });
|
|
174
|
+
timer = setInterval(() => { try { adapter.poll(); } catch { send({ type: 'fatal', message: msg('shortcut.unavailable') }); close(1); } }, 20);
|
|
175
|
+
process.on('message', message => {
|
|
176
|
+
if (closed || !message || typeof message !== 'object') return;
|
|
177
|
+
if (message.command === 'close') { close(); return; }
|
|
178
|
+
if (message.command !== 'set' || !Number.isSafeInteger(message.requestId) || !Number.isSafeInteger(message.generation)) return;
|
|
179
|
+
try {
|
|
180
|
+
adapter.set(message.binding, message.generation);
|
|
181
|
+
send({ type: 'reply', requestId: message.requestId, ok: true });
|
|
182
|
+
} catch (error) { send({ type: 'reply', requestId: message.requestId, ok: false, message: error.message }); }
|
|
183
|
+
});
|
|
184
|
+
process.once('disconnect', () => close());
|
|
185
|
+
send({ type: 'ready' });
|
|
186
|
+
} catch { send({ type: 'fatal', message: msg('shortcut.unavailable') }); close(1); }
|
|
187
|
+
}
|
|
188
|
+
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url) && process.send) runWorker();
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { fork } from 'node:child_process';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { normalizeShortcut, shortcutBindingSchema } from '../shared/screenshot-shortcut.mjs';
|
|
6
|
+
import { message as msg, safeMessage } from '../shared/i18n.mjs';
|
|
7
|
+
|
|
8
|
+
const KEY = 'dsh-asr/screenshot-shortcuts';
|
|
9
|
+
const storedSchema = z.object({ version: z.literal(1), platforms: z.object({
|
|
10
|
+
win32: shortcutBindingSchema.nullable().optional(), darwin: shortcutBindingSchema.nullable().optional(),
|
|
11
|
+
}).strict() }).strict();
|
|
12
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
13
|
+
const errorText = (error, fallback = 'shortcut.unavailable') => safeMessage(error?.message, fallback);
|
|
14
|
+
function payload(record) {
|
|
15
|
+
if (!record) return { version: 1, platforms: {} };
|
|
16
|
+
if (record.kind !== 'grant') throw new Error(msg('shortcut.saveFailed'));
|
|
17
|
+
const parsed = storedSchema.safeParse(record.payload);
|
|
18
|
+
if (!parsed.success) throw new Error(msg('shortcut.saveFailed'));
|
|
19
|
+
return parsed.data;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class ScreenshotShortcutService extends EventEmitter {
|
|
23
|
+
constructor({ credentials, platform = process.platform, arch = process.arch, launch = fork,
|
|
24
|
+
startTimeoutMs = 5000, timeoutMs = 3000, closeTimeoutMs = 750, retryDelayMs = 1000,
|
|
25
|
+
leaseMs = 30000, now = () => Date.now() } = {}) {
|
|
26
|
+
super();
|
|
27
|
+
Object.assign(this, { credentials, platform: ['win32', 'darwin'].includes(platform) ? platform : 'other',
|
|
28
|
+
arch, launch, startTimeoutMs, timeoutMs, closeTimeoutMs, retryDelayMs, leaseMs, now });
|
|
29
|
+
this.supported = platform === 'win32' && arch === 'x64' || platform === 'darwin' && arch === 'arm64';
|
|
30
|
+
this.binding = null; this.registered = false; this.error = ''; this.loaded = false;
|
|
31
|
+
this.pending = new Map(); this.leases = new Map(); this.sequence = 0; this.generation = 0;
|
|
32
|
+
this.activeGeneration = 0; this.operations = Promise.resolve(); this.closed = false; this.updating = false;
|
|
33
|
+
}
|
|
34
|
+
snapshot() {
|
|
35
|
+
return { supported: this.supported, platform: this.platform, binding: structuredClone(this.binding),
|
|
36
|
+
registered: this.registered, error: this.error };
|
|
37
|
+
}
|
|
38
|
+
changed() { if (!this.closed) this.emit('change', this.snapshot()); }
|
|
39
|
+
assertOpen() { if (this.closed) throw new Error(msg('error.closed')); }
|
|
40
|
+
enqueue(operation) {
|
|
41
|
+
if (this.closed) return Promise.reject(new Error(msg('error.closed')));
|
|
42
|
+
const pending = this.operations.then(() => { this.assertOpen(); return operation(); });
|
|
43
|
+
this.operations = pending.catch(() => {});
|
|
44
|
+
return pending;
|
|
45
|
+
}
|
|
46
|
+
async load() {
|
|
47
|
+
if (this.loaded || !this.supported) return;
|
|
48
|
+
let state;
|
|
49
|
+
try { state = payload(await this.credentials.readRecord(KEY)); }
|
|
50
|
+
catch { throw new Error(msg('shortcut.saveFailed')); }
|
|
51
|
+
this.assertOpen();
|
|
52
|
+
this.binding = normalizeShortcut(state.platforms[this.platform] ?? null, this.platform);
|
|
53
|
+
this.loaded = true;
|
|
54
|
+
if (!this.binding && this.error) { this.error = ''; this.changed(); }
|
|
55
|
+
}
|
|
56
|
+
async restore() {
|
|
57
|
+
if (!this.supported) return;
|
|
58
|
+
if (!this.binding) { this.registered = false; this.error = ''; return; }
|
|
59
|
+
if (this.leases.size || this.registered) return;
|
|
60
|
+
this.updating = true;
|
|
61
|
+
try {
|
|
62
|
+
this.activeGeneration = await this.applyNative(this.binding);
|
|
63
|
+
this.registered = true; this.error = ''; this.changed();
|
|
64
|
+
} finally { this.updating = false; }
|
|
65
|
+
}
|
|
66
|
+
start() {
|
|
67
|
+
return this.enqueue(async () => {
|
|
68
|
+
try { await this.load(); await this.restore(); }
|
|
69
|
+
catch (error) {
|
|
70
|
+
this.assertOpen(); this.error = errorText(error); this.registered = false; this.changed();
|
|
71
|
+
}
|
|
72
|
+
return this.snapshot();
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
state() { return this.start(); }
|
|
76
|
+
set(input) {
|
|
77
|
+
return this.enqueue(async () => {
|
|
78
|
+
if (!this.supported) throw new Error(msg('shortcut.unavailable'));
|
|
79
|
+
const candidate = normalizeShortcut(input, this.platform);
|
|
80
|
+
try { await this.load(); }
|
|
81
|
+
catch (error) { this.error = errorText(error, 'shortcut.saveFailed'); this.changed(); throw new Error(this.error); }
|
|
82
|
+
if (same(candidate, this.binding) && (candidate === null || this.registered)) {
|
|
83
|
+
this.error = ''; this.changed(); return this.snapshot();
|
|
84
|
+
}
|
|
85
|
+
const previous = this.binding;
|
|
86
|
+
let nativeChanged = false;
|
|
87
|
+
this.updating = true;
|
|
88
|
+
try {
|
|
89
|
+
let generation = await this.applyNative(candidate); nativeChanged = true;
|
|
90
|
+
if (this.leases.size && candidate) generation = await this.applyNative(null);
|
|
91
|
+
this.assertOpen();
|
|
92
|
+
try {
|
|
93
|
+
await this.credentials.modifyRecord(KEY, record => {
|
|
94
|
+
this.assertOpen();
|
|
95
|
+
const state = payload(record);
|
|
96
|
+
state.platforms[this.platform] = candidate;
|
|
97
|
+
return { kind: 'grant', payload: state };
|
|
98
|
+
});
|
|
99
|
+
} catch { throw new Error(msg('shortcut.saveFailed')); }
|
|
100
|
+
this.assertOpen();
|
|
101
|
+
this.binding = candidate; this.activeGeneration = generation;
|
|
102
|
+
this.registered = Boolean(candidate) && !this.leases.size;
|
|
103
|
+
this.error = ''; this.changed(); return this.snapshot();
|
|
104
|
+
} catch (error) {
|
|
105
|
+
this.assertOpen();
|
|
106
|
+
let rollbackFailed = false;
|
|
107
|
+
if (nativeChanged) {
|
|
108
|
+
try {
|
|
109
|
+
this.activeGeneration = await this.applyNative(this.leases.size ? null : previous);
|
|
110
|
+
this.registered = Boolean(previous) && !this.leases.size;
|
|
111
|
+
} catch {
|
|
112
|
+
rollbackFailed = true; this.registered = false;
|
|
113
|
+
this.stopCurrentWorker(); this.emit('notice', msg('shortcut.unavailable'));
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
this.error = rollbackFailed ? msg('shortcut.unavailable') : errorText(error);
|
|
117
|
+
this.changed(); throw new Error(this.error);
|
|
118
|
+
} finally { this.updating = false; }
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
suspend(clientId, paused) {
|
|
122
|
+
return this.enqueue(async () => {
|
|
123
|
+
if (typeof clientId !== 'string' || !clientId.trim() || clientId.length > 80 || typeof paused !== 'boolean')
|
|
124
|
+
throw new Error(msg('shortcut.invalid'));
|
|
125
|
+
await this.load();
|
|
126
|
+
if (!this.supported) return this.snapshot();
|
|
127
|
+
if (paused) {
|
|
128
|
+
this.leases.set(clientId, this.now() + this.leaseMs);
|
|
129
|
+
this.scheduleExpiry();
|
|
130
|
+
this.error = '';
|
|
131
|
+
if (this.registered) {
|
|
132
|
+
this.updating = true;
|
|
133
|
+
try { this.activeGeneration = await this.applyNative(null); this.registered = false; this.error = ''; }
|
|
134
|
+
catch (error) {
|
|
135
|
+
this.leases.delete(clientId); this.scheduleExpiry(); this.error = errorText(error); this.changed(); throw new Error(this.error);
|
|
136
|
+
} finally { this.updating = false; }
|
|
137
|
+
}
|
|
138
|
+
} else {
|
|
139
|
+
this.leases.delete(clientId); this.scheduleExpiry();
|
|
140
|
+
try { await this.restore(); }
|
|
141
|
+
catch (error) { this.error = errorText(error); this.registered = false; }
|
|
142
|
+
}
|
|
143
|
+
this.changed(); return this.snapshot();
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
scheduleExpiry() {
|
|
147
|
+
clearTimeout(this.leaseTimer);
|
|
148
|
+
if (this.closed || !this.leases.size) return;
|
|
149
|
+
const earliest = Math.min(...this.leases.values());
|
|
150
|
+
this.leaseTimer = setTimeout(() => {
|
|
151
|
+
this.enqueue(async () => {
|
|
152
|
+
for (const [client, deadline] of this.leases) if (deadline <= this.now()) this.leases.delete(client);
|
|
153
|
+
this.scheduleExpiry();
|
|
154
|
+
try { await this.restore(); }
|
|
155
|
+
catch (error) { this.error = errorText(error); this.registered = false; this.emit('notice', this.error); }
|
|
156
|
+
this.changed();
|
|
157
|
+
}).catch(() => {});
|
|
158
|
+
}, Math.max(1, earliest - this.now()));
|
|
159
|
+
this.leaseTimer.unref?.();
|
|
160
|
+
}
|
|
161
|
+
async applyNative(binding) {
|
|
162
|
+
this.assertOpen();
|
|
163
|
+
const generation = ++this.generation;
|
|
164
|
+
if (!binding && !this.child) return generation;
|
|
165
|
+
await this.startWorker(); this.assertOpen();
|
|
166
|
+
await this.command({ command: 'set', binding, generation });
|
|
167
|
+
return generation;
|
|
168
|
+
}
|
|
169
|
+
startWorker() {
|
|
170
|
+
this.assertOpen();
|
|
171
|
+
if (this.starting) return this.starting.promise;
|
|
172
|
+
if (this.child) return Promise.resolve();
|
|
173
|
+
let child;
|
|
174
|
+
try { child = this.launch(fileURLToPath(new URL('./screenshot-shortcut-worker.mjs', import.meta.url)), [],
|
|
175
|
+
{ stdio: ['ignore', 'ignore', 'ignore', 'ipc'], execArgv: [], windowsHide: true }); }
|
|
176
|
+
catch { return Promise.reject(new Error(msg('shortcut.unavailable'))); }
|
|
177
|
+
this.child = child;
|
|
178
|
+
const starting = { child };
|
|
179
|
+
starting.promise = new Promise((resolve, reject) => {
|
|
180
|
+
starting.reject = reject;
|
|
181
|
+
const timer = setTimeout(() => { this.workerFailed(child); child.kill(); }, this.startTimeoutMs);
|
|
182
|
+
starting.clear = () => clearTimeout(timer);
|
|
183
|
+
child.on('message', message => {
|
|
184
|
+
if (this.child !== child || this.closed || !message || typeof message !== 'object') return;
|
|
185
|
+
if (message.type === 'ready') {
|
|
186
|
+
clearTimeout(timer); if (this.starting === starting) this.starting = undefined; resolve();
|
|
187
|
+
} else if (message.type === 'trigger') {
|
|
188
|
+
if (!this.updating && this.registered && !this.leases.size && message.generation === this.activeGeneration) this.emit('trigger');
|
|
189
|
+
} else if (message.type === 'reply') {
|
|
190
|
+
const pending = this.pending.get(message.requestId);
|
|
191
|
+
if (!pending || pending.child !== child) return;
|
|
192
|
+
clearTimeout(pending.timer); this.pending.delete(message.requestId);
|
|
193
|
+
if (message.ok === true) pending.resolve(); else pending.reject(new Error(errorText({ message: message.message })));
|
|
194
|
+
} else if (message.type === 'fatal') { this.workerFailed(child); child.kill(); }
|
|
195
|
+
});
|
|
196
|
+
child.once('error', () => this.workerFailed(child));
|
|
197
|
+
child.once('exit', () => this.workerFailed(child));
|
|
198
|
+
child.once('disconnect', () => this.workerFailed(child));
|
|
199
|
+
});
|
|
200
|
+
this.starting = starting;
|
|
201
|
+
return starting.promise;
|
|
202
|
+
}
|
|
203
|
+
command(message) {
|
|
204
|
+
const child = this.child;
|
|
205
|
+
if (!child?.connected) return Promise.reject(new Error(msg('shortcut.unavailable')));
|
|
206
|
+
const requestId = ++this.sequence;
|
|
207
|
+
return new Promise((resolve, reject) => {
|
|
208
|
+
const timer = setTimeout(() => { this.workerFailed(child); child.kill(); }, this.timeoutMs);
|
|
209
|
+
this.pending.set(requestId, { child, timer, resolve, reject });
|
|
210
|
+
try {
|
|
211
|
+
child.send({ ...message, requestId }, error => { if (error) { this.workerFailed(child); child.kill(); } });
|
|
212
|
+
} catch { this.workerFailed(child); child.kill(); }
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
workerFailed(child) {
|
|
216
|
+
if (this.child !== child) return;
|
|
217
|
+
this.child = undefined; this.registered = false; this.activeGeneration = 0;
|
|
218
|
+
if (this.starting?.child === child) {
|
|
219
|
+
this.starting.clear(); this.starting.reject(new Error(msg('shortcut.unavailable'))); this.starting = undefined;
|
|
220
|
+
}
|
|
221
|
+
for (const [id, pending] of this.pending) {
|
|
222
|
+
if (pending.child !== child) continue;
|
|
223
|
+
clearTimeout(pending.timer); this.pending.delete(id); pending.reject(new Error(msg('shortcut.unavailable')));
|
|
224
|
+
}
|
|
225
|
+
if (this.closed) return;
|
|
226
|
+
this.error = msg('shortcut.unavailable'); this.changed();
|
|
227
|
+
if (this.binding) this.emit('notice', this.error);
|
|
228
|
+
if (this.binding && !this.retryTimer) {
|
|
229
|
+
this.retryTimer = setTimeout(() => {
|
|
230
|
+
this.retryTimer = undefined;
|
|
231
|
+
this.enqueue(async () => {
|
|
232
|
+
try { await this.restore(); }
|
|
233
|
+
catch (error) { this.error = errorText(error); this.changed(); }
|
|
234
|
+
}).catch(() => {});
|
|
235
|
+
}, this.retryDelayMs);
|
|
236
|
+
this.retryTimer.unref?.();
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
stopCurrentWorker() {
|
|
240
|
+
const child = this.child;
|
|
241
|
+
if (!child) return;
|
|
242
|
+
this.child = undefined; this.registered = false; this.activeGeneration = 0;
|
|
243
|
+
child.kill();
|
|
244
|
+
}
|
|
245
|
+
close() {
|
|
246
|
+
if (this.closing) return this.closing;
|
|
247
|
+
this.closed = true; this.registered = false; this.activeGeneration = 0;
|
|
248
|
+
clearTimeout(this.leaseTimer); clearTimeout(this.retryTimer); this.leases.clear();
|
|
249
|
+
const child = this.child; this.child = undefined;
|
|
250
|
+
if (this.starting) {
|
|
251
|
+
this.starting.clear(); this.starting.reject(new Error(msg('error.closed'))); this.starting = undefined;
|
|
252
|
+
}
|
|
253
|
+
for (const pending of this.pending.values()) { clearTimeout(pending.timer); pending.reject(new Error(msg('error.closed'))); }
|
|
254
|
+
this.pending.clear();
|
|
255
|
+
const stopped = !child ? Promise.resolve() : new Promise(resolve => {
|
|
256
|
+
let timer;
|
|
257
|
+
const done = () => { clearTimeout(timer); child.off('exit', done); resolve(); };
|
|
258
|
+
timer = setTimeout(() => { child.kill(); done(); }, this.closeTimeoutMs);
|
|
259
|
+
child.once('exit', done);
|
|
260
|
+
try { if (child.connected) child.send({ command: 'close' }, error => { if (error) { child.kill(); done(); } }); else { child.kill(); done(); } }
|
|
261
|
+
catch { child.kill(); done(); }
|
|
262
|
+
});
|
|
263
|
+
this.closing = Promise.allSettled([stopped, this.operations]).then(() => {});
|
|
264
|
+
return this.closing;
|
|
265
|
+
}
|
|
266
|
+
}
|