@sonicloud/dsh-sonicloud-device 0.1.1 → 0.1.3
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 -0
- package/CHANGELOG.zh.md +44 -0
- package/README.md +81 -86
- package/README.zh.md +135 -0
- package/dist/build.json +1 -1
- package/dist/client.js +202 -28
- package/docs/contributing/development.md +51 -28
- package/docs/images/plugin-install.png +0 -0
- package/docs/images/sonicloud-device.png +0 -0
- package/docs/specs/ci-cd.md +24 -37
- package/docs/specs/mouse-settings.md +7 -34
- package/docs/specs/smart-mouse-plugin.md +51 -32
- package/native/README.md +4 -0
- package/native/desktop/VOICE_SOURCE.json +16 -0
- package/native/desktop/VoicePanel.cs +191 -59
- package/native/desktop/VoicePanel.swift +27 -0
- 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/desktop/typer.dll +0 -0
- package/native/desktop/windows.ps1 +1 -1
- 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 +2 -1
- package/src/desktop/presentation.mjs +18 -4
- package/src/desktop/screenshot-worker.mjs +225 -0
- package/src/desktop/screenshot.mjs +185 -0
- package/src/devices/actions.mjs +7 -1
- package/src/devices/manager.mjs +145 -81
- package/src/host/index.mjs +5 -1
- package/src/shared/remote.mjs +5 -0
- /package/{src/client/assets → docs/images}/contact-wechat.jpg +0 -0
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { createInterface } from 'node:readline';
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { chmodSync, existsSync } from 'node:fs';
|
|
4
5
|
|
|
5
6
|
// Private stdio IPC: transcripts never appear in process arguments, files, or logs.
|
|
6
7
|
export class DesktopPresentation {
|
|
@@ -13,7 +14,11 @@ export class DesktopPresentation {
|
|
|
13
14
|
if (this.child) return;
|
|
14
15
|
const root = new URL('../../native/desktop/', import.meta.url);
|
|
15
16
|
let file, args = [];
|
|
16
|
-
if (this.platform === 'darwin')
|
|
17
|
+
if (this.platform === 'darwin') {
|
|
18
|
+
file = fileURLToPath(new URL(`darwin-${this.arch}/Sonicloud Voice.app/Contents/MacOS/sonicloud-voice`, root));
|
|
19
|
+
// Windows 生成的 npm 包不保留 Unix 执行位,启动前恢复随包程序权限。
|
|
20
|
+
if (existsSync(file)) chmodSync(file, 0o755);
|
|
21
|
+
}
|
|
17
22
|
else if (this.platform === 'win32') {
|
|
18
23
|
file = 'powershell.exe'; args = ['-NoProfile', '-NonInteractive', '-STA', '-ExecutionPolicy', 'Bypass', '-File', fileURLToPath(new URL('windows.ps1', root))];
|
|
19
24
|
} else throw new Error('当前平台不支持桌面语音浮层');
|
|
@@ -28,7 +33,7 @@ export class DesktopPresentation {
|
|
|
28
33
|
if (pending) {
|
|
29
34
|
clearTimeout(pending.timer); this.requests.delete(message.id);
|
|
30
35
|
if (message.ok) pending.resolve(message.value);
|
|
31
|
-
else pending.reject(new Error('桌面语音浮层操作失败'));
|
|
36
|
+
else pending.reject(new Error(message.message || '桌面语音浮层操作失败'));
|
|
32
37
|
}
|
|
33
38
|
});
|
|
34
39
|
const failed = () => {
|
|
@@ -46,13 +51,13 @@ export class DesktopPresentation {
|
|
|
46
51
|
if (!this.child || this.closed) return;
|
|
47
52
|
this.child.stdin.write(JSON.stringify(message) + '\n');
|
|
48
53
|
}
|
|
49
|
-
request(message) {
|
|
54
|
+
request(message, { killOnTimeout = true } = {}) {
|
|
50
55
|
this.start();
|
|
51
56
|
const id = ++this.sequence;
|
|
52
57
|
return new Promise((resolve, reject) => {
|
|
53
58
|
const timer = setTimeout(() => {
|
|
54
59
|
this.requests.delete(id); reject(new Error('桌面语音浮层响应超时,请重试'));
|
|
55
|
-
this.child?.kill();
|
|
60
|
+
if (killOnTimeout) this.child?.kill();
|
|
56
61
|
}, this.timeoutMs);
|
|
57
62
|
this.requests.set(id, { resolve, reject, timer }); this.send({ ...message, id });
|
|
58
63
|
});
|
|
@@ -61,6 +66,15 @@ export class DesktopPresentation {
|
|
|
61
66
|
this.sessionId = run.id;
|
|
62
67
|
await this.request({ command: 'begin', sessionId: run.id, action: run.action });
|
|
63
68
|
}
|
|
69
|
+
async permissions(action = 'check') {
|
|
70
|
+
if (!['check', 'accessibility', 'refresh'].includes(action)) throw new Error('不支持此打字权限操作');
|
|
71
|
+
if (this.closed) throw new Error('桌面语音浮层已关闭');
|
|
72
|
+
if (this.platform !== 'darwin') return { supported: false, accessibility: true, helperApp: '' };
|
|
73
|
+
const value = await this.request({ command: 'permissions', action }, { killOnTimeout: false });
|
|
74
|
+
if (!value || value.supported !== true || typeof value.accessibility !== 'boolean' || typeof value.helperApp !== 'string')
|
|
75
|
+
throw new Error('打字权限状态不可用,请更新插件后重试');
|
|
76
|
+
return value;
|
|
77
|
+
}
|
|
64
78
|
event(event) {
|
|
65
79
|
if (event.type === 'devices' || event.type === 'request' || event.type === 'result') return;
|
|
66
80
|
if (event.sessionId && event.sessionId !== this.sessionId) return;
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import koffi from 'koffi';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
|
|
4
|
+
const [libraryPath, helperPath] = process.argv.slice(2);
|
|
5
|
+
if (process.platform === 'win32') process.env.PATH = dirname(libraryPath) + ';' + (process.env.PATH || '');
|
|
6
|
+
const inFlight = new Set();
|
|
7
|
+
const call = (fn, ...args) => {
|
|
8
|
+
const pending = new Promise((resolve, reject) => fn.async(...args, (error, value) => error ? reject(error) : resolve(value)));
|
|
9
|
+
inFlight.add(pending);
|
|
10
|
+
pending.then(() => inFlight.delete(pending), () => inFlight.delete(pending));
|
|
11
|
+
return pending;
|
|
12
|
+
};
|
|
13
|
+
const callbacks = [];
|
|
14
|
+
let api, handle, closing = false, closePromise, connected = false, connection, disconnected, stateRequest;
|
|
15
|
+
let capabilities = new Set();
|
|
16
|
+
let commands = Promise.resolve(), events = Promise.resolve();
|
|
17
|
+
function send(message) {
|
|
18
|
+
if (!process.connected) return;
|
|
19
|
+
try { process.send(message, () => {}); } catch { /* 父进程可能已经退出。 */ }
|
|
20
|
+
}
|
|
21
|
+
const notice = message => { if (!closing) send({ type: 'notice', message }); };
|
|
22
|
+
function finishConnection(error) {
|
|
23
|
+
if (!connection) return;
|
|
24
|
+
clearTimeout(connection.timer);
|
|
25
|
+
const pending = connection; connection = undefined;
|
|
26
|
+
if (error) pending.reject(error); else pending.resolve();
|
|
27
|
+
}
|
|
28
|
+
function finishState(error, value, request = stateRequest) {
|
|
29
|
+
if (!request || stateRequest !== request) return;
|
|
30
|
+
stateRequest = undefined; clearTimeout(request.timer);
|
|
31
|
+
if (error) request.reject(error); else request.resolve(value);
|
|
32
|
+
}
|
|
33
|
+
const errorMessage = rc => rc === -3 ? '截图正在进行,请先完成或取消当前截图'
|
|
34
|
+
: rc === -2 ? '截图进程未连接,请重试' : '截图调用失败,请重试';
|
|
35
|
+
|
|
36
|
+
// 原生线程回调只保留事件文本并排队;所有 FFI 调用离开回调后异步执行。
|
|
37
|
+
function queueEvent(json) {
|
|
38
|
+
const text = String(json || '');
|
|
39
|
+
setImmediate(() => {
|
|
40
|
+
let event; try { event = JSON.parse(text); } catch { notice('截图组件返回无效事件,请重试'); return; }
|
|
41
|
+
if (event.type === 'disconnected') {
|
|
42
|
+
connected = false; capabilities = new Set();
|
|
43
|
+
finishState(new Error('截图进程已断开,请重新检查权限'));
|
|
44
|
+
finishConnection(new Error('截图进程已断开,请重试'));
|
|
45
|
+
disconnected?.();
|
|
46
|
+
}
|
|
47
|
+
if (closing) return;
|
|
48
|
+
events = events.then(async () => {
|
|
49
|
+
if (closing) return;
|
|
50
|
+
if (['connected', 'disconnected', 'hello_ack', 'session_started', 'session_ended', 'pin_opened', 'pin_closed', 'state_report'].includes(event.type)) {
|
|
51
|
+
send({ type: 'event', event });
|
|
52
|
+
}
|
|
53
|
+
if (event.type === 'connected') {
|
|
54
|
+
const rc = await call(api.config, handle, JSON.stringify({ ocr_visible: false, trans_enabled: false }));
|
|
55
|
+
if (rc !== 0) { connected = false; finishConnection(new Error('截图配置失败,请重试')); return; }
|
|
56
|
+
connected = true; finishConnection();
|
|
57
|
+
} else if (event.type === 'hello_ack') {
|
|
58
|
+
capabilities = new Set(Array.isArray(event.capabilities) ? event.capabilities : []);
|
|
59
|
+
} else if (event.type === 'state_report') {
|
|
60
|
+
finishState(undefined, event);
|
|
61
|
+
} else if (event.type === 'disconnected') {
|
|
62
|
+
connected = false;
|
|
63
|
+
} else if (event.type === 'connect_failed') {
|
|
64
|
+
connected = false;
|
|
65
|
+
const message = event.code === 'stale_helper_refused'
|
|
66
|
+
? '截图进程被其他程序占用,请关闭其他截图程序后重试' : '截图进程连接失败,请重试';
|
|
67
|
+
if (connection) finishConnection(new Error(message)); else notice(message);
|
|
68
|
+
} else if (event.type === 'error' || event.type === 'word_failed') {
|
|
69
|
+
notice(event.code === 'permission_screen_required'
|
|
70
|
+
? '请先在“声云设备”中为 screenhelper 授权屏幕录制,再重新检查权限'
|
|
71
|
+
: ['permission_busy', 'permission_request_busy'].includes(event.code) ? '请先完成当前截图或关闭贴图,再设置截图权限'
|
|
72
|
+
: '截图操作失败,请检查系统权限后重试');
|
|
73
|
+
} else if (['word_started', 'word_result', 'ocr_requested'].includes(event.type)) {
|
|
74
|
+
notice('当前插件尚未接入截图文字识别和 Word 导出,请使用复制、保存或贴图');
|
|
75
|
+
}
|
|
76
|
+
}).catch(() => { connected = false; finishConnection(new Error('截图组件通信失败,请重试')); notice('截图组件通信失败,请重试'); });
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function initialize() {
|
|
81
|
+
const library = koffi.load(libraryPath);
|
|
82
|
+
api = {
|
|
83
|
+
create: library.func('void *sct_create()'),
|
|
84
|
+
destroy: library.func('void sct_destroy_wait(void *h)'),
|
|
85
|
+
setEvent: library.func('int sct_set_event_callback(void *h, void *fn, void *user)'),
|
|
86
|
+
setLog: library.func('int sct_set_log_callback(void *h, void *fn, void *user)'),
|
|
87
|
+
helper: library.func('int sct_set_helper_path(void *h, const char *path)'),
|
|
88
|
+
connect: library.func('int sct_connect_async(void *h, int timeout_ms)'),
|
|
89
|
+
capture: library.func('int sct_start_capture(void *h, const char *trigger)'),
|
|
90
|
+
query: library.func('int sct_query_state(void *h)'),
|
|
91
|
+
config: library.func('int sct_set_config(void *h, const char *json)'),
|
|
92
|
+
shutdown: library.func('int sct_shutdown(void *h, const char *policy)'),
|
|
93
|
+
};
|
|
94
|
+
handle = await call(api.create);
|
|
95
|
+
if (!handle) throw new Error('截图句柄创建失败');
|
|
96
|
+
const eventProto = koffi.proto('void SonicloudScreenshotEvent(void *user, const char *json, const uint8_t *payload, int len)');
|
|
97
|
+
const logProto = koffi.proto('void SonicloudScreenshotLog(void *user, int level, const char *message)');
|
|
98
|
+
callbacks.push(koffi.register((_user, json) => queueEvent(json), koffi.pointer(eventProto)));
|
|
99
|
+
callbacks.push(koffi.register(() => {}, koffi.pointer(logProto)));
|
|
100
|
+
if (await call(api.setEvent, handle, callbacks[0], null) !== 0 ||
|
|
101
|
+
await call(api.setLog, handle, callbacks[1], null) !== 0 ||
|
|
102
|
+
await call(api.helper, handle, helperPath) !== 0) throw new Error('截图组件初始化失败');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function ensureConnected() {
|
|
106
|
+
if (closing) throw new Error('截图服务已关闭');
|
|
107
|
+
if (connected) return;
|
|
108
|
+
if (!connection) {
|
|
109
|
+
let resolve, reject;
|
|
110
|
+
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
|
|
111
|
+
connection = { promise, resolve, reject, timer: setTimeout(() => finishConnection(new Error('截图进程连接超时,请重试')), 6500) };
|
|
112
|
+
call(api.connect, handle, 5000).then(rc => { if (rc !== 0) finishConnection(new Error(errorMessage(rc))); },
|
|
113
|
+
() => finishConnection(new Error('截图进程连接失败,请重试')));
|
|
114
|
+
}
|
|
115
|
+
return connection.promise;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function queryState() {
|
|
119
|
+
if (closing) throw new Error('截图服务已关闭');
|
|
120
|
+
if (stateRequest) return stateRequest.promise;
|
|
121
|
+
let resolve, reject;
|
|
122
|
+
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
|
|
123
|
+
const request = { promise, resolve, reject,
|
|
124
|
+
timer: setTimeout(() => finishState(new Error('截图权限检查超时,请先完成系统授权窗口后重试'), undefined, request), 2500) };
|
|
125
|
+
stateRequest = request;
|
|
126
|
+
call(api.query, handle).then(rc => {
|
|
127
|
+
if (rc !== 0) finishState(new Error('截图权限检查失败,请重试'), undefined, request);
|
|
128
|
+
}, () => finishState(new Error('截图权限检查失败,请重试'), undefined, request));
|
|
129
|
+
return promise;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function permissionView(state) {
|
|
133
|
+
if (typeof state.perm_screen !== 'boolean' || typeof state.perm_a11y !== 'boolean')
|
|
134
|
+
throw new Error('截图组件未返回 macOS 权限状态,请更新插件');
|
|
135
|
+
return { supported: true, screenRecording: state.perm_screen, accessibility: state.perm_a11y,
|
|
136
|
+
helperApp: typeof state.helper_app === 'string' ? state.helper_app.slice(0, 4096) : '' };
|
|
137
|
+
}
|
|
138
|
+
const idle = state => state.capturing === false && state.pins_alive === 0 && state.pin_editing !== true;
|
|
139
|
+
|
|
140
|
+
async function stopHelper() {
|
|
141
|
+
let timer;
|
|
142
|
+
const stopped = new Promise(resolve => {
|
|
143
|
+
disconnected = () => resolve(true);
|
|
144
|
+
timer = setTimeout(() => resolve(false), 2000);
|
|
145
|
+
});
|
|
146
|
+
try {
|
|
147
|
+
const rc = await call(api.shutdown, handle, 'close_now');
|
|
148
|
+
if (rc !== 0) throw new Error('截图进程未能退出,请稍后重新检查权限');
|
|
149
|
+
if (!await stopped) throw new Error('截图进程正在退出,请稍后重新检查权限');
|
|
150
|
+
} finally { clearTimeout(timer); disconnected = undefined; }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function permissions(action) {
|
|
154
|
+
if (!['check', 'screen', 'accessibility', 'refresh'].includes(action)) throw new Error('不支持的截图权限操作');
|
|
155
|
+
if (process.platform !== 'darwin') return { supported: false, screenRecording: true, accessibility: true, helperApp: '' };
|
|
156
|
+
let state = await queryState();
|
|
157
|
+
let view = permissionView(state);
|
|
158
|
+
if (action === 'refresh' && (!view.screenRecording || !view.accessibility) && idle(state)) {
|
|
159
|
+
await stopHelper(); await ensureConnected();
|
|
160
|
+
state = await queryState(); view = permissionView(state);
|
|
161
|
+
}
|
|
162
|
+
if (action === 'screen' || action === 'accessibility') {
|
|
163
|
+
if (!idle(state)) throw new Error('请先完成当前截图或关闭贴图,再设置截图权限');
|
|
164
|
+
if (!capabilities.has('permission_preflight')) throw new Error('截图组件尚不支持授权引导,请重新启用或更新插件');
|
|
165
|
+
const rc = await call(api.config, handle, JSON.stringify({ permission_request: action }));
|
|
166
|
+
if (rc !== 0) throw new Error('截图授权请求未能发送,请重试');
|
|
167
|
+
// 系统授权由用户完成;写入请求只代表已受理,不能当作已授权。
|
|
168
|
+
}
|
|
169
|
+
return view;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
process.on('message', message => {
|
|
173
|
+
if (message?.command === 'close') { void close(); return; }
|
|
174
|
+
if (closing || !['capture', 'permissions'].includes(message?.command)) return;
|
|
175
|
+
commands = commands.then(async () => {
|
|
176
|
+
await initialized;
|
|
177
|
+
await ensureConnected();
|
|
178
|
+
if (closing) throw new Error('截图服务已关闭');
|
|
179
|
+
if (message.command === 'permissions') {
|
|
180
|
+
const value = await permissions(message.action ?? 'check');
|
|
181
|
+
send({ type: 'reply', requestId: message.requestId, ok: true, value });
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
if (process.platform === 'darwin' && !permissionView(await queryState()).screenRecording)
|
|
185
|
+
throw new Error('请先在“声云设备”中为 screenhelper 授权屏幕录制,再重新检查权限');
|
|
186
|
+
const trigger = typeof message.trigger === 'string' ? message.trigger.replace(/[^a-zA-Z0-9_.-]/g, '_').slice(0, 64) : 'ui';
|
|
187
|
+
const rc = await call(api.capture, handle, trigger || 'ui');
|
|
188
|
+
if (rc !== 0) throw new Error(errorMessage(rc));
|
|
189
|
+
send({ type: 'reply', requestId: message.requestId, ok: true });
|
|
190
|
+
}).catch(error => { if (!closing) send({ type: 'reply', requestId: message.requestId, ok: false, message: error.message }); });
|
|
191
|
+
});
|
|
192
|
+
process.on('disconnect', () => { void close(); });
|
|
193
|
+
const initialized = initialize();
|
|
194
|
+
initialized.then(() => { if (!closing) send({ type: 'ready' }); }).catch(() => {
|
|
195
|
+
send({ type: 'fatal' }); void close();
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
function close() {
|
|
199
|
+
if (closePromise) return closePromise;
|
|
200
|
+
closing = true; connected = false;
|
|
201
|
+
finishConnection(new Error('截图服务已关闭'));
|
|
202
|
+
finishState(new Error('截图服务已关闭'));
|
|
203
|
+
closePromise = (async () => {
|
|
204
|
+
await initialized.catch(() => {});
|
|
205
|
+
await commands.catch(() => {}); await events.catch(() => {});
|
|
206
|
+
// 包含尚未返回的 connect_async FFI 调用,避免销毁与外部调用并发使用句柄。
|
|
207
|
+
await Promise.allSettled([...inFlight]);
|
|
208
|
+
if (handle) {
|
|
209
|
+
let timer;
|
|
210
|
+
const helperExited = new Promise(resolve => { disconnected = resolve; timer = setTimeout(resolve, 2000); });
|
|
211
|
+
try {
|
|
212
|
+
const rc = await call(api.shutdown, handle, 'close_now');
|
|
213
|
+
// 等待 helper 消费退出帧并断开,立即 destroy 会导致已写的帧被丢弃。
|
|
214
|
+
if (rc === 0) await helperExited;
|
|
215
|
+
} catch { /* 断连时仍继续完成销毁屏障。 */ }
|
|
216
|
+
finally { clearTimeout(timer); disconnected = undefined; }
|
|
217
|
+
await call(api.destroy, handle);
|
|
218
|
+
handle = undefined;
|
|
219
|
+
}
|
|
220
|
+
// destroy_wait 已确认原生线程及在途回调全部退出。
|
|
221
|
+
for (const callback of callbacks) koffi.unregister(callback);
|
|
222
|
+
if (process.connected) process.disconnect();
|
|
223
|
+
})().catch(() => { process.exitCode = 1; if (process.connected) process.disconnect(); });
|
|
224
|
+
return closePromise;
|
|
225
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { fork, execFile } from 'node:child_process';
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { mkdir, mkdtemp, readFile, rename, rm, stat } from 'node:fs/promises';
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { promisify } from 'node:util';
|
|
10
|
+
|
|
11
|
+
const execute = promisify(execFile);
|
|
12
|
+
const nativeRoot = fileURLToPath(new URL('../../native/screenshot/', import.meta.url));
|
|
13
|
+
const macPaths = directory => ({
|
|
14
|
+
libraryPath: join(directory, 'screentool', 'libscreentool.dylib'),
|
|
15
|
+
helperPath: join(directory, 'screentool', 'helper', 'screenhelper.app', 'Contents', 'MacOS', 'screenhelper'),
|
|
16
|
+
});
|
|
17
|
+
const complete = paths => existsSync(paths.libraryPath) && existsSync(paths.helperPath);
|
|
18
|
+
|
|
19
|
+
// ditto 在 macOS 上还原软链接、执行权限及原始签名;缓存不修改随包 app。
|
|
20
|
+
export async function prepareMacScreenshot({
|
|
21
|
+
archivePath = join(nativeRoot, 'darwin-arm64', 'screentool-macos-1.2.2.zip'),
|
|
22
|
+
cacheRoot = join(homedir(), 'Library', 'Caches', 'sonicloud-device'),
|
|
23
|
+
extract = execute,
|
|
24
|
+
} = {}) {
|
|
25
|
+
const digest = createHash('sha256').update(await readFile(archivePath)).digest('hex');
|
|
26
|
+
const directory = join(cacheRoot, `screentool-${digest}`);
|
|
27
|
+
const paths = macPaths(directory);
|
|
28
|
+
if (complete(paths)) return paths;
|
|
29
|
+
await mkdir(cacheRoot, { recursive: true });
|
|
30
|
+
const lock = `${directory}.lock`;
|
|
31
|
+
const deadline = Date.now() + 35000;
|
|
32
|
+
for (;;) {
|
|
33
|
+
try { await mkdir(lock); break; }
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (error.code !== 'EEXIST') throw error;
|
|
36
|
+
if (complete(paths)) return paths;
|
|
37
|
+
// ditto 最多运行 30 秒;清理崩溃后留下的过期准备锁。
|
|
38
|
+
try { if (Date.now() - (await stat(lock)).mtimeMs > 60000) { await rm(lock, { recursive: true, force: true }); continue; } }
|
|
39
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
40
|
+
if (Date.now() > deadline) throw new Error('截图组件正在准备,请稍后重试');
|
|
41
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
let temporary;
|
|
45
|
+
try {
|
|
46
|
+
if (complete(paths)) return paths;
|
|
47
|
+
// 仅清理当前压缩包哈希对应的受控缓存目录,不触碰其他版本或原始 app。
|
|
48
|
+
await rm(directory, { recursive: true, force: true });
|
|
49
|
+
temporary = await mkdtemp(join(cacheRoot, '.screentool-'));
|
|
50
|
+
await extract('/usr/bin/ditto', ['-x', '-k', archivePath, temporary], { timeout: 30000, maxBuffer: 8192 });
|
|
51
|
+
if (!complete(macPaths(temporary))) throw new Error('截图组件解压不完整');
|
|
52
|
+
// 另一进程可能已完成相同版本;只清理本次创建的临时目录。
|
|
53
|
+
if (!complete(paths)) {
|
|
54
|
+
try { await rename(temporary, directory); }
|
|
55
|
+
catch (error) { if (!complete(paths)) throw error; }
|
|
56
|
+
}
|
|
57
|
+
return paths;
|
|
58
|
+
} finally {
|
|
59
|
+
if (temporary) await rm(temporary, { recursive: true, force: true });
|
|
60
|
+
await rm(lock, { recursive: true, force: true });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export class ScreenshotService extends EventEmitter {
|
|
65
|
+
constructor({ platform = process.platform, arch = process.arch, launch = fork,
|
|
66
|
+
timeoutMs = 9000, startTimeoutMs = 10000, closeTimeoutMs = 5000,
|
|
67
|
+
libraryPath, helperPath, prepareMac = prepareMacScreenshot, exists = existsSync } = {}) {
|
|
68
|
+
super();
|
|
69
|
+
Object.assign(this, { platform, arch, launch, timeoutMs, startTimeoutMs, closeTimeoutMs,
|
|
70
|
+
libraryPath, helperPath, prepareMac, exists });
|
|
71
|
+
this.pending = new Map(); this.sequence = 0;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
start() {
|
|
75
|
+
if (this.closed) return Promise.reject(new Error('截图服务已关闭'));
|
|
76
|
+
if (this.starting) return this.starting;
|
|
77
|
+
const attempt = this.startWorker().catch(error => { if (this.starting === attempt) this.starting = undefined; throw error; });
|
|
78
|
+
this.starting = attempt;
|
|
79
|
+
return this.starting;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async startWorker() {
|
|
83
|
+
const target = `${this.platform}-${this.arch}`;
|
|
84
|
+
if (!['win32-x64', 'darwin-arm64'].includes(target)) throw new Error('当前平台不支持截图,请使用 Windows x64 或 Apple 芯片 Mac');
|
|
85
|
+
let paths = { libraryPath: this.libraryPath, helperPath: this.helperPath };
|
|
86
|
+
if (!paths.libraryPath || !paths.helperPath) {
|
|
87
|
+
try {
|
|
88
|
+
const defaults = this.platform === 'darwin' ? await this.prepareMac() : {
|
|
89
|
+
libraryPath: join(nativeRoot, target, 'screentool.dll'),
|
|
90
|
+
helperPath: join(nativeRoot, target, 'screenhelper.exe'),
|
|
91
|
+
};
|
|
92
|
+
paths = { libraryPath: paths.libraryPath ?? defaults.libraryPath, helperPath: paths.helperPath ?? defaults.helperPath };
|
|
93
|
+
} catch { throw new Error('截图组件准备失败,请检查插件安装、缓存目录权限并重试'); }
|
|
94
|
+
}
|
|
95
|
+
if (this.closed) throw new Error('截图服务已关闭');
|
|
96
|
+
if (!this.exists(paths.libraryPath) || !this.exists(paths.helperPath)) throw new Error('截图组件缺失,请重新安装插件');
|
|
97
|
+
let child;
|
|
98
|
+
try {
|
|
99
|
+
child = this.launch(fileURLToPath(new URL('./screenshot-worker.mjs', import.meta.url)),
|
|
100
|
+
[paths.libraryPath, paths.helperPath], { stdio: ['ignore', 'ignore', 'ignore', 'ipc'], execArgv: [], windowsHide: true });
|
|
101
|
+
} catch { throw new Error('截图服务启动失败,请检查插件安装并重试'); }
|
|
102
|
+
this.child = child;
|
|
103
|
+
return new Promise((resolve, reject) => {
|
|
104
|
+
let ready = false, failed = false;
|
|
105
|
+
const timer = setTimeout(() => { fail('截图服务启动超时,请重试'); child.kill(); }, this.startTimeoutMs);
|
|
106
|
+
const fail = message => {
|
|
107
|
+
if (failed) return;
|
|
108
|
+
failed = true; clearTimeout(timer);
|
|
109
|
+
if (this.child !== child) return;
|
|
110
|
+
this.child = undefined; this.starting = undefined;
|
|
111
|
+
for (const pending of this.pending.values()) { clearTimeout(pending.timer); pending.reject(new Error(message)); }
|
|
112
|
+
this.pending.clear(); reject(new Error(message));
|
|
113
|
+
if (ready && !this.closed) this.emit('notice', message);
|
|
114
|
+
};
|
|
115
|
+
child.on('message', message => {
|
|
116
|
+
if (this.child !== child || !message || typeof message !== 'object') return;
|
|
117
|
+
if (message.type === 'ready') { clearTimeout(timer); ready = true; resolve(); }
|
|
118
|
+
else if (message.type === 'fatal') { fail('截图组件加载失败,请检查系统架构、运行依赖并重新安装插件'); child.kill(); }
|
|
119
|
+
else if (message.type === 'notice') { if (!this.closed && typeof message.message === 'string') this.emit('notice', message.message); }
|
|
120
|
+
else if (message.type === 'event') { if (!this.closed && message.event && typeof message.event.type === 'string') this.emit('event', message.event); }
|
|
121
|
+
else if (message.type === 'reply') {
|
|
122
|
+
const pending = this.pending.get(message.requestId);
|
|
123
|
+
if (!pending) return;
|
|
124
|
+
clearTimeout(pending.timer); this.pending.delete(message.requestId);
|
|
125
|
+
if (message.ok) pending.resolve(message.value ?? true);
|
|
126
|
+
else pending.reject(new Error(message.message || '截图失败,请重试'));
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
child.once('exit', () => fail(this.closed ? '截图服务已关闭' : '截图服务已停止,请重试'));
|
|
130
|
+
child.once('error', () => { fail('截图服务启动失败,请检查插件安装并重试'); child.kill(); });
|
|
131
|
+
child.once('disconnect', () => { fail(this.closed ? '截图服务已关闭' : '截图服务连接已断开,请重试'); if (!this.closed) child.kill(); });
|
|
132
|
+
this.rejectStarting = () => { clearTimeout(timer); reject(new Error('截图服务已关闭')); };
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
capture(trigger = 'ui') { return this.command('capture', { trigger }); }
|
|
137
|
+
|
|
138
|
+
async permissions(action = 'check') {
|
|
139
|
+
if (!['check', 'screen', 'accessibility', 'refresh'].includes(action)) throw new Error('不支持的截图权限操作');
|
|
140
|
+
if (this.closed) throw new Error('截图服务已关闭');
|
|
141
|
+
if (this.platform !== 'darwin') return { supported: false, screenRecording: true, accessibility: true, helperApp: '' };
|
|
142
|
+
const state = await this.command('permissions', { action }, Math.max(this.timeoutMs, 20000));
|
|
143
|
+
if (!state || typeof state !== 'object' || state.supported !== true || typeof state.screenRecording !== 'boolean'
|
|
144
|
+
|| typeof state.accessibility !== 'boolean' || typeof state.helperApp !== 'string') throw new Error('截图权限状态无效,请重新加载插件');
|
|
145
|
+
return state;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async command(command, fields = {}, timeoutMs = this.timeoutMs) {
|
|
149
|
+
await this.start();
|
|
150
|
+
if (this.closed) throw new Error('截图服务已关闭');
|
|
151
|
+
const child = this.child;
|
|
152
|
+
if (!child?.connected) throw new Error('截图服务未连接,请重试');
|
|
153
|
+
const requestId = ++this.sequence;
|
|
154
|
+
return new Promise((resolve, reject) => {
|
|
155
|
+
const timer = setTimeout(() => {
|
|
156
|
+
this.pending.delete(requestId); reject(new Error('截图服务响应超时,请重试')); child.kill();
|
|
157
|
+
}, timeoutMs);
|
|
158
|
+
this.pending.set(requestId, { resolve, reject, timer });
|
|
159
|
+
try {
|
|
160
|
+
child.send({ command, ...fields, requestId }, error => {
|
|
161
|
+
if (!error) return;
|
|
162
|
+
const pending = this.pending.get(requestId);
|
|
163
|
+
if (pending) { clearTimeout(timer); this.pending.delete(requestId); reject(new Error('截图指令发送失败,请重试')); child.kill(); }
|
|
164
|
+
});
|
|
165
|
+
} catch { clearTimeout(timer); this.pending.delete(requestId); reject(new Error('截图指令发送失败,请重试')); child.kill(); }
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
close() {
|
|
170
|
+
if (this.closing) return this.closing;
|
|
171
|
+
this.closed = true; this.rejectStarting?.();
|
|
172
|
+
for (const pending of this.pending.values()) { clearTimeout(pending.timer); pending.reject(new Error('截图服务已关闭')); }
|
|
173
|
+
this.pending.clear();
|
|
174
|
+
const child = this.child;
|
|
175
|
+
this.closing = child ? new Promise(resolve => {
|
|
176
|
+
let timer;
|
|
177
|
+
const done = () => { clearTimeout(timer); child.off('exit', done); resolve(); };
|
|
178
|
+
timer = setTimeout(() => { child.kill(); done(); }, this.closeTimeoutMs);
|
|
179
|
+
child.once('exit', done);
|
|
180
|
+
try { if (child.connected) child.send({ command: 'close' }, error => { if (error) { child.kill(); done(); } }); else { child.kill(); done(); } }
|
|
181
|
+
catch { child.kill(); done(); }
|
|
182
|
+
}) : Promise.resolve();
|
|
183
|
+
return this.closing;
|
|
184
|
+
}
|
|
185
|
+
}
|
package/src/devices/actions.mjs
CHANGED
|
@@ -36,7 +36,13 @@ export async function systemAction(action, value, { platform = process.platform,
|
|
|
36
36
|
const scripts = {
|
|
37
37
|
enter: '$s=New-Object -ComObject WScript.Shell; $s.SendKeys("{ENTER}")',
|
|
38
38
|
backspace: '$s=New-Object -ComObject WScript.Shell; $s.SendKeys("{BACKSPACE}")',
|
|
39
|
-
|
|
39
|
+
// The window title varies with the active page, so title matching fails intermittently; activate by handle.
|
|
40
|
+
// Minimized windows need ShowWindow(SW_RESTORE) because AppActivate never restores them. When no visible handle
|
|
41
|
+
// exists (hidden to the tray), a second launch of the running exe reaches the single-instance handler, which
|
|
42
|
+
// restores or recreates the window from inside the app. The plugin backend itself runs the app exe as node via
|
|
43
|
+
// ELECTRON_RUN_AS_NODE, and a second launch inheriting that variable would also start as plain node and exit
|
|
44
|
+
// without any window, so the Electron overrides must be stripped before handing off.
|
|
45
|
+
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",
|
|
40
46
|
};
|
|
41
47
|
if (!scripts[action]) throw new Error('不支持此按键动作');
|
|
42
48
|
args = ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(scripts[action], 'utf16le').toString('base64')];
|