@sonicloud/dsh-sonicloud-device 0.1.2 → 0.1.4
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 +44 -1
- package/CHANGELOG.zh.md +44 -1
- package/README.md +36 -11
- package/README.zh.md +26 -1
- package/dist/build.json +1 -1
- package/dist/client.js +1594 -98
- package/docs/contributing/development.md +35 -5
- package/docs/specs/ci-cd.md +5 -4
- package/docs/specs/multilingual.md +98 -0
- package/docs/specs/smart-mouse-plugin.md +31 -1
- 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/README.md +4 -0
- package/native/desktop/VOICE_SOURCE.json +16 -0
- package/native/desktop/VoicePanel.cs +70 -33
- package/native/desktop/VoicePanel.swift +83 -19
- package/native/desktop/darwin-arm64/Sonicloud Voice.app/Contents/MacOS/sonicloud-voice +0 -0
- package/native/desktop/darwin-arm64/Sonicloud Voice.app/Contents/_CodeSignature/CodeResources +115 -0
- package/native/screenshot/README.md +34 -0
- package/native/screenshot/SOURCE.json +218 -0
- package/native/screenshot/darwin-arm64/screentool-macos-1.2.2.zip +0 -0
- package/native/screenshot/patches/hide-cloud-actions.patch +202 -0
- package/native/screenshot/patches/mac-permissions.patch +545 -0
- package/native/screenshot/patches/upstream-files.json +22 -0
- package/native/screenshot/win32-x64/PixPinScrollCapture.dll +0 -0
- package/native/screenshot/win32-x64/Qt5Core.dll +0 -0
- package/native/screenshot/win32-x64/Qt5Gui.dll +0 -0
- package/native/screenshot/win32-x64/Qt5Network.dll +0 -0
- package/native/screenshot/win32-x64/Qt5Svg.dll +0 -0
- package/native/screenshot/win32-x64/Qt5Widgets.dll +0 -0
- package/native/screenshot/win32-x64/iconengines/qsvgicon.dll +0 -0
- package/native/screenshot/win32-x64/imageformats/qjpeg.dll +0 -0
- package/native/screenshot/win32-x64/imageformats/qsvg.dll +0 -0
- package/native/screenshot/win32-x64/libcrypto-1_1-x64.dll +0 -0
- package/native/screenshot/win32-x64/libssl-1_1-x64.dll +0 -0
- package/native/screenshot/win32-x64/msvcp140.dll +0 -0
- package/native/screenshot/win32-x64/platforms/qwindows.dll +0 -0
- package/native/screenshot/win32-x64/qwindowsvistastyle.dll +0 -0
- package/native/screenshot/win32-x64/screenhelper.exe +0 -0
- package/native/screenshot/win32-x64/screentool.dll +0 -0
- package/native/screenshot/win32-x64/vcruntime140.dll +0 -0
- package/native/screenshot/win32-x64/vcruntime140_1.dll +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 +31 -11
- package/src/desktop/screenshot-worker.mjs +226 -0
- package/src/desktop/screenshot.mjs +186 -0
- 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 +72 -37
- 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 +12 -3
- package/src/host/locale.mjs +42 -0
- package/src/shared/devices.mjs +13 -12
- package/src/shared/i18n.mjs +47 -0
- package/src/shared/locales/de.json +155 -0
- package/src/shared/locales/en.json +155 -0
- package/src/shared/locales/es.json +155 -0
- package/src/shared/locales/fr.json +155 -0
- package/src/shared/locales/ja.json +155 -0
- package/src/shared/locales/pt.json +155 -0
- package/src/shared/locales/ru.json +155 -0
- package/src/shared/locales/zh.json +155 -0
- package/src/shared/remote.mjs +7 -1
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { message as msg } from '../shared/i18n.mjs';
|
|
2
|
+
import { EventEmitter } from 'node:events';
|
|
3
|
+
import { fork, execFile } from 'node:child_process';
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
import { mkdir, mkdtemp, readFile, rename, rm, stat } from 'node:fs/promises';
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { homedir } from 'node:os';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { promisify } from 'node:util';
|
|
11
|
+
|
|
12
|
+
const execute = promisify(execFile);
|
|
13
|
+
const nativeRoot = fileURLToPath(new URL('../../native/screenshot/', import.meta.url));
|
|
14
|
+
const macPaths = directory => ({
|
|
15
|
+
libraryPath: join(directory, 'screentool', 'libscreentool.dylib'),
|
|
16
|
+
helperPath: join(directory, 'screentool', 'helper', 'screenhelper.app', 'Contents', 'MacOS', 'screenhelper'),
|
|
17
|
+
});
|
|
18
|
+
const complete = paths => existsSync(paths.libraryPath) && existsSync(paths.helperPath);
|
|
19
|
+
|
|
20
|
+
// ditto 在 macOS 上还原软链接、执行权限及原始签名;缓存不修改随包 app。
|
|
21
|
+
export async function prepareMacScreenshot({
|
|
22
|
+
archivePath = join(nativeRoot, 'darwin-arm64', 'screentool-macos-1.2.2.zip'),
|
|
23
|
+
cacheRoot = join(homedir(), 'Library', 'Caches', 'sonicloud-device'),
|
|
24
|
+
extract = execute,
|
|
25
|
+
} = {}) {
|
|
26
|
+
const digest = createHash('sha256').update(await readFile(archivePath)).digest('hex');
|
|
27
|
+
const directory = join(cacheRoot, `screentool-${digest}`);
|
|
28
|
+
const paths = macPaths(directory);
|
|
29
|
+
if (complete(paths)) return paths;
|
|
30
|
+
await mkdir(cacheRoot, { recursive: true });
|
|
31
|
+
const lock = `${directory}.lock`;
|
|
32
|
+
const deadline = Date.now() + 35000;
|
|
33
|
+
for (;;) {
|
|
34
|
+
try { await mkdir(lock); break; }
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (error.code !== 'EEXIST') throw error;
|
|
37
|
+
if (complete(paths)) return paths;
|
|
38
|
+
// ditto 最多运行 30 秒;清理崩溃后留下的过期准备锁。
|
|
39
|
+
try { if (Date.now() - (await stat(lock)).mtimeMs > 60000) { await rm(lock, { recursive: true, force: true }); continue; } }
|
|
40
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
41
|
+
if (Date.now() > deadline) throw new Error(msg('error.screenshot'));
|
|
42
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
let temporary;
|
|
46
|
+
try {
|
|
47
|
+
if (complete(paths)) return paths;
|
|
48
|
+
// 仅清理当前压缩包哈希对应的受控缓存目录,不触碰其他版本或原始 app。
|
|
49
|
+
await rm(directory, { recursive: true, force: true });
|
|
50
|
+
temporary = await mkdtemp(join(cacheRoot, '.screentool-'));
|
|
51
|
+
await extract('/usr/bin/ditto', ['-x', '-k', archivePath, temporary], { timeout: 30000, maxBuffer: 8192 });
|
|
52
|
+
if (!complete(macPaths(temporary))) throw new Error(msg('error.screenshot'));
|
|
53
|
+
// 另一进程可能已完成相同版本;只清理本次创建的临时目录。
|
|
54
|
+
if (!complete(paths)) {
|
|
55
|
+
try { await rename(temporary, directory); }
|
|
56
|
+
catch (error) { if (!complete(paths)) throw error; }
|
|
57
|
+
}
|
|
58
|
+
return paths;
|
|
59
|
+
} finally {
|
|
60
|
+
if (temporary) await rm(temporary, { recursive: true, force: true });
|
|
61
|
+
await rm(lock, { recursive: true, force: true });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export class ScreenshotService extends EventEmitter {
|
|
66
|
+
constructor({ platform = process.platform, arch = process.arch, launch = fork,
|
|
67
|
+
timeoutMs = 9000, startTimeoutMs = 10000, closeTimeoutMs = 5000,
|
|
68
|
+
libraryPath, helperPath, prepareMac = prepareMacScreenshot, exists = existsSync } = {}) {
|
|
69
|
+
super();
|
|
70
|
+
Object.assign(this, { platform, arch, launch, timeoutMs, startTimeoutMs, closeTimeoutMs,
|
|
71
|
+
libraryPath, helperPath, prepareMac, exists });
|
|
72
|
+
this.pending = new Map(); this.sequence = 0;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
start() {
|
|
76
|
+
if (this.closed) return Promise.reject(new Error(msg('error.closed')));
|
|
77
|
+
if (this.starting) return this.starting;
|
|
78
|
+
const attempt = this.startWorker().catch(error => { if (this.starting === attempt) this.starting = undefined; throw error; });
|
|
79
|
+
this.starting = attempt;
|
|
80
|
+
return this.starting;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async startWorker() {
|
|
84
|
+
const target = `${this.platform}-${this.arch}`;
|
|
85
|
+
if (!['win32-x64', 'darwin-arm64'].includes(target)) throw new Error(msg('error.screenshot'));
|
|
86
|
+
let paths = { libraryPath: this.libraryPath, helperPath: this.helperPath };
|
|
87
|
+
if (!paths.libraryPath || !paths.helperPath) {
|
|
88
|
+
try {
|
|
89
|
+
const defaults = this.platform === 'darwin' ? await this.prepareMac() : {
|
|
90
|
+
libraryPath: join(nativeRoot, target, 'screentool.dll'),
|
|
91
|
+
helperPath: join(nativeRoot, target, 'screenhelper.exe'),
|
|
92
|
+
};
|
|
93
|
+
paths = { libraryPath: paths.libraryPath ?? defaults.libraryPath, helperPath: paths.helperPath ?? defaults.helperPath };
|
|
94
|
+
} catch { throw new Error(msg('error.permission')); }
|
|
95
|
+
}
|
|
96
|
+
if (this.closed) throw new Error(msg('error.closed'));
|
|
97
|
+
if (!this.exists(paths.libraryPath) || !this.exists(paths.helperPath)) throw new Error(msg('error.screenshot'));
|
|
98
|
+
let child;
|
|
99
|
+
try {
|
|
100
|
+
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 });
|
|
102
|
+
} catch { throw new Error(msg('error.screenshot')); }
|
|
103
|
+
this.child = child;
|
|
104
|
+
return new Promise((resolve, reject) => {
|
|
105
|
+
let ready = false, failed = false;
|
|
106
|
+
const timer = setTimeout(() => { fail(msg('error.timeout')); child.kill(); }, this.startTimeoutMs);
|
|
107
|
+
const fail = message => {
|
|
108
|
+
if (failed) return;
|
|
109
|
+
failed = true; clearTimeout(timer);
|
|
110
|
+
if (this.child !== child) return;
|
|
111
|
+
this.child = undefined; this.starting = undefined;
|
|
112
|
+
for (const pending of this.pending.values()) { clearTimeout(pending.timer); pending.reject(new Error(message)); }
|
|
113
|
+
this.pending.clear(); reject(new Error(message));
|
|
114
|
+
if (ready && !this.closed) this.emit('notice', message);
|
|
115
|
+
};
|
|
116
|
+
child.on('message', message => {
|
|
117
|
+
if (this.child !== child || !message || typeof message !== 'object') return;
|
|
118
|
+
if (message.type === 'ready') { clearTimeout(timer); ready = true; resolve(); }
|
|
119
|
+
else if (message.type === 'fatal') { fail(msg('error.screenshot')); child.kill(); }
|
|
120
|
+
else if (message.type === 'notice') { if (!this.closed && typeof message.message === 'string') this.emit('notice', message.message); }
|
|
121
|
+
else if (message.type === 'event') { if (!this.closed && message.event && typeof message.event.type === 'string') this.emit('event', message.event); }
|
|
122
|
+
else if (message.type === 'reply') {
|
|
123
|
+
const pending = this.pending.get(message.requestId);
|
|
124
|
+
if (!pending) return;
|
|
125
|
+
clearTimeout(pending.timer); this.pending.delete(message.requestId);
|
|
126
|
+
if (message.ok) pending.resolve(message.value ?? true);
|
|
127
|
+
else pending.reject(new Error(message.message || msg('error.screenshot')));
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
child.once('exit', () => fail(this.closed ? msg('error.closed') : msg('error.screenshot')));
|
|
131
|
+
child.once('error', () => { fail(msg('error.screenshot')); child.kill(); });
|
|
132
|
+
child.once('disconnect', () => { fail(this.closed ? msg('error.closed') : msg('error.screenshot')); if (!this.closed) child.kill(); });
|
|
133
|
+
this.rejectStarting = () => { clearTimeout(timer); reject(new Error(msg('error.closed'))); };
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
capture(trigger = 'ui') { return this.command('capture', { trigger }); }
|
|
138
|
+
|
|
139
|
+
async permissions(action = 'check') {
|
|
140
|
+
if (!['check', 'screen', 'accessibility', 'refresh'].includes(action)) throw new Error(msg('error.permission'));
|
|
141
|
+
if (this.closed) throw new Error(msg('error.closed'));
|
|
142
|
+
if (this.platform !== 'darwin') return { supported: false, screenRecording: true, accessibility: true, helperApp: '' };
|
|
143
|
+
const state = await this.command('permissions', { action }, Math.max(this.timeoutMs, 20000));
|
|
144
|
+
if (!state || typeof state !== 'object' || state.supported !== true || typeof state.screenRecording !== 'boolean'
|
|
145
|
+
|| typeof state.accessibility !== 'boolean' || typeof state.helperApp !== 'string') throw new Error(msg('error.permission'));
|
|
146
|
+
return state;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async command(command, fields = {}, timeoutMs = this.timeoutMs) {
|
|
150
|
+
await this.start();
|
|
151
|
+
if (this.closed) throw new Error(msg('error.closed'));
|
|
152
|
+
const child = this.child;
|
|
153
|
+
if (!child?.connected) throw new Error(msg('error.screenshot'));
|
|
154
|
+
const requestId = ++this.sequence;
|
|
155
|
+
return new Promise((resolve, reject) => {
|
|
156
|
+
const timer = setTimeout(() => {
|
|
157
|
+
this.pending.delete(requestId); reject(new Error(msg('error.timeout'))); child.kill();
|
|
158
|
+
}, timeoutMs);
|
|
159
|
+
this.pending.set(requestId, { resolve, reject, timer });
|
|
160
|
+
try {
|
|
161
|
+
child.send({ command, ...fields, requestId }, error => {
|
|
162
|
+
if (!error) return;
|
|
163
|
+
const pending = this.pending.get(requestId);
|
|
164
|
+
if (pending) { clearTimeout(timer); this.pending.delete(requestId); reject(new Error(msg('error.screenshot'))); child.kill(); }
|
|
165
|
+
});
|
|
166
|
+
} catch { clearTimeout(timer); this.pending.delete(requestId); reject(new Error(msg('error.screenshot'))); child.kill(); }
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
close() {
|
|
171
|
+
if (this.closing) return this.closing;
|
|
172
|
+
this.closed = true; this.rejectStarting?.();
|
|
173
|
+
for (const pending of this.pending.values()) { clearTimeout(pending.timer); pending.reject(new Error(msg('error.closed'))); }
|
|
174
|
+
this.pending.clear();
|
|
175
|
+
const child = this.child;
|
|
176
|
+
this.closing = child ? new Promise(resolve => {
|
|
177
|
+
let timer;
|
|
178
|
+
const done = () => { clearTimeout(timer); child.off('exit', done); resolve(); };
|
|
179
|
+
timer = setTimeout(() => { child.kill(); done(); }, this.closeTimeoutMs);
|
|
180
|
+
child.once('exit', done);
|
|
181
|
+
try { if (child.connected) child.send({ command: 'close' }, error => { if (error) { child.kill(); done(); } }); else { child.kill(); done(); } }
|
|
182
|
+
catch { child.kill(); done(); }
|
|
183
|
+
}) : Promise.resolve();
|
|
184
|
+
return this.closing;
|
|
185
|
+
}
|
|
186
|
+
}
|
package/src/devices/actions.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { message as msg } from '../shared/i18n.mjs';
|
|
1
2
|
import { execFile } from 'node:child_process';
|
|
2
3
|
import { promisify } from 'node:util';
|
|
3
4
|
import { webUrl } from '../shared/devices.mjs';
|
|
@@ -15,9 +16,9 @@ export async function systemAction(action, value, { platform = process.platform,
|
|
|
15
16
|
const result = await execute('/usr/bin/osascript', ['-l', 'JavaScript', '-e',
|
|
16
17
|
"ObjC.import('CoreServices'); ObjC.unwrap(ObjC.castRefToObject($.LSCopyDefaultHandlerForURLScheme($('http'))));"], commandOptions);
|
|
17
18
|
const browser = result.stdout.trim();
|
|
18
|
-
if (!/^[a-z\d][a-z\d.-]+$/i.test(browser)) throw new Error('
|
|
19
|
+
if (!/^[a-z\d][a-z\d.-]+$/i.test(browser)) throw new Error(msg('error.browser'));
|
|
19
20
|
args = ['-n', '-b', browser, '--args', url];
|
|
20
|
-
} catch { throw new Error('
|
|
21
|
+
} catch { throw new Error(msg('error.browser')); }
|
|
21
22
|
}
|
|
22
23
|
}
|
|
23
24
|
else if (platform === 'win32') { file = 'rundll32.exe'; args = ['url.dll,FileProtocolHandler', url]; }
|
|
@@ -29,7 +30,7 @@ export async function systemAction(action, value, { platform = process.platform,
|
|
|
29
30
|
backspace: 'tell application "System Events" to key code 51',
|
|
30
31
|
openAi: 'tell application "DeepSeek Harness" to activate',
|
|
31
32
|
};
|
|
32
|
-
if (!scripts[action]) throw new Error('
|
|
33
|
+
if (!scripts[action]) throw new Error(msg('error.action'));
|
|
33
34
|
args = ['-e', scripts[action]];
|
|
34
35
|
} else if (platform === 'win32') {
|
|
35
36
|
file = 'powershell.exe';
|
|
@@ -44,9 +45,9 @@ export async function systemAction(action, value, { platform = process.platform,
|
|
|
44
45
|
// without any window, so the Electron overrides must be stripped before handing off.
|
|
45
46
|
openAi: "$p=Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 } | Select-Object -First 1; if($p){ Add-Type -Namespace Win -Name Native -MemberDefinition '[DllImport(\"user32.dll\")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);[DllImport(\"user32.dll\")] public static extern bool SetForegroundWindow(IntPtr hWnd);'; [Win.Native]::ShowWindow($p.MainWindowHandle, 9) | Out-Null; if([Win.Native]::SetForegroundWindow($p.MainWindowHandle)){ exit 0 } }; Remove-Item Env:\\ELECTRON_RUN_AS_NODE, Env:\\ELECTRON_NO_ATTACH_CONSOLE, Env:\\ELECTRON_NO_ASAR -ErrorAction SilentlyContinue; $exe=(Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue | Select-Object -First 1).Path; if($exe){ Start-Process -FilePath $exe -ArgumentList 'dsh://open'; exit 0 }; Start-Process -FilePath rundll32.exe -ArgumentList 'url.dll,FileProtocolHandler','dsh://open' -WindowStyle Hidden; exit 0",
|
|
46
47
|
};
|
|
47
|
-
if (!scripts[action]) throw new Error('
|
|
48
|
+
if (!scripts[action]) throw new Error(msg('error.action'));
|
|
48
49
|
args = ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(scripts[action], 'utf16le').toString('base64')];
|
|
49
|
-
} else throw new Error('
|
|
50
|
+
} else throw new Error(msg('error.action'));
|
|
50
51
|
try { await execute(file, args, commandOptions); }
|
|
51
|
-
catch { throw new Error(action === 'openUrl' ? '
|
|
52
|
+
catch { throw new Error(action === 'openUrl' ? msg('error.browser') : msg('error.action')); }
|
|
52
53
|
}
|
package/src/devices/config.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { message as msg } from '../shared/i18n.mjs';
|
|
1
2
|
import { z } from 'zod';
|
|
2
|
-
const query = z.partialRecord(z.enum(['lid', 'lanid', 'role', 'language', 'accent', 'rlang']), z.union([z.string().max(128), z.number()])).refine(value => Object.keys(value).length > 0, '
|
|
3
|
+
const query = z.partialRecord(z.enum(['lid', 'lanid', 'role', 'language', 'accent', 'rlang']), z.union([z.string().max(128), z.number()])).refine(value => Object.keys(value).length > 0, msg('error.language'));
|
|
3
4
|
export const pluginConfigSchema = z.object({
|
|
4
5
|
native: z.object({ libraryPath: z.string().min(1).max(4096).optional() }).strict().optional(),
|
|
5
6
|
dpiLevels: z.partialRecord(z.enum(['800', '1200', '1600', '2400']), z.number().int().min(0).max(255)).optional(),
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { message as msg } from '../shared/i18n.mjs';
|
|
1
2
|
import { execFile } from 'node:child_process';
|
|
2
3
|
import { promisify } from 'node:util';
|
|
3
4
|
|
|
@@ -44,9 +45,9 @@ export async function diagnoseUsb(workerPid, { platform = process.platform, exec
|
|
|
44
45
|
const result = parseUsbOwners(stdout, workerPid);
|
|
45
46
|
if (result.owners.length) {
|
|
46
47
|
const names = [...new Set(result.owners.map(item => item.name))].join('、');
|
|
47
|
-
return
|
|
48
|
+
return msg('status.occupied', { names });
|
|
48
49
|
}
|
|
49
50
|
return result.receiverPresent
|
|
50
|
-
? '
|
|
51
|
-
: '
|
|
51
|
+
? msg('status.receiver')
|
|
52
|
+
: msg('status.searching');
|
|
52
53
|
}
|
package/src/devices/manager.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { message as msg } from '../shared/i18n.mjs';
|
|
1
2
|
import { randomUUID } from 'node:crypto';
|
|
2
3
|
import { AsyncQueue, PcmPackets } from './queue.mjs';
|
|
3
4
|
import { DeviceStore } from './store.mjs';
|
|
@@ -10,18 +11,18 @@ import { translateText } from './translate.mjs';
|
|
|
10
11
|
|
|
11
12
|
const VOICE = new Set(['voice_input', 'translate', 'speechSearch', 'ai_input']);
|
|
12
13
|
export class DeviceManager {
|
|
13
|
-
constructor({ credentials, recognize, prepare = async () => undefined, sdk = new MouseSdk(), action = systemAction, translate = translateText, desktop, aiConversation, config = {} }) {
|
|
14
|
-
Object.assign(this, { sdk, recognize, prepare, action, translate, desktop, aiConversation, config });
|
|
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 });
|
|
15
16
|
this.store = new DeviceStore(credentials);
|
|
16
17
|
this.devices = new Map(); this.clients = new Set(); this.pressed = new Map(); this.pending = Promise.resolve();
|
|
17
|
-
this.status = '
|
|
18
|
+
this.status = msg('status.connecting'); this.disposed = false;
|
|
18
19
|
this.languages = config.recognitionLanguages ?? DEFAULT_LANGUAGES;
|
|
19
20
|
this.dpiLevels = config.dpiLevels ?? { '800': 21, '1200': 32, '1600': 42, '2400': 63 };
|
|
20
21
|
this.dpiReportLevels = config.dpiReportLevels ?? { '800': 0, '1200': 1, '1600': 2, '2400': 3 };
|
|
21
22
|
this.onEvent = event => {
|
|
22
23
|
// Audio is copied in the worker. Process it synchronously in IPC order; commands are serialized separately.
|
|
23
24
|
if (event.type === 'audio') { this.audio(event); return; }
|
|
24
|
-
this.pending = this.pending.then(() => this.event(event)).catch(() => this.publish({ type: 'notice', message: '
|
|
25
|
+
this.pending = this.pending.then(() => this.event(event)).catch(() => this.publish({ type: 'notice', message: msg('error.device') }));
|
|
25
26
|
};
|
|
26
27
|
this.onFault = message => {
|
|
27
28
|
this.status = message; this.cancel();
|
|
@@ -29,15 +30,17 @@ export class DeviceManager {
|
|
|
29
30
|
};
|
|
30
31
|
if (desktop) {
|
|
31
32
|
desktop.onCancel = id => this.cancel(id);
|
|
32
|
-
desktop.onFault = () => this.cancel(undefined, '
|
|
33
|
+
desktop.onFault = () => this.cancel(undefined, msg('error.panel'));
|
|
33
34
|
}
|
|
35
|
+
this.onScreenshotNotice = message => { if (!this.disposed) this.publish({ type: 'notice', message }); };
|
|
36
|
+
screenshot?.on('notice', this.onScreenshotNotice);
|
|
34
37
|
sdk.on('event', this.onEvent); sdk.on('fault', this.onFault);
|
|
35
38
|
}
|
|
36
39
|
async start() {
|
|
37
40
|
if (this.started) return this.started;
|
|
38
41
|
this.started = (async () => {
|
|
39
42
|
try { this.desktop?.start?.(); } catch { /* Key press reports unsupported native presentation. */ }
|
|
40
|
-
try { await this.sdk.start(); this.status = this.devices.size ? '
|
|
43
|
+
try { await this.sdk.start(); this.status = this.devices.size ? msg('status.connected') : msg('status.searching'); }
|
|
41
44
|
catch (error) { this.status = error.message; }
|
|
42
45
|
this.snapshot();
|
|
43
46
|
})();
|
|
@@ -59,7 +62,7 @@ export class DeviceManager {
|
|
|
59
62
|
}
|
|
60
63
|
snapshot() { this.publish({ type: 'devices', ...this.view() }); }
|
|
61
64
|
async *watch(clientId, signal) {
|
|
62
|
-
if (!this.desktop && this.owner) { yield { type: 'notice', message: '
|
|
65
|
+
if (!this.desktop && this.owner) { yield { type: 'notice', message: msg('error.busy') }; return; }
|
|
63
66
|
const queue = new AsyncQueue(256); if (!this.desktop) this.owner = clientId; this.clients.add(queue);
|
|
64
67
|
const abort = () => queue.end(true);
|
|
65
68
|
signal.addEventListener('abort', abort, { once: true });
|
|
@@ -78,7 +81,7 @@ export class DeviceManager {
|
|
|
78
81
|
case 'connected': return this.connectDevice(event);
|
|
79
82
|
case 'disconnected': return this.disconnectDevice(event);
|
|
80
83
|
case 'message': return this.deviceMessage(event);
|
|
81
|
-
case 'overflow': return this.cancelFor(event.id, '
|
|
84
|
+
case 'overflow': return this.cancelFor(event.id, msg('error.audio'));
|
|
82
85
|
case 'warning': return this.publish({ type: 'notice', message: event.message });
|
|
83
86
|
case 'diagnostic':
|
|
84
87
|
if (!this.devices.size) { this.status = event.message; this.snapshot(); }
|
|
@@ -90,26 +93,26 @@ export class DeviceManager {
|
|
|
90
93
|
const stable = isStableSn(id);
|
|
91
94
|
const category = event.deviceType ?? 'smart-mouse';
|
|
92
95
|
const saved = stable && category === 'smart-mouse' ? await this.store.get(id) : null;
|
|
93
|
-
const device = { id, sn: stable ? id : '', type: category, name: event.name ||
|
|
96
|
+
const device = { id, sn: stable ? id : '', type: category, name: event.name || '', defaultName: !event.name,
|
|
94
97
|
connection: event.mode === 1 ? 'ble' : 'usb', connectionId: randomUUID(), battery: null,
|
|
95
98
|
identityConfirmed: stable, dpiState: 'unknown', ...saved };
|
|
96
99
|
this.devices.set(id, device);
|
|
97
100
|
this.clearPressed(id);
|
|
98
|
-
this.status = '
|
|
101
|
+
this.status = msg('status.connected');
|
|
99
102
|
if (saved?.revision > 0) await this.applyDpi(device);
|
|
100
103
|
this.snapshot();
|
|
101
104
|
}
|
|
102
105
|
disconnectDevice({ id, mode }) {
|
|
103
106
|
const device = this.devices.get(id);
|
|
104
107
|
if (!device || device.connection !== (mode === 1 ? 'ble' : 'usb')) return;
|
|
105
|
-
this.cancelFor(id, '
|
|
106
|
-
if (!this.devices.size) this.status = '
|
|
108
|
+
this.cancelFor(id, msg('error.device')); this.devices.delete(id); this.clearPressed(id);
|
|
109
|
+
if (!this.devices.size) this.status = msg('status.searching');
|
|
107
110
|
this.snapshot();
|
|
108
111
|
}
|
|
109
112
|
async deviceMessage({ id, message }) {
|
|
110
113
|
const device = this.devices.get(id);
|
|
111
|
-
if (message.type === 'warning') { this.publish({ type: 'notice', message: message.text || '
|
|
112
|
-
if (message.type === 'queueOverflow') { this.cancel(undefined, '
|
|
114
|
+
if (message.type === 'warning') { this.publish({ type: 'notice', message: message.text || msg('error.device') }); return; }
|
|
115
|
+
if (message.type === 'queueOverflow') { this.cancel(undefined, msg('error.audio')); return; }
|
|
113
116
|
if (!device) return;
|
|
114
117
|
switch (message.type) {
|
|
115
118
|
case 'deviceInfo': return this.updateDeviceInfo(device, message);
|
|
@@ -121,7 +124,7 @@ export class DeviceManager {
|
|
|
121
124
|
if (isStableSn(message.sn) && message.sn !== device.sn) {
|
|
122
125
|
// 只补全临时身份,不合并已确认的设备。
|
|
123
126
|
if (device.identityConfirmed || this.devices.has(message.sn)) {
|
|
124
|
-
device.identityConfirmed = false; this.cancelFor(device.id, '
|
|
127
|
+
device.identityConfirmed = false; this.cancelFor(device.id, msg('error.device'));
|
|
125
128
|
} else {
|
|
126
129
|
this.devices.delete(device.id); device.sn = message.sn; device.identityConfirmed = true;
|
|
127
130
|
if (device.type === 'smart-mouse') Object.assign(device, await this.store.get(message.sn));
|
|
@@ -151,33 +154,48 @@ export class DeviceManager {
|
|
|
151
154
|
}
|
|
152
155
|
async savePreferences(sn, revision, preferences) {
|
|
153
156
|
const device = [...this.devices.values()].find(item => item.sn === sn && item.identityConfirmed);
|
|
154
|
-
if (!device || device.type !== 'smart-mouse') throw new Error('
|
|
157
|
+
if (!device || device.type !== 'smart-mouse') throw new Error(msg('error.settings'));
|
|
155
158
|
const connectionId = device.connectionId;
|
|
156
159
|
const dpiChanged = preferences.dpi !== device.preferences.dpi || device.dpiState === 'failed';
|
|
157
160
|
const saved = await this.store.save(sn, revision, preferences);
|
|
158
|
-
if (this.devices.get(device.id)?.connectionId !== connectionId) { this.snapshot(); return { ...saved, message: '
|
|
161
|
+
if (this.devices.get(device.id)?.connectionId !== connectionId) { this.snapshot(); return { ...saved, message: msg('settings.savedOffline') }; }
|
|
159
162
|
Object.assign(device, saved);
|
|
160
|
-
let message = '
|
|
163
|
+
let message = msg('settings.saved');
|
|
161
164
|
if (dpiChanged) {
|
|
162
|
-
message = '
|
|
165
|
+
message = msg('settings.savedDpi', { reason: await this.applyDpi(device) });
|
|
163
166
|
}
|
|
164
167
|
this.snapshot(); return { ...saved, message };
|
|
165
168
|
}
|
|
166
169
|
async applyDpi(device) {
|
|
167
170
|
const level = this.dpiLevels[device.preferences.dpi];
|
|
168
171
|
try {
|
|
169
|
-
if (!Number.isInteger(level) || level < 0 || level > 255) throw new Error('
|
|
170
|
-
if (await this.sdk.dpi(device.id, level) !== 1) throw new Error('
|
|
171
|
-
device.dpiState = 'sent'; return '
|
|
172
|
+
if (!Number.isInteger(level) || level < 0 || level > 255) throw new Error(msg('keys.dpiFailed'));
|
|
173
|
+
if (await this.sdk.dpi(device.id, level) !== 1) throw new Error(msg('keys.dpiFailed'));
|
|
174
|
+
device.dpiState = 'sent'; return msg('settings.dpiSent');
|
|
172
175
|
} catch (error) { device.dpiState = 'failed'; return error.message; }
|
|
173
176
|
}
|
|
174
177
|
async key(device, event) {
|
|
175
|
-
if (device.type !== 'smart-mouse'
|
|
178
|
+
if (this.disposed || device.type !== 'smart-mouse') return;
|
|
179
|
+
if (event.key !== 'capture' && !this.owner && !this.desktop) return;
|
|
176
180
|
if (!device.identityConfirmed) {
|
|
177
|
-
if (event.action === 'down' || event.action === 'click') this.publish({ type: 'notice', message: '
|
|
181
|
+
if (event.action === 'down' || event.action === 'click') this.publish({ type: 'notice', message: msg('error.device') });
|
|
178
182
|
return;
|
|
179
183
|
}
|
|
180
184
|
const key = `${device.id}:${event.key}:${event.index ?? 0}`;
|
|
185
|
+
if (event.key === 'capture') {
|
|
186
|
+
const pressed = this.pressed.get(key);
|
|
187
|
+
if (event.action === 'up') {
|
|
188
|
+
if (pressed) pressed.releasedAt = Date.now();
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (event.action !== 'click' && event.action !== 'down') return;
|
|
192
|
+
// SDK 固件可能同时上报 down 与 click;松键后短暂保留标记以吸收尾随 click。
|
|
193
|
+
if (pressed && (!pressed.releasedAt || (event.action === 'click' && Date.now() - pressed.releasedAt < 300))) return;
|
|
194
|
+
if (event.action === 'down') this.pressed.set(key, { capture: true });
|
|
195
|
+
else this.pressed.delete(key);
|
|
196
|
+
void this.captureScreenshot('mouse').catch(error => this.onScreenshotNotice(error.message));
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
181
199
|
if (event.action === 'up') {
|
|
182
200
|
const pressed = this.pressed.get(key); this.pressed.delete(key);
|
|
183
201
|
if (this.run?.key === key) this.release(this.run);
|
|
@@ -191,7 +209,7 @@ export class DeviceManager {
|
|
|
191
209
|
this.pressed.set(key, structuredClone(device.preferences));
|
|
192
210
|
const action = event.key === 'ai' ? 'ai_input' : event.key === 'm' ? device.preferences.mAction : event.key === 'translation' ? 'translate' : device.preferences.speechAction;
|
|
193
211
|
if (!VOICE.has(action)) return;
|
|
194
|
-
if (this.run) { this.publish({ type: 'notice', message: '
|
|
212
|
+
if (this.run) { this.publish({ type: 'notice', message: msg('error.busy') }); return; }
|
|
195
213
|
let query;
|
|
196
214
|
try {
|
|
197
215
|
query = recognitionQuery(device.preferences, action, this.languages);
|
|
@@ -203,15 +221,30 @@ export class DeviceManager {
|
|
|
203
221
|
};
|
|
204
222
|
run.packets = new PcmPackets(chunk => run.queue.push(chunk));
|
|
205
223
|
this.run = run;
|
|
206
|
-
if (!this.desktop) run.captureTimer = setTimeout(() => this.fail(run, '
|
|
224
|
+
if (!this.desktop) run.captureTimer = setTimeout(() => this.fail(run, msg('error.connection')), 5000);
|
|
207
225
|
run.durationTimer = setTimeout(() => this.release(run), 600000);
|
|
208
226
|
// Opening the app/client must not block key-up or device-disconnect events.
|
|
209
227
|
if (action === 'ai_input') void this.begin(run, device);
|
|
210
228
|
else await this.begin(run, device);
|
|
211
229
|
}
|
|
230
|
+
async captureScreenshot(trigger = 'ui') {
|
|
231
|
+
if (this.disposed) throw new Error(msg('error.closed'));
|
|
232
|
+
if (!this.screenshot) throw new Error(msg('error.screenshot'));
|
|
233
|
+
return this.screenshot.capture(trigger);
|
|
234
|
+
}
|
|
235
|
+
async screenshotPermissions(action = 'check') {
|
|
236
|
+
if (this.disposed) throw new Error(msg('error.closed'));
|
|
237
|
+
if (!this.screenshot?.permissions) throw new Error(msg('error.permission'));
|
|
238
|
+
return this.screenshot.permissions(action);
|
|
239
|
+
}
|
|
240
|
+
async typingPermissions(action = 'check') {
|
|
241
|
+
if (this.disposed) throw new Error(msg('error.closed'));
|
|
242
|
+
if (!this.desktop?.permissions) throw new Error(msg('error.permission'));
|
|
243
|
+
return this.desktop.permissions(action);
|
|
244
|
+
}
|
|
212
245
|
async prepareAi(run) {
|
|
213
246
|
try {
|
|
214
|
-
if (!this.aiConversation || !this.desktop) throw new Error('
|
|
247
|
+
if (!this.aiConversation || !this.desktop) throw new Error(msg('error.ai'));
|
|
215
248
|
// Activation failure alone must not abort: with the window tray-hidden the renderer lives on and insertion still works.
|
|
216
249
|
try { await this.action('openAi'); } catch { run.aiActivateFailed = true; }
|
|
217
250
|
run.lifetime.signal.throwIfAborted();
|
|
@@ -222,12 +255,12 @@ export class DeviceManager {
|
|
|
222
255
|
async begin(run, device) {
|
|
223
256
|
try {
|
|
224
257
|
if (run.action === 'ai_input') run.aiReady = this.prepareAi(run);
|
|
225
|
-
if (run.action === 'ai_input' && !this.desktop) throw new Error('
|
|
258
|
+
if (run.action === 'ai_input' && !this.desktop) throw new Error(msg('error.ai'));
|
|
226
259
|
if (this.desktop) await this.desktop.begin(run);
|
|
227
260
|
if (this.run !== run || run.closing) return;
|
|
228
261
|
run.service = await this.prepare();
|
|
229
262
|
if (this.run !== run || run.closing) return;
|
|
230
|
-
if (await this.sdk.source(device.id) !== 1) throw new Error('
|
|
263
|
+
if (await this.sdk.source(device.id) !== 1) throw new Error(msg('error.audio'));
|
|
231
264
|
if (this.run !== run || run.closing) return;
|
|
232
265
|
if (this.desktop) { run.started = true; void this.process(run); }
|
|
233
266
|
else this.publish({ type: 'request', sessionId: run.id, sn: run.sn, action: run.action });
|
|
@@ -242,9 +275,9 @@ export class DeviceManager {
|
|
|
242
275
|
if (!run || run.deviceId !== event.id || run.audioEnded || this.devices.get(event.id)?.connectionId !== run.connectionId) return;
|
|
243
276
|
try {
|
|
244
277
|
const buffer = Buffer.from(event.data, 'base64');
|
|
245
|
-
if (buffer.toString('base64') !== event.data || buffer.length > 320000) throw new Error('
|
|
278
|
+
if (buffer.toString('base64') !== event.data || buffer.length > 320000) throw new Error(msg('error.audio'));
|
|
246
279
|
run.bytes += buffer.length;
|
|
247
|
-
if (!run.ready && run.bytes > 320000) throw new Error('
|
|
280
|
+
if (!run.ready && run.bytes > 320000) throw new Error(msg('error.audio'));
|
|
248
281
|
run.packets.write(buffer);
|
|
249
282
|
} catch (error) { this.fail(run, error.message); }
|
|
250
283
|
}
|
|
@@ -255,7 +288,7 @@ export class DeviceManager {
|
|
|
255
288
|
run.started = true; clearTimeout(run.captureTimer);
|
|
256
289
|
void this.process(run); return true;
|
|
257
290
|
}
|
|
258
|
-
assertOwner(clientId) { if (!this.owner || this.owner !== clientId) throw new Error('
|
|
291
|
+
assertOwner(clientId) { if (!this.owner || this.owner !== clientId) throw new Error(msg('error.busy')); }
|
|
259
292
|
release(run) {
|
|
260
293
|
if (this.run !== run || run.released) return;
|
|
261
294
|
run.released = true;
|
|
@@ -266,7 +299,7 @@ export class DeviceManager {
|
|
|
266
299
|
try { run.audioEnded = true; run.packets.flush(); run.queue.end(); }
|
|
267
300
|
catch (error) { this.fail(run, error.message); }
|
|
268
301
|
}, this.config.tailMs ?? 150);
|
|
269
|
-
run.uploadTimer = setTimeout(() => this.fail(run, '
|
|
302
|
+
run.uploadTimer = setTimeout(() => this.fail(run, msg('error.timeout')), 15000);
|
|
270
303
|
}
|
|
271
304
|
async process(run) {
|
|
272
305
|
try {
|
|
@@ -285,9 +318,9 @@ export class DeviceManager {
|
|
|
285
318
|
if (event.type === 'complete') { complete = true; break; }
|
|
286
319
|
}
|
|
287
320
|
if (this.run !== run || run.closing) return;
|
|
288
|
-
if (!complete || !run.released) throw new Error('
|
|
321
|
+
if (!complete || !run.released) throw new Error(msg('error.connection'));
|
|
289
322
|
await this.complete(run);
|
|
290
|
-
} catch (error) { this.fail(run, error.message || '
|
|
323
|
+
} catch (error) { this.fail(run, error.message || msg('error.generic')); }
|
|
291
324
|
}
|
|
292
325
|
async complete(run) {
|
|
293
326
|
let text = formatTranscript(run.transcript.finalText(), run.preferences, run.action);
|
|
@@ -311,12 +344,12 @@ export class DeviceManager {
|
|
|
311
344
|
await this.aiConversation.insert(run, text);
|
|
312
345
|
if (this.run !== run || run.closing) return;
|
|
313
346
|
this.publish(run.aiActivateFailed
|
|
314
|
-
? { type: 'failed', sessionId: run.id, message: '
|
|
347
|
+
? { type: 'failed', sessionId: run.id, message: msg('error.aiWindow') }
|
|
315
348
|
: { type: 'finished', sessionId: run.id });
|
|
316
349
|
} catch (error) {
|
|
317
350
|
// On Windows the panel keeps the text so the user can focus any input and submit it there.
|
|
318
351
|
if (this.desktop?.platform === 'win32') {
|
|
319
|
-
this.publish({ type: 'submitOffer', sessionId: run.id, text, message: '
|
|
352
|
+
this.publish({ type: 'submitOffer', sessionId: run.id, text, message: msg('panel.openInput') });
|
|
320
353
|
await this.finish(run);
|
|
321
354
|
return;
|
|
322
355
|
}
|
|
@@ -358,7 +391,9 @@ export class DeviceManager {
|
|
|
358
391
|
for (const queue of this.clients) queue.end(true);
|
|
359
392
|
this.clients.clear(); this.owner = undefined;
|
|
360
393
|
this.sdk.off('event', this.onEvent); this.sdk.off('fault', this.onFault);
|
|
394
|
+
this.screenshot?.off('notice', this.onScreenshotNotice);
|
|
361
395
|
this.aiConversation?.close();
|
|
396
|
+
try { await this.screenshot?.close(); } catch { /* 截图进程退出失败不阻断设备和语音清理。 */ }
|
|
362
397
|
await this.desktop?.close();
|
|
363
398
|
await this.sdk.close();
|
|
364
399
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { message as msg } from '../shared/i18n.mjs';
|
|
1
2
|
import koffi from 'koffi';
|
|
2
3
|
import { dirname } from 'node:path';
|
|
3
4
|
const path = process.argv[2];
|
|
@@ -29,10 +30,10 @@ try {
|
|
|
29
30
|
bind('um_register_connected', 'void MouseConnected(const char *id, int mode)', (id, mode) => notify({ type: 'connected', id, mode }));
|
|
30
31
|
bind('um_register_disconnected', 'void MouseDisconnected(const char *id, int mode)', (id, mode) => notify({ type: 'disconnected', id, mode }));
|
|
31
32
|
bind('um_register_message', 'void MouseMessage(const char *id, const char *json)', (id, json) => {
|
|
32
|
-
try { notify({ type: 'message', id, message: JSON.parse(json) }); } catch { notify({ type: 'warning', message: '
|
|
33
|
+
try { notify({ type: 'message', id, message: JSON.parse(json) }); } catch { notify({ type: 'warning', message: msg('error.device') }); }
|
|
33
34
|
});
|
|
34
35
|
bind('um_register_audio', 'void MouseAudio(const char *id, const void *pcm, int len)', (id, pcm, len) => {
|
|
35
|
-
if (len <= 0 || len > 320000 || len % 2) { notify({ type: 'warning', message: '
|
|
36
|
+
if (len <= 0 || len > 320000 || len % 2) { notify({ type: 'warning', message: msg('error.audio') }); return; }
|
|
36
37
|
// The SDK buffer expires as soon as this callback returns.
|
|
37
38
|
const audio = Buffer.from(koffi.decode(pcm, 'uint8_t', len));
|
|
38
39
|
if (queued > 100) { notify({ type: 'overflow', id }); return; }
|
|
@@ -51,7 +52,7 @@ try {
|
|
|
51
52
|
await asyncCall(api.init, 0);
|
|
52
53
|
notify({ type: 'ready', version: library.func('const char *um_sdk_version(void)')() });
|
|
53
54
|
} catch {
|
|
54
|
-
notify({ type: 'fatal', message: '
|
|
55
|
+
notify({ type: 'fatal', message: msg('error.sdk') });
|
|
55
56
|
process.exitCode = 1; setTimeout(() => process.exit(1), 50);
|
|
56
57
|
}
|
|
57
58
|
async function close() {
|
package/src/devices/native.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { message as msg } from '../shared/i18n.mjs';
|
|
1
2
|
import { EventEmitter } from 'node:events';
|
|
2
3
|
import { fork } from 'node:child_process';
|
|
3
4
|
import { fileURLToPath } from 'node:url';
|
|
@@ -10,7 +11,7 @@ export class MouseSdk extends EventEmitter {
|
|
|
10
11
|
const target = `${process.platform}-${process.arch}`;
|
|
11
12
|
const filename = process.platform === 'win32' ? 'uMouseSdk.dll' : 'libuMouseSdk.dylib';
|
|
12
13
|
const path = this.config.libraryPath ?? fileURLToPath(new URL(`../../native/${target}/${filename}`, import.meta.url));
|
|
13
|
-
if (!existsSync(path)) throw new Error(
|
|
14
|
+
if (!existsSync(path)) throw new Error(msg('error.sdk'));
|
|
14
15
|
const child = fork(fileURLToPath(new URL('./native-worker.mjs', import.meta.url)), [path], {
|
|
15
16
|
stdio: ['ignore', 'ignore', 'ignore', 'ipc'], execArgv: [],
|
|
16
17
|
});
|
|
@@ -27,7 +28,7 @@ export class MouseSdk extends EventEmitter {
|
|
|
27
28
|
finally { diagnosing = false; }
|
|
28
29
|
};
|
|
29
30
|
this.starting = new Promise((resolve, reject) => {
|
|
30
|
-
const timer = setTimeout(() => { child.kill(); reject(new Error('
|
|
31
|
+
const timer = setTimeout(() => { child.kill(); reject(new Error(msg('error.timeout'))); }, 15000);
|
|
31
32
|
child.on('message', message => {
|
|
32
33
|
if (message.type === 'ready') {
|
|
33
34
|
clearTimeout(timer); resolve(message.version);
|
|
@@ -49,23 +50,23 @@ export class MouseSdk extends EventEmitter {
|
|
|
49
50
|
clearInterval(this.diagnosticTimer);
|
|
50
51
|
clearTimeout(timer);
|
|
51
52
|
if (this.child === child) this.child = undefined;
|
|
52
|
-
for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(new Error('
|
|
53
|
+
for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(new Error(msg('error.sdk'))); }
|
|
53
54
|
this.pending.clear();
|
|
54
|
-
reject(new Error('
|
|
55
|
-
if (!this.stopping) this.emit('fault', '
|
|
55
|
+
reject(new Error(msg('error.sdk')));
|
|
56
|
+
if (!this.stopping) this.emit('fault', msg('error.sdk'));
|
|
56
57
|
};
|
|
57
58
|
child.once('exit', failed); child.once('error', failed);
|
|
58
59
|
});
|
|
59
60
|
return this.starting;
|
|
60
61
|
}
|
|
61
62
|
command(command, fields = {}) {
|
|
62
|
-
if (!this.child?.connected) return Promise.reject(new Error('
|
|
63
|
+
if (!this.child?.connected) return Promise.reject(new Error(msg('error.sdk')));
|
|
63
64
|
const requestId = ++this.serial;
|
|
64
65
|
return new Promise((resolve, reject) => {
|
|
65
|
-
const timer = setTimeout(() => { this.pending.delete(requestId); reject(new Error('
|
|
66
|
+
const timer = setTimeout(() => { this.pending.delete(requestId); reject(new Error(msg('error.timeout'))); }, 3000);
|
|
66
67
|
this.pending.set(requestId, { resolve, reject, timer });
|
|
67
68
|
this.child.send({ command, requestId, ...fields }, error => {
|
|
68
|
-
if (error) { clearTimeout(timer); this.pending.delete(requestId); reject(new Error('
|
|
69
|
+
if (error) { clearTimeout(timer); this.pending.delete(requestId); reject(new Error(msg('error.device'))); }
|
|
69
70
|
});
|
|
70
71
|
});
|
|
71
72
|
}
|