@sonicloud/dsh-sonicloud-device 0.1.4 → 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.
Files changed (46) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/CHANGELOG.zh.md +21 -0
  3. package/README.md +7 -5
  4. package/README.zh.md +7 -5
  5. package/dist/build.json +1 -1
  6. package/dist/client.js +647 -52
  7. package/docs/contributing/development.md +3 -3
  8. package/docs/specs/mouse-settings.md +1 -1
  9. package/docs/specs/multilingual.md +1 -1
  10. package/docs/specs/smart-mouse-plugin.md +6 -3
  11. package/native/screenshot/README.md +9 -4
  12. package/native/screenshot/SOURCE.json +48 -17
  13. package/native/screenshot/darwin-arm64/screentool-macos-1.2.2.zip +0 -0
  14. package/native/screenshot/helper-i18n/de.json +85 -0
  15. package/native/screenshot/helper-i18n/es.json +85 -0
  16. package/native/screenshot/helper-i18n/fr.json +85 -0
  17. package/native/screenshot/patches/{hide-cloud-actions.patch → macos/hide-cloud-actions.patch} +84 -76
  18. package/native/screenshot/patches/macos/mac-clang-compat.patch +14 -0
  19. package/native/screenshot/patches/macos/mac-color-panel.patch +40 -0
  20. package/native/screenshot/patches/macos/mac-permissions.patch +549 -0
  21. package/native/screenshot/patches/macos/mac-ui-focus.patch +658 -0
  22. package/native/screenshot/patches/macos/upstream-files.json +77 -0
  23. package/native/screenshot/patches/upstream-files.json +12 -8
  24. package/native/screenshot/win32-x64/i18n/de.json +85 -0
  25. package/native/screenshot/win32-x64/i18n/es.json +85 -0
  26. package/native/screenshot/win32-x64/i18n/fr.json +85 -0
  27. package/native/screenshot/win32-x64/screenhelper.exe +0 -0
  28. package/package.json +1 -1
  29. package/src/desktop/presentation.mjs +1 -1
  30. package/src/desktop/screenshot-shortcut-worker.mjs +188 -0
  31. package/src/desktop/screenshot-shortcut.mjs +266 -0
  32. package/src/desktop/screenshot-worker.mjs +16 -0
  33. package/src/desktop/screenshot.mjs +21 -2
  34. package/src/devices/manager.mjs +36 -3
  35. package/src/host/index.mjs +7 -2
  36. package/src/host/locale.mjs +5 -3
  37. package/src/shared/locales/de.json +28 -2
  38. package/src/shared/locales/en.json +28 -2
  39. package/src/shared/locales/es.json +28 -2
  40. package/src/shared/locales/fr.json +28 -2
  41. package/src/shared/locales/ja.json +28 -2
  42. package/src/shared/locales/pt.json +28 -2
  43. package/src/shared/locales/ru.json +28 -2
  44. package/src/shared/locales/zh.json +28 -2
  45. package/src/shared/remote.mjs +5 -0
  46. package/src/shared/screenshot-shortcut.mjs +50 -0
@@ -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
+ }
@@ -14,6 +14,7 @@ const call = (fn, ...args) => {
14
14
  const callbacks = [];
15
15
  let api, handle, closing = false, closePromise, connected = false, connection, disconnected, stateRequest;
16
16
  let capabilities = new Set();
17
+ let currentLanguage; // 宿主下发的 UI 语言;helper(重)连后应用,实际生效由 language_changed 事件回报
17
18
  let commands = Promise.resolve(), events = Promise.resolve();
18
19
  function send(message) {
19
20
  if (!process.connected) return;
@@ -55,6 +56,12 @@ function queueEvent(json) {
55
56
  const rc = await call(api.config, handle, JSON.stringify({ ocr_visible: false, trans_enabled: false }));
56
57
  if (rc !== 0) { connected = false; finishConnection(new Error(msg('error.screenshot'))); return; }
57
58
  connected = true; finishConnection();
59
+ // helper(含重连)每次就绪都重申当前语言:HelperConfig 不跨 helper 进程持久。
60
+ // 经 set_config 的 lang 键透传:随包 dylib 为原包 1.2.2(无 1.3.0 的
61
+ // sct_set_language 符号),厂商推荐 FFI 宿主走 set_config。宿主语言中
62
+ // helper 无内置 .qm 的语种(西/法/德)由交付包 helper 同目录 i18n/ 的
63
+ // screentool-i18n/1 JSON 补齐,helper 启动时自举装载,无需宿主下发目录。
64
+ if (currentLanguage) { try { await call(api.config, handle, JSON.stringify({ lang: currentLanguage })); } catch { /* 失败由 language_changed 事件如实回报 */ } }
58
65
  } else if (event.type === 'hello_ack') {
59
66
  capabilities = new Set(Array.isArray(event.capabilities) ? event.capabilities : []);
60
67
  } else if (event.type === 'state_report') {
@@ -138,6 +145,14 @@ function permissionView(state) {
138
145
  }
139
146
  const idle = state => state.capturing === false && state.pins_alive === 0 && state.pin_editing !== true;
140
147
 
148
+ async function applyLanguage(tag) {
149
+ // 尽力而为:语言标签限定字母与连字符,其余静默忽略;生效与否由 language_changed 事件回报。
150
+ if (typeof tag !== 'string' || !/^[a-zA-Z][a-zA-Z-]{1,15}$/.test(tag)) return;
151
+ currentLanguage = tag;
152
+ if (closing || !handle || !connected) return;
153
+ try { await call(api.config, handle, JSON.stringify({ lang: tag })); } catch { /* helper 解析折叠/回退自己回报 */ }
154
+ }
155
+
141
156
  async function stopHelper() {
142
157
  let timer;
143
158
  const stopped = new Promise(resolve => {
@@ -172,6 +187,7 @@ async function permissions(action) {
172
187
 
173
188
  process.on('message', message => {
174
189
  if (message?.command === 'close') { void close(); return; }
190
+ if (message?.command === 'locale') { void applyLanguage(message.language); return; }
175
191
  if (closing || !['capture', 'permissions'].includes(message?.command)) return;
176
192
  commands = commands.then(async () => {
177
193
  await initialized;
@@ -70,6 +70,17 @@ export class ScreenshotService extends EventEmitter {
70
70
  Object.assign(this, { platform, arch, launch, timeoutMs, startTimeoutMs, closeTimeoutMs,
71
71
  libraryPath, helperPath, prepareMac, exists });
72
72
  this.pending = new Map(); this.sequence = 0;
73
+ this.locale = undefined; // 宿主 UI 语言:worker(重)启动时下发,运行中热切换
74
+ }
75
+
76
+ // 语言为尽力而为:不拉起未运行的 worker;helper 生效结果经 language_changed 事件回报。
77
+ setLocale(locale) {
78
+ if (typeof locale !== 'string' || !/^[a-zA-Z][a-zA-Z-]{1,15}$/.test(locale)) return;
79
+ this.locale = locale;
80
+ const child = this.child;
81
+ if (!this.closed && child?.connected) {
82
+ try { child.send({ command: 'locale', language: locale }, () => {}); } catch { /* worker 故障走现有监管 */ }
83
+ }
73
84
  }
74
85
 
75
86
  start() {
@@ -97,8 +108,11 @@ export class ScreenshotService extends EventEmitter {
97
108
  if (!this.exists(paths.libraryPath) || !this.exists(paths.helperPath)) throw new Error(msg('error.screenshot'));
98
109
  let child;
99
110
  try {
111
+ const forkOptions = { stdio: ['ignore', 'ignore', 'ignore', 'ipc'], execArgv: [], windowsHide: true,
112
+ // helper 出生语言(1.3.0 HelperConfig 读 SCREENTOOL_LANG;1.2.2 忽略,跨平台无害)
113
+ env: { ...process.env, ...(this.locale ? { SCREENTOOL_LANG: this.locale } : {}) } };
100
114
  child = this.launch(fileURLToPath(new URL('./screenshot-worker.mjs', import.meta.url)),
101
- [paths.libraryPath, paths.helperPath], { stdio: ['ignore', 'ignore', 'ignore', 'ipc'], execArgv: [], windowsHide: true });
115
+ [paths.libraryPath, paths.helperPath], forkOptions);
102
116
  } catch { throw new Error(msg('error.screenshot')); }
103
117
  this.child = child;
104
118
  return new Promise((resolve, reject) => {
@@ -115,7 +129,12 @@ export class ScreenshotService extends EventEmitter {
115
129
  };
116
130
  child.on('message', message => {
117
131
  if (this.child !== child || !message || typeof message !== 'object') return;
118
- if (message.type === 'ready') { clearTimeout(timer); ready = true; resolve(); }
132
+ if (message.type === 'ready') {
133
+ clearTimeout(timer); ready = true; resolve();
134
+ if (this.locale && !this.closed) {
135
+ try { child.send({ command: 'locale', language: this.locale }, () => {}); } catch { /* worker 故障走现有监管 */ }
136
+ }
137
+ }
119
138
  else if (message.type === 'fatal') { fail(msg('error.screenshot')); child.kill(); }
120
139
  else if (message.type === 'notice') { if (!this.closed && typeof message.message === 'string') this.emit('notice', message.message); }
121
140
  else if (message.type === 'event') { if (!this.closed && message.event && typeof message.event.type === 'string') this.emit('event', message.event); }
@@ -11,8 +11,8 @@ import { translateText } from './translate.mjs';
11
11
 
12
12
  const VOICE = new Set(['voice_input', 'translate', 'speechSearch', 'ai_input']);
13
13
  export class DeviceManager {
14
- constructor({ credentials, recognize, prepare = async () => undefined, sdk = new MouseSdk(), action = systemAction, translate = translateText, desktop, screenshot, aiConversation, config = {} }) {
15
- Object.assign(this, { sdk, recognize, prepare, action, translate, desktop, screenshot, aiConversation, config });
14
+ constructor({ credentials, recognize, prepare = async () => undefined, sdk = new MouseSdk(), action = systemAction, translate = translateText, desktop, screenshot, shortcut, aiConversation, config = {} }) {
15
+ Object.assign(this, { sdk, recognize, prepare, action, translate, desktop, screenshot, shortcut, aiConversation, config });
16
16
  this.store = new DeviceStore(credentials);
17
17
  this.devices = new Map(); this.clients = new Set(); this.pressed = new Map(); this.pending = Promise.resolve();
18
18
  this.status = msg('status.connecting'); this.disposed = false;
@@ -34,12 +34,25 @@ export class DeviceManager {
34
34
  }
35
35
  this.onScreenshotNotice = message => { if (!this.disposed) this.publish({ type: 'notice', message }); };
36
36
  screenshot?.on('notice', this.onScreenshotNotice);
37
+ this.onShortcutTrigger = () => {
38
+ if (!this.disposed) void this.captureScreenshot('hotkey').catch(error => this.onScreenshotNotice(error.message));
39
+ };
40
+ this.onShortcutChange = value => { if (!this.disposed) this.publish({ type: 'screenshotShortcut', value }); };
41
+ shortcut?.on('trigger', this.onShortcutTrigger);
42
+ shortcut?.on('notice', this.onScreenshotNotice);
43
+ shortcut?.on('change', this.onShortcutChange);
37
44
  sdk.on('event', this.onEvent); sdk.on('fault', this.onFault);
38
45
  }
46
+ // 宿主 UI 语言变化:语音浮层与截图组件分别尽力跟随,互不阻断。
47
+ setLocale(locale) {
48
+ try { this.desktop?.setLocale?.(locale); } catch { /* 呈现层失败不影响其余跟随 */ }
49
+ try { this.screenshot?.setLocale?.(locale); } catch { /* 截图组件失败不影响其余跟随 */ }
50
+ }
39
51
  async start() {
40
52
  if (this.started) return this.started;
41
53
  this.started = (async () => {
42
54
  try { this.desktop?.start?.(); } catch { /* Key press reports unsupported native presentation. */ }
55
+ try { await this.shortcut?.start(); } catch { this.onScreenshotNotice(msg('shortcut.unavailable')); }
43
56
  try { await this.sdk.start(); this.status = this.devices.size ? msg('status.connected') : msg('status.searching'); }
44
57
  catch (error) { this.status = error.message; }
45
58
  this.snapshot();
@@ -48,7 +61,7 @@ export class DeviceManager {
48
61
  }
49
62
  publish(event) {
50
63
  this.desktop?.event(event);
51
- if (this.desktop && !['devices', 'notice'].includes(event.type)) return;
64
+ if (this.desktop && !['devices', 'notice', 'screenshotShortcut'].includes(event.type)) return;
52
65
  for (const queue of this.clients) {
53
66
  try { queue.push(event); } catch { queue.end(true); this.clients.delete(queue); if (!this.desktop) this.cancel(); }
54
67
  }
@@ -69,6 +82,7 @@ export class DeviceManager {
69
82
  try {
70
83
  signal.throwIfAborted(); await this.start();
71
84
  queue.push({ type: 'devices', ...this.view() });
85
+ if (this.shortcut) queue.push({ type: 'screenshotShortcut', value: await this.shortcut.state() });
72
86
  yield* queue;
73
87
  } finally {
74
88
  signal.removeEventListener('abort', abort); queue.end(true); this.clients.delete(queue);
@@ -237,6 +251,21 @@ export class DeviceManager {
237
251
  if (!this.screenshot?.permissions) throw new Error(msg('error.permission'));
238
252
  return this.screenshot.permissions(action);
239
253
  }
254
+ async screenshotShortcutState() {
255
+ if (this.disposed) throw new Error(msg('error.closed'));
256
+ if (!this.shortcut) return { supported: false, platform: 'other', binding: null, registered: false, error: '' };
257
+ return this.shortcut.state();
258
+ }
259
+ async setScreenshotShortcut(binding) {
260
+ if (this.disposed) throw new Error(msg('error.closed'));
261
+ if (!this.shortcut) throw new Error(msg('shortcut.unavailable'));
262
+ return this.shortcut.set(binding);
263
+ }
264
+ async pauseScreenshotShortcut(clientId, paused) {
265
+ if (this.disposed) throw new Error(msg('error.closed'));
266
+ if (!this.shortcut) throw new Error(msg('shortcut.unavailable'));
267
+ return this.shortcut.suspend(clientId, paused);
268
+ }
240
269
  async typingPermissions(action = 'check') {
241
270
  if (this.disposed) throw new Error(msg('error.closed'));
242
271
  if (!this.desktop?.permissions) throw new Error(msg('error.permission'));
@@ -392,6 +421,10 @@ export class DeviceManager {
392
421
  this.clients.clear(); this.owner = undefined;
393
422
  this.sdk.off('event', this.onEvent); this.sdk.off('fault', this.onFault);
394
423
  this.screenshot?.off('notice', this.onScreenshotNotice);
424
+ this.shortcut?.off('trigger', this.onShortcutTrigger);
425
+ this.shortcut?.off('notice', this.onScreenshotNotice);
426
+ this.shortcut?.off('change', this.onShortcutChange);
427
+ try { await this.shortcut?.close(); } catch { /* Release the native registration before the capture process. */ }
395
428
  this.aiConversation?.close();
396
429
  try { await this.screenshot?.close(); } catch { /* 截图进程退出失败不阻断设备和语音清理。 */ }
397
430
  await this.desktop?.close();
@@ -10,6 +10,7 @@ import { DeviceManager } from '../devices/manager.mjs';
10
10
  import { MouseSdk } from '../devices/native.mjs';
11
11
  import { DesktopPresentation } from '../desktop/presentation.mjs';
12
12
  import { ScreenshotService } from '../desktop/screenshot.mjs';
13
+ import { ScreenshotShortcutService } from '../desktop/screenshot-shortcut.mjs';
13
14
  import { pluginConfigSchema } from '../devices/config.mjs';
14
15
  import { AiConversationBridge } from './ai-conversation.mjs';
15
16
 
@@ -30,7 +31,7 @@ export class MouseController extends TypertRemoteService {
30
31
  sdk: dependencies.sdk ?? new MouseSdk(config.native), ...dependencies, aiConversation: this.aiConversation,
31
32
  prepare: () => this.service(), recognize: request => this.recognize(request),
32
33
  translate: request => this.translate(request) });
33
- this.locale = new HostLocale(locale => this.manager.desktop?.setLocale(locale));
34
+ this.locale = new HostLocale(locale => this.manager.setLocale(locale));
34
35
  ctx.effect(() => () => {
35
36
  this.lifetime.abort(); this.providers.clear(); return this.manager.close();
36
37
  });
@@ -40,6 +41,9 @@ export class MouseController extends TypertRemoteService {
40
41
  catalog() { return this.store.catalog(); }
41
42
  devices() { return this.manager.view(); }
42
43
  captureScreenshot() { return this.manager.captureScreenshot(); }
44
+ screenshotShortcut() { return this.manager.screenshotShortcutState(); }
45
+ setScreenshotShortcut(binding) { return this.manager.setScreenshotShortcut(binding); }
46
+ pauseScreenshotShortcut(clientId, paused) { return this.manager.pauseScreenshotShortcut(clientId, paused); }
43
47
  screenshotPermissions(action) { return this.manager.screenshotPermissions(action); }
44
48
  typingPermissions(action) { return this.manager.typingPermissions(action); }
45
49
  saveDevice(sn, revision, preferences) { return this.manager.save(sn, revision, preferences); }
@@ -98,7 +102,8 @@ export class MouseController extends TypertRemoteService {
98
102
  }
99
103
  export async function apply(ctx, config = {}) {
100
104
  ctx.effect(() => ctx.typert.register(TYPERT));
101
- const controller = new MouseController(ctx, config, { desktop: new DesktopPresentation(), screenshot: new ScreenshotService() });
105
+ const controller = new MouseController(ctx, config, { desktop: new DesktopPresentation(), screenshot: new ScreenshotService(),
106
+ shortcut: new ScreenshotShortcutService({ credentials: ctx.credentials }) });
102
107
  attachHostLocale(ctx, controller);
103
108
  await controller.initialized;
104
109
  void controller.manager.start();
@@ -2,7 +2,7 @@ import { LOCALES, resolveLocale } from '../shared/i18n.mjs';
2
2
 
3
3
  // Host 配置 revision 是跨窗口的权威顺序;客户端 locale revision 仅在单个窗口有效。
4
4
  export class HostLocale {
5
- constructor(apply) { this.apply = apply; this.locale = 'en'; this.revision = undefined; this.automatic = undefined; }
5
+ constructor(apply) { this.apply = apply; this.locale = 'en'; this.applied = false; this.revision = undefined; this.automatic = undefined; }
6
6
  attach(read) { this.read = read; this.refresh(); }
7
7
  refresh() {
8
8
  const state = this.read?.();
@@ -16,8 +16,10 @@ export class HostLocale {
16
16
  return state;
17
17
  }
18
18
  set(locale) {
19
- if (locale === this.locale) return;
20
- this.locale = locale; this.apply(locale);
19
+ // 初始 locale='en' 只是占位:宿主若本就是英文,首次 set 也必须下发,
20
+ // 否则截图组件等后加入的跟随方永远收不到语言(语音浮层靠默认英文巧合命中)。
21
+ if (locale === this.locale && this.applied) return;
22
+ this.applied = true; this.locale = locale; this.apply(locale);
21
23
  }
22
24
  accept({ active, resolved, revision }) {
23
25
  const state = this.refresh();
@@ -63,7 +63,7 @@
63
63
  "permission.checkTyping": "Eingabeberechtigungen erneut prüfen",
64
64
  "permission.checkScreenshot": "Screenshot-Berechtigungen erneut prüfen",
65
65
  "permission.checking": "Wird geprüft…",
66
- "permission.recheck": "Erteilt, erneut prüfen",
66
+ "permission.recheck": "Erneut prüfen",
67
67
  "permission.location": "Speicherort anzeigen, falls {helper} fehlt",
68
68
  "permission.pathHelp": "Diesen Pfad zum manuellen Hinzufügen in den Systemeinstellungen verwenden:",
69
69
  "permission.ready": "Screenshot-Berechtigungen für {helper} sind bereit.",
@@ -151,5 +151,31 @@
151
151
  "error.workspace": "Kein Arbeitsbereich verfügbar.",
152
152
  "error.cancelled": "Die Sprachsitzung wurde abgebrochen.",
153
153
  "error.deviceLimit": "Die maximale Gerätezahl der Lizenz ist erreicht.",
154
- "error.screenshotExport": "Texterkennung und Word-Export sind nicht verfügbar. Nutzen Sie Kopieren, Speichern oder Anheften."
154
+ "error.screenshotExport": "Texterkennung und Word-Export sind nicht verfügbar. Nutzen Sie Kopieren, Speichern oder Anheften.",
155
+ "shortcut.configure": "Tastenkürzel festlegen",
156
+ "shortcut.title": "Tastenkürzel für Bildschirmfotos festlegen",
157
+ "shortcut.help": "Drücke die Aufnahmetaste der Maus oder das Tastenkürzel und wähle einen Bereich zum Kommentieren, Kopieren, Speichern oder Anheften aus.",
158
+ "shortcut.unset": "Nicht festgelegt",
159
+ "shortcut.record": "Tastenkombination drücken",
160
+ "shortcut.recordHelp": "Verwende mindestens eine Zusatztaste wie Command, Strg oder Alt.",
161
+ "shortcut.suggested": "Vorgeschlagene Kombination {shortcut} verwenden",
162
+ "shortcut.clear": "Entfernen",
163
+ "shortcut.save": "Speichern",
164
+ "shortcut.saving": "Wird gespeichert…",
165
+ "shortcut.invalid": "Ungültiges oder vom System reserviertes Tastenkürzel",
166
+ "shortcut.unavailable": "In dieser Umgebung können keine globalen Tastenkürzel für Bildschirmfotos registriert werden.",
167
+ "shortcut.saveFailed": "Das Tastenkürzel konnte nicht gespeichert werden. Die bisherige Einstellung bleibt erhalten.",
168
+ "shortcut.conflict": "Dieses Tastenkürzel wird bereits verwendet. Wähle eine andere Kombination.",
169
+ "permission.system": "Systemberechtigungen",
170
+ "permission.intro": "Erteile vor der ersten Verwendung die folgenden Systemberechtigungen.",
171
+ "permission.allGranted": "Die Berechtigungen für Bildschirmfotos und Texteingabe sind bereit.",
172
+ "permission.grant": "Berechtigung erteilen",
173
+ "permission.typingTitle": "Texteingabe",
174
+ "permission.screenTitle": "Bildschirmfotos",
175
+ "permission.scrollTitle": "Automatische Scroll-Aufnahme",
176
+ "permission.optional": "Optional",
177
+ "permission.screenHelp": "Für Bildschirmfotos erforderlich. Die Aufnahmeansicht wird erst nach Erteilung der Berechtigung geöffnet.",
178
+ "permission.scrollHelp": "Normale Bildschirmfotos und manuelles Scrollen bleiben ohne diese Berechtigung verfügbar.",
179
+ "permission.locations": "Komponente in den Berechtigungen nicht gefunden? Speicherort anzeigen",
180
+ "shortcut.autoSave": "Einstellungen werden automatisch gespeichert"
155
181
  }
@@ -63,7 +63,7 @@
63
63
  "permission.checkTyping": "Recheck typing permissions",
64
64
  "permission.checkScreenshot": "Recheck screenshot permissions",
65
65
  "permission.checking": "Checking…",
66
- "permission.recheck": "Granted, check again",
66
+ "permission.recheck": "Check again",
67
67
  "permission.location": "View component location if {helper} is missing",
68
68
  "permission.pathHelp": "Use this location to add the component to the system permission list:",
69
69
  "permission.ready": "Screenshot permissions for {helper} are ready.",
@@ -151,5 +151,31 @@
151
151
  "error.workspace": "No workspace is available.",
152
152
  "error.cancelled": "The voice session was cancelled.",
153
153
  "error.deviceLimit": "The license device limit has been reached.",
154
- "error.screenshotExport": "Screenshot OCR and Word export are not supported. Use copy, save or pin instead."
154
+ "error.screenshotExport": "Screenshot OCR and Word export are not supported. Use copy, save or pin instead.",
155
+ "shortcut.configure": "Set shortcut",
156
+ "shortcut.title": "Set screenshot shortcut",
157
+ "shortcut.help": "Press the mouse capture button or shortcut, then select a region to annotate, copy, save or pin.",
158
+ "shortcut.unset": "Not set",
159
+ "shortcut.record": "Press a key combination",
160
+ "shortcut.recordHelp": "Include at least one modifier such as Command, Ctrl or Alt.",
161
+ "shortcut.suggested": "Use suggested shortcut {shortcut}",
162
+ "shortcut.clear": "Clear",
163
+ "shortcut.save": "Save",
164
+ "shortcut.saving": "Saving…",
165
+ "shortcut.invalid": "Invalid or system-reserved shortcut",
166
+ "shortcut.unavailable": "Screenshot shortcuts cannot be registered in this environment.",
167
+ "shortcut.saveFailed": "Could not save the shortcut. The previous setting is preserved.",
168
+ "shortcut.conflict": "This shortcut is already in use. Choose another combination.",
169
+ "permission.system": "System permissions",
170
+ "permission.intro": "Complete the following system permissions before first use.",
171
+ "permission.allGranted": "Permissions are ready for screenshots and text insertion.",
172
+ "permission.grant": "Grant access",
173
+ "permission.typingTitle": "Text insertion",
174
+ "permission.screenTitle": "Screenshots",
175
+ "permission.scrollTitle": "Automatic scrolling capture",
176
+ "permission.optional": "Optional",
177
+ "permission.screenHelp": "Required for screenshots. The capture overlay stays closed until permission is granted.",
178
+ "permission.scrollHelp": "Regular screenshots and manual scrolling remain available without this permission.",
179
+ "permission.locations": "Cannot find a permission component? View its location",
180
+ "shortcut.autoSave": "Settings save automatically"
155
181
  }
@@ -63,7 +63,7 @@
63
63
  "permission.checkTyping": "Revisar permisos de escritura",
64
64
  "permission.checkScreenshot": "Revisar permisos de captura",
65
65
  "permission.checking": "Comprobando…",
66
- "permission.recheck": "Permiso concedido, comprobar",
66
+ "permission.recheck": "Volver a comprobar",
67
67
  "permission.location": "Ver ubicación si no encuentras {helper}",
68
68
  "permission.pathHelp": "Usa esta ubicación para añadir el componente a los permisos del sistema:",
69
69
  "permission.ready": "Los permisos de captura de {helper} están listos.",
@@ -151,5 +151,31 @@
151
151
  "error.workspace": "No hay ningún espacio de trabajo disponible.",
152
152
  "error.cancelled": "Se canceló la sesión de voz.",
153
153
  "error.deviceLimit": "Se alcanzó el límite de dispositivos de la licencia.",
154
- "error.screenshotExport": "El OCR de capturas y la exportación a Word no están disponibles. Usa copiar, guardar o fijar."
154
+ "error.screenshotExport": "El OCR de capturas y la exportación a Word no están disponibles. Usa copiar, guardar o fijar.",
155
+ "shortcut.configure": "Configurar atajo",
156
+ "shortcut.title": "Configurar atajo de captura",
157
+ "shortcut.help": "Pulsa el botón de captura del ratón o el atajo y selecciona una región para anotar, copiar, guardar o fijar.",
158
+ "shortcut.unset": "Sin configurar",
159
+ "shortcut.record": "Pulsa una combinación de teclas",
160
+ "shortcut.recordHelp": "Incluye al menos un modificador, como Command, Ctrl o Alt.",
161
+ "shortcut.suggested": "Usar combinación sugerida {shortcut}",
162
+ "shortcut.clear": "Borrar",
163
+ "shortcut.save": "Guardar",
164
+ "shortcut.saving": "Guardando…",
165
+ "shortcut.invalid": "Atajo no válido o reservado por el sistema",
166
+ "shortcut.unavailable": "No se pueden registrar atajos de captura en este entorno.",
167
+ "shortcut.saveFailed": "No se pudo guardar el atajo. Se conserva la configuración anterior.",
168
+ "shortcut.conflict": "Este atajo ya está en uso. Elige otra combinación.",
169
+ "permission.system": "Permisos del sistema",
170
+ "permission.intro": "Completa los siguientes permisos del sistema antes del primer uso.",
171
+ "permission.allGranted": "Los permisos para capturas e inserción de texto están listos.",
172
+ "permission.grant": "Conceder acceso",
173
+ "permission.typingTitle": "Inserción de texto",
174
+ "permission.screenTitle": "Capturas de pantalla",
175
+ "permission.scrollTitle": "Captura con desplazamiento automático",
176
+ "permission.optional": "Opcional",
177
+ "permission.screenHelp": "Necesario para las capturas. La superposición de captura no aparece hasta que se conceda el permiso.",
178
+ "permission.scrollHelp": "Las capturas normales y el desplazamiento manual siguen disponibles sin este permiso.",
179
+ "permission.locations": "¿No encuentras un componente en los permisos? Ver ubicación",
180
+ "shortcut.autoSave": "La configuración se guarda automáticamente"
155
181
  }