@andy.ian/dsh-homing 2.1.8 → 2.1.10
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/bin/window-agent-daemon.mjs +163 -82
- package/index.js +4 -0
- package/lib/orientation.mjs +11 -5
- package/lib/vendor/vnc.bundle.js +3 -0
- package/lib/vnc-app.js +7 -1
- package/lib/vnc-boot.js +1 -1
- package/lib/window-agent.ps1 +454 -0
- package/lib/window-remote.mjs +28 -12
- package/package.json +3 -2
|
@@ -32,6 +32,21 @@ const IDLE_SECONDS = Math.max(10, Number(process.env.DSH_AGENT_IDLE_SECONDS) ||
|
|
|
32
32
|
const LOG_FILE = path.join(agentDir(), 'window-agent.log')
|
|
33
33
|
|
|
34
34
|
const writeLogLine = createLogWriter(LOG_FILE)
|
|
35
|
+
const ORIENTATION_FILE = path.join(agentDir(), 'orientation.json')
|
|
36
|
+
|
|
37
|
+
function readOrientationState() {
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(fs.readFileSync(ORIENTATION_FILE, 'utf8'))
|
|
40
|
+
} catch {
|
|
41
|
+
return null
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function writeOrientationState(mode) {
|
|
46
|
+
try {
|
|
47
|
+
fs.writeFileSync(ORIENTATION_FILE, JSON.stringify({ mode, ts: Date.now() }) + '\n', 'utf8')
|
|
48
|
+
} catch { /* 忽略 */ }
|
|
49
|
+
}
|
|
35
50
|
|
|
36
51
|
function log(message) {
|
|
37
52
|
writeLogLine(`${new Date().toISOString()} [node-daemon] ${message}\n`)
|
|
@@ -40,64 +55,100 @@ function log(message) {
|
|
|
40
55
|
const isWindows = process.platform === 'win32'
|
|
41
56
|
|
|
42
57
|
// ---------------- PowerShell 工作进程(仅 Windows) ----------------
|
|
58
|
+
//
|
|
59
|
+
// 两套独立工作进程:
|
|
60
|
+
// - ops:窗口列表/截图/点击/键盘等,请求串行
|
|
61
|
+
// - rotate:只做转屏。独立进程,绝不被窗口操作的排队/卡死拖住
|
|
62
|
+
// 任何一个超时都会被杀掉,下次请求重建。
|
|
43
63
|
|
|
44
|
-
|
|
45
|
-
let
|
|
46
|
-
let
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
55
|
-
// stdio 工作进程只被守护进程使用,不需要 token(避免二次鉴权)
|
|
56
|
-
env: { ...process.env, DSH_AGENT_TOKEN: '' },
|
|
57
|
-
})
|
|
58
|
-
child.stderr.on('data', () => { /* 工作进程 stderr 忽略 */ })
|
|
59
|
-
workerReader = readline.createInterface({ input: child.stdout })
|
|
60
|
-
workerReader.on('line', (line) => {
|
|
61
|
-
const text = line.trim()
|
|
62
|
-
if (!text.startsWith('{')) return
|
|
63
|
-
let message = null
|
|
64
|
-
try { message = JSON.parse(text) } catch { return }
|
|
65
|
-
const resolve = workerPending.get(message.id)
|
|
66
|
-
if (resolve === undefined) return
|
|
67
|
-
workerPending.delete(message.id)
|
|
68
|
-
resolve(message)
|
|
69
|
-
})
|
|
70
|
-
const failPending = () => {
|
|
71
|
-
for (const [, resolve] of workerPending) resolve({ ok: false, error: '窗口工作进程已退出' })
|
|
72
|
-
workerPending.clear()
|
|
73
|
-
worker = null
|
|
64
|
+
function createWorker(label) {
|
|
65
|
+
let child = null
|
|
66
|
+
let reader = null
|
|
67
|
+
let stderr = ''
|
|
68
|
+
let seq = 0
|
|
69
|
+
const pending = new Map()
|
|
70
|
+
|
|
71
|
+
function failPending(message) {
|
|
72
|
+
for (const [, resolve] of pending) resolve({ ok: false, error: message })
|
|
73
|
+
pending.clear()
|
|
74
74
|
}
|
|
75
|
-
child.on('exit', () => { log('worker exit'); failPending() })
|
|
76
|
-
child.on('error', () => { log('worker error'); failPending() })
|
|
77
|
-
worker = child
|
|
78
|
-
return child
|
|
79
|
-
}
|
|
80
75
|
|
|
81
|
-
function
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
|
|
76
|
+
function ensure() {
|
|
77
|
+
if (!isWindows) throw new Error('窗口操作仅支持 Windows')
|
|
78
|
+
if (child !== null && child.exitCode === null) return child
|
|
79
|
+
const spawned = spawn(powershellExe(), ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', WORKER], {
|
|
80
|
+
windowsHide: true,
|
|
81
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
82
|
+
env: { ...process.env, DSH_AGENT_TOKEN: '' },
|
|
83
|
+
})
|
|
84
|
+
stderr = ''
|
|
85
|
+
spawned.stderr.on('data', (chunk) => { stderr = (stderr + String(chunk)).slice(-2000) })
|
|
86
|
+
reader = readline.createInterface({ input: spawned.stdout })
|
|
87
|
+
reader.on('line', (line) => {
|
|
88
|
+
const text = line.trim()
|
|
89
|
+
if (!text.startsWith('{')) return
|
|
90
|
+
let message = null
|
|
91
|
+
try { message = JSON.parse(text) } catch { return }
|
|
92
|
+
const resolve = pending.get(message.id)
|
|
93
|
+
if (resolve === undefined) return
|
|
94
|
+
pending.delete(message.id)
|
|
91
95
|
resolve(message)
|
|
92
96
|
})
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
97
|
+
spawned.on('exit', () => { log(label + ' worker exit'); failPending('窗口工作进程已退出') })
|
|
98
|
+
spawned.on('error', () => { log(label + ' worker error'); failPending('窗口工作进程启动失败') })
|
|
99
|
+
child = spawned
|
|
100
|
+
return spawned
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function kill() {
|
|
104
|
+
try { child?.kill() } catch { /* 忽略 */ }
|
|
105
|
+
child = null
|
|
106
|
+
failPending('窗口工作进程已重启')
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function call(request, timeoutMs = 20_000) {
|
|
110
|
+
const spawned = ensure()
|
|
111
|
+
const id = String(++seq)
|
|
112
|
+
return new Promise((resolve) => {
|
|
113
|
+
const timer = setTimeout(() => {
|
|
114
|
+
pending.delete(id)
|
|
115
|
+
log(label + ' worker timeout, restarting' + (stderr ? ': ' + stderr.replace(/\s+/gu, ' ').slice(-300) : ''))
|
|
116
|
+
try { spawned.kill() } catch { /* 忽略 */ }
|
|
117
|
+
child = null
|
|
118
|
+
resolve({ ok: false, error: 'timeout' })
|
|
119
|
+
}, timeoutMs)
|
|
120
|
+
pending.set(id, (message) => {
|
|
121
|
+
clearTimeout(timer)
|
|
122
|
+
resolve(message)
|
|
123
|
+
})
|
|
124
|
+
try {
|
|
125
|
+
spawned.stdin.write(JSON.stringify({ id, ...request }) + '\n')
|
|
126
|
+
} catch (error) {
|
|
127
|
+
clearTimeout(timer)
|
|
128
|
+
pending.delete(id)
|
|
129
|
+
resolve({ ok: false, error: String(error?.message ?? error) })
|
|
130
|
+
}
|
|
131
|
+
})
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return { call, kill }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const opsWorker = createWorker('ops')
|
|
138
|
+
const rotateWorker = createWorker('rotate')
|
|
139
|
+
|
|
140
|
+
function workerCall(request, timeoutMs = 20_000) {
|
|
141
|
+
return opsWorker.call(request, timeoutMs)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 转屏:独立进程;失败就杀掉重建再试一次,避免一次卡死影响用户操作 */
|
|
145
|
+
async function rotateWorkerCall(mode) {
|
|
146
|
+
const request = { cmd: 'rotate', mode }
|
|
147
|
+
const first = await rotateWorker.call(request, 15_000)
|
|
148
|
+
if (first.ok === true && first.result === 0) return first
|
|
149
|
+
log('rotate failed (' + (first.error ?? 'result=' + first.result) + '), retry with fresh worker')
|
|
150
|
+
rotateWorker.kill()
|
|
151
|
+
return rotateWorker.call(request, 15_000)
|
|
101
152
|
}
|
|
102
153
|
|
|
103
154
|
// ---------------- 转屏(跨平台分派) ----------------
|
|
@@ -130,9 +181,9 @@ async function linuxScreenSize() {
|
|
|
130
181
|
async function rotatePlatform(mode) {
|
|
131
182
|
const portrait = mode === 'portrait'
|
|
132
183
|
if (isWindows) {
|
|
133
|
-
const result = await
|
|
184
|
+
const result = await rotateWorkerCall(portrait ? 'portrait' : 'landscape')
|
|
134
185
|
return {
|
|
135
|
-
ok: result.ok === true,
|
|
186
|
+
ok: result.ok === true && result.result === 0,
|
|
136
187
|
result: result.result ?? null,
|
|
137
188
|
screen: { width: Number(result.screenWidth) || 0, height: Number(result.screenHeight) || 0 },
|
|
138
189
|
detail: `windows result=${result.result ?? '?'}`,
|
|
@@ -162,11 +213,31 @@ async function rotatePlatform(mode) {
|
|
|
162
213
|
|
|
163
214
|
let queue = Promise.resolve()
|
|
164
215
|
|
|
216
|
+
/** 转屏回横屏(空闲/DSH 退出时自动调用) */
|
|
217
|
+
async function restoreOrientation(reason) {
|
|
218
|
+
const state = readOrientationState()
|
|
219
|
+
const rotatedByUs = state?.mode === 'portrait'
|
|
220
|
+
if (!rotatedByUs) {
|
|
221
|
+
log('restore skip (' + reason + '): orientation not set by us')
|
|
222
|
+
return { ok: true, restored: false }
|
|
223
|
+
}
|
|
224
|
+
const result = await rotatePlatform('landscape')
|
|
225
|
+
if (result.ok === true) {
|
|
226
|
+
writeOrientationState('landscape')
|
|
227
|
+
log('restore orientation (' + reason + '): landscape ok')
|
|
228
|
+
} else {
|
|
229
|
+
log('restore orientation (' + reason + ') failed: ' + (result.detail ?? 'unknown'))
|
|
230
|
+
}
|
|
231
|
+
return { ok: result.ok === true, restored: result.ok === true }
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const FAST_COMMANDS = new Set(['ping', 'version', 'shutdown', 'rotate', 'restore'])
|
|
235
|
+
|
|
165
236
|
async function handle(request) {
|
|
166
237
|
const cmd = String(request.cmd ?? '')
|
|
167
238
|
if (cmd === 'ping') return { ok: true, pong: true }
|
|
168
239
|
if (cmd === 'version') {
|
|
169
|
-
return { ok: true, version: '
|
|
240
|
+
return { ok: true, version: '3', platform: process.platform, pid: process.pid, pipe: NAME }
|
|
170
241
|
}
|
|
171
242
|
if (cmd === 'shutdown') {
|
|
172
243
|
setTimeout(() => process.exit(0), 50)
|
|
@@ -174,12 +245,17 @@ async function handle(request) {
|
|
|
174
245
|
}
|
|
175
246
|
if (cmd === 'rotate') {
|
|
176
247
|
const mode = request.mode === 'landscape' ? 'landscape' : 'portrait'
|
|
177
|
-
|
|
248
|
+
const result = await rotatePlatform(mode)
|
|
249
|
+
if (result.ok === true) writeOrientationState(mode)
|
|
250
|
+
return result
|
|
251
|
+
}
|
|
252
|
+
if (cmd === 'restore') {
|
|
253
|
+
return restoreOrientation('explicit')
|
|
178
254
|
}
|
|
179
255
|
// 其余窗口操作:Windows 交给工作进程
|
|
180
256
|
if (!isWindows) return { ok: false, error: '窗口操作仅支持 Windows' }
|
|
181
257
|
const { id: _ignoredId, token: _ignoredToken, ...payload } = request
|
|
182
|
-
return workerCall(payload,
|
|
258
|
+
return workerCall(payload, 15_000)
|
|
183
259
|
}
|
|
184
260
|
|
|
185
261
|
const server = net.createServer((socket) => {
|
|
@@ -203,15 +279,22 @@ const server = net.createServer((socket) => {
|
|
|
203
279
|
continue
|
|
204
280
|
}
|
|
205
281
|
const id = request.id
|
|
206
|
-
|
|
282
|
+
touchInactivity()
|
|
283
|
+
const runRequest = async () => {
|
|
207
284
|
let result
|
|
208
285
|
try {
|
|
209
286
|
result = await handle(request)
|
|
210
287
|
} catch (error) {
|
|
211
288
|
result = { ok: false, error: String(error?.message ?? error) }
|
|
212
289
|
}
|
|
213
|
-
try { socket.write(JSON.stringify({
|
|
214
|
-
}
|
|
290
|
+
try { socket.write(JSON.stringify({ ...result, id }) + '\n') } catch { /* 已断开 */ }
|
|
291
|
+
}
|
|
292
|
+
if (FAST_COMMANDS.has(String(request.cmd ?? ''))) {
|
|
293
|
+
// 转屏/恢复/探活:不进入窗口操作串行队列
|
|
294
|
+
void runRequest()
|
|
295
|
+
} else {
|
|
296
|
+
queue = queue.then(runRequest)
|
|
297
|
+
}
|
|
215
298
|
}
|
|
216
299
|
})
|
|
217
300
|
socket.on('error', () => { /* 忽略 */ })
|
|
@@ -232,37 +315,35 @@ function start() {
|
|
|
232
315
|
})
|
|
233
316
|
}
|
|
234
317
|
|
|
235
|
-
//
|
|
236
|
-
|
|
237
|
-
let
|
|
318
|
+
// 空闲恢复:超过 IDLE_SECONDS 没有任何请求(VNC 不再使用 / DSH 已退出)时,
|
|
319
|
+
// 如果竖屏是本守护进程切的,自动恢复横屏,然后退出。
|
|
320
|
+
let inactivityTimer = null
|
|
238
321
|
|
|
239
|
-
function
|
|
240
|
-
if (
|
|
241
|
-
|
|
242
|
-
|
|
322
|
+
function touchInactivity() {
|
|
323
|
+
if (inactivityTimer !== null) clearTimeout(inactivityTimer)
|
|
324
|
+
inactivityTimer = setTimeout(async () => {
|
|
325
|
+
inactivityTimer = null
|
|
326
|
+
try {
|
|
327
|
+
await restoreOrientation('idle ' + IDLE_SECONDS + 's')
|
|
328
|
+
} catch (error) {
|
|
329
|
+
log('restore on idle failed: ' + String(error?.message ?? error))
|
|
330
|
+
}
|
|
243
331
|
log('idle exit')
|
|
244
|
-
try {
|
|
332
|
+
try { opsWorker.kill() } catch { /* 忽略 */ }
|
|
333
|
+
try { rotateWorker.kill() } catch { /* 忽略 */ }
|
|
245
334
|
try { server.close() } catch { /* 忽略 */ }
|
|
246
335
|
process.exit(0)
|
|
247
336
|
}, IDLE_SECONDS * 1000)
|
|
248
|
-
|
|
337
|
+
inactivityTimer.unref?.()
|
|
249
338
|
}
|
|
250
339
|
|
|
251
|
-
server.on('connection', (
|
|
252
|
-
clients += 1
|
|
253
|
-
if (idleTimer !== null) {
|
|
254
|
-
clearTimeout(idleTimer)
|
|
255
|
-
idleTimer = null
|
|
256
|
-
}
|
|
257
|
-
socket.on('close', () => {
|
|
258
|
-
clients -= 1
|
|
259
|
-
armIdle()
|
|
260
|
-
})
|
|
261
|
-
})
|
|
340
|
+
server.on('connection', () => { /* 连接本身不重置空闲计时,只有请求算活动 */ })
|
|
262
341
|
|
|
263
342
|
process.on('exit', () => {
|
|
264
|
-
try {
|
|
343
|
+
try { opsWorker.kill() } catch { /* 忽略 */ }
|
|
344
|
+
try { rotateWorker.kill() } catch { /* 忽略 */ }
|
|
265
345
|
removeStaleSocket(SOCKET)
|
|
266
346
|
})
|
|
267
347
|
|
|
268
348
|
start()
|
|
349
|
+
touchInactivity()
|
package/index.js
CHANGED
|
@@ -4617,6 +4617,10 @@ export function apply(ctx, rawConfig) {
|
|
|
4617
4617
|
}
|
|
4618
4618
|
|
|
4619
4619
|
return () => {
|
|
4620
|
+
// DSH 退出:主动让转屏守护进程恢复横屏(硬退出则由守护进程空闲计时兜底)
|
|
4621
|
+
Promise.resolve()
|
|
4622
|
+
.then(() => windowRemote.restoreOrientation(6_000))
|
|
4623
|
+
.catch(() => {})
|
|
4620
4624
|
if (syncTimer) clearInterval(syncTimer);
|
|
4621
4625
|
if (reloadTimer) clearTimeout(reloadTimer);
|
|
4622
4626
|
try { watcher?.close(); } catch { /* ignore */ }
|
package/lib/orientation.mjs
CHANGED
|
@@ -80,14 +80,20 @@ async function rotateMac(mode) {
|
|
|
80
80
|
}
|
|
81
81
|
|
|
82
82
|
async function rotateWindows(mode) {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
83
|
+
// 转屏统一交给 Node 转屏守护进程(窗口代理守护进程)执行:
|
|
84
|
+
// 守护进程内有独立的转屏工作进程,不会被窗口列表/截图等请求阻塞;
|
|
85
|
+
// 它还会在长时间无活动或 DSH 退出后自动恢复横屏。
|
|
86
|
+
const { rotateScreen } = await import('./window-remote.mjs')
|
|
87
|
+
const result = await rotateScreen(mode, 20_000)
|
|
88
|
+
const screen = result.screen ?? {
|
|
89
|
+
width: Number(result.screenWidth) || 0,
|
|
90
|
+
height: Number(result.screenHeight) || 0,
|
|
91
|
+
}
|
|
86
92
|
return {
|
|
87
93
|
ok: result.ok === true && result.result === 0,
|
|
88
94
|
platform: 'win32',
|
|
89
|
-
detail: `result=${result.result ?? '?'} screen=${
|
|
90
|
-
screen
|
|
95
|
+
detail: `agent result=${result.result ?? '?'} screen=${screen.width}x${screen.height}`,
|
|
96
|
+
screen,
|
|
91
97
|
}
|
|
92
98
|
}
|
|
93
99
|
|
package/lib/vendor/vnc.bundle.js
CHANGED
|
@@ -14374,8 +14374,10 @@ async function fetchWindows() {
|
|
|
14374
14374
|
}
|
|
14375
14375
|
return data.windows || [];
|
|
14376
14376
|
}
|
|
14377
|
+
var pollPausedUntil = 0;
|
|
14377
14378
|
async function pollWindows() {
|
|
14378
14379
|
if (!connected) return;
|
|
14380
|
+
if (Date.now() < pollPausedUntil) return;
|
|
14379
14381
|
try {
|
|
14380
14382
|
const windows = await fetchWindows();
|
|
14381
14383
|
const ids = new Set(windows.map((w) => w.hwnd));
|
|
@@ -14402,6 +14404,7 @@ async function pollWindows() {
|
|
|
14402
14404
|
if (Date.now() - lastClickAt > 5e3) pendingForeground = null;
|
|
14403
14405
|
knownWindows = ids;
|
|
14404
14406
|
} catch {
|
|
14407
|
+
pollPausedUntil = Date.now() + 5e3;
|
|
14405
14408
|
}
|
|
14406
14409
|
}
|
|
14407
14410
|
async function waitForeground(hwnd, timeout = 3e3) {
|
package/lib/vnc-app.js
CHANGED
|
@@ -255,8 +255,11 @@ function refreshWindowView(windows) {
|
|
|
255
255
|
if (changed) focusWindowRect(match)
|
|
256
256
|
}
|
|
257
257
|
|
|
258
|
+
let pollPausedUntil = 0
|
|
259
|
+
|
|
258
260
|
async function pollWindows() {
|
|
259
261
|
if (!connected) return
|
|
262
|
+
if (Date.now() < pollPausedUntil) return
|
|
260
263
|
try {
|
|
261
264
|
const windows = await fetchWindows()
|
|
262
265
|
const ids = new Set(windows.map((w) => w.hwnd))
|
|
@@ -285,7 +288,10 @@ async function pollWindows() {
|
|
|
285
288
|
if (Date.now() - lastClickAt > 5000) pendingForeground = null
|
|
286
289
|
|
|
287
290
|
knownWindows = ids
|
|
288
|
-
} catch {
|
|
291
|
+
} catch {
|
|
292
|
+
// 窗口代理卡住/超时:暂停轮询 5 秒,别把请求链继续堆满
|
|
293
|
+
pollPausedUntil = Date.now() + 5000
|
|
294
|
+
}
|
|
289
295
|
}
|
|
290
296
|
|
|
291
297
|
/** 等窗口真正成为前台,最多 timeout 毫秒 */
|
package/lib/vnc-boot.js
CHANGED
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
# Window sharing agent: line-delimited JSON over stdin/stdout.
|
|
2
|
+
#
|
|
3
|
+
# Request: {"id":"1","cmd":"list"}
|
|
4
|
+
# {"id":"2","cmd":"capture","hwnd":"12345","maxWidth":1280}
|
|
5
|
+
# {"id":"3","cmd":"click","hwnd":"12345","x":100,"y":50,"button":"left"}
|
|
6
|
+
# {"id":"4","cmd":"wheel","hwnd":"12345","delta":-120}
|
|
7
|
+
# {"id":"5","cmd":"key","hwnd":"12345","text":"hello"} or {"keys":["enter","tab"]}
|
|
8
|
+
#
|
|
9
|
+
# Response: {"id":"1","ok":true,"windows":[...]}
|
|
10
|
+
# {"id":"2","ok":true,"width":W,"height":H,"data":"<base64 jpeg>"}
|
|
11
|
+
#
|
|
12
|
+
# ASCII only on purpose: Windows PowerShell 5.1 reads scripts as ANSI,
|
|
13
|
+
# so non-ASCII comments would break parsing without a BOM.
|
|
14
|
+
param(
|
|
15
|
+
[string]$PipeName = '',
|
|
16
|
+
[int]$IdleSeconds = 600
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
$ErrorActionPreference = 'Stop'
|
|
20
|
+
# Force UTF-8 on both pipes so JSON (titles, text input) survives GBK default
|
|
21
|
+
[Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false)
|
|
22
|
+
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
|
|
23
|
+
$OutputEncoding = [System.Text.UTF8Encoding]::new($false)
|
|
24
|
+
Add-Type -AssemblyName System.Drawing
|
|
25
|
+
Add-Type @"
|
|
26
|
+
using System;
|
|
27
|
+
using System.Text;
|
|
28
|
+
using System.Runtime.InteropServices;
|
|
29
|
+
public class W32 {
|
|
30
|
+
public delegate bool EnumProc(IntPtr h, IntPtr p);
|
|
31
|
+
[DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc cb, IntPtr p);
|
|
32
|
+
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
|
|
33
|
+
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowTextW(IntPtr h, StringBuilder s, int n);
|
|
34
|
+
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr SendMessageTimeoutW(IntPtr h, uint msg, IntPtr w, StringBuilder l, uint flags, uint timeout, out IntPtr result);
|
|
35
|
+
public static string SafeWindowText(IntPtr h, int n) {
|
|
36
|
+
StringBuilder sb = new StringBuilder(n); IntPtr res;
|
|
37
|
+
SendMessageTimeoutW(h, 0x000D, (IntPtr)n, sb, 0x0002, 100, out res);
|
|
38
|
+
return sb.ToString();
|
|
39
|
+
}
|
|
40
|
+
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetClassNameW(IntPtr h, StringBuilder s, int n);
|
|
41
|
+
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
|
|
42
|
+
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr h, out RECT r);
|
|
43
|
+
[DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr h, ref POINT p);
|
|
44
|
+
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr h, IntPtr hdc, uint flags);
|
|
45
|
+
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
|
|
46
|
+
[DllImport("user32.dll")] public static extern int GetSystemMetrics(int index);
|
|
47
|
+
[DllImport("user32.dll")] public static extern bool IsZoomed(IntPtr h);
|
|
48
|
+
[DllImport("user32.dll")] public static extern bool SwitchToThisWindow(IntPtr h, bool alt);
|
|
49
|
+
[DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr h);
|
|
50
|
+
[DllImport("user32.dll")] public static extern bool AttachThreadInput(int from, int to, bool attach);
|
|
51
|
+
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
|
52
|
+
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int cmd);
|
|
53
|
+
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
|
|
54
|
+
[DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
|
|
55
|
+
[DllImport("user32.dll")] public static extern void mouse_event(uint flags, int dx, int dy, int data, UIntPtr extra);
|
|
56
|
+
[DllImport("user32.dll")] public static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
|
|
57
|
+
[DllImport("user32.dll")] public static extern bool PostMessageW(IntPtr h, uint msg, IntPtr w, IntPtr l);
|
|
58
|
+
[DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
|
|
59
|
+
[StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
|
|
60
|
+
[StructLayout(LayoutKind.Explicit, Size = 40)] public struct INPUT { [FieldOffset(0)] public uint type; [FieldOffset(8)] public KEYBDINPUT ki; }
|
|
61
|
+
[DllImport("user32.dll", SetLastError = true)] public static extern uint SendInput(uint n, INPUT[] p, int cb);
|
|
62
|
+
public static bool SendUnicode(string text) {
|
|
63
|
+
if (string.IsNullOrEmpty(text)) { return true; }
|
|
64
|
+
INPUT[] inputs = new INPUT[text.Length * 2];
|
|
65
|
+
for (int i = 0; i < text.Length; i++) {
|
|
66
|
+
inputs[i * 2].type = 1; inputs[i * 2].ki.wScan = (ushort)text[i]; inputs[i * 2].ki.dwFlags = 0x0004;
|
|
67
|
+
inputs[i * 2 + 1].type = 1; inputs[i * 2 + 1].ki.wScan = (ushort)text[i]; inputs[i * 2 + 1].ki.dwFlags = 0x0004 | 0x0002;
|
|
68
|
+
}
|
|
69
|
+
return SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT))) == (uint)inputs.Length;
|
|
70
|
+
}
|
|
71
|
+
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
|
|
72
|
+
[StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }
|
|
73
|
+
}
|
|
74
|
+
"@
|
|
75
|
+
|
|
76
|
+
$MouseLeftDown = 0x0002
|
|
77
|
+
$MouseLeftUp = 0x0004
|
|
78
|
+
$MouseRightDown = 0x0008
|
|
79
|
+
$MouseRightUp = 0x0010
|
|
80
|
+
$MouseWheel = 0x0800
|
|
81
|
+
$KeyUp = 0x0002
|
|
82
|
+
|
|
83
|
+
function Get-Windows {
|
|
84
|
+
$list = New-Object System.Collections.ArrayList
|
|
85
|
+
$cb = [W32+EnumProc]{
|
|
86
|
+
param($h, $p)
|
|
87
|
+
try {
|
|
88
|
+
if ([W32]::IsWindowVisible($h)) {
|
|
89
|
+
$title = [W32]::SafeWindowText($h, 512).Trim()
|
|
90
|
+
if ($title.Length -gt 0) {
|
|
91
|
+
$r = New-Object W32+RECT
|
|
92
|
+
[void][W32]::GetWindowRect($h, [ref]$r)
|
|
93
|
+
$w = $r.Right - $r.Left
|
|
94
|
+
$hh = $r.Bottom - $r.Top
|
|
95
|
+
if ($w -gt 120 -and $hh -gt 60) {
|
|
96
|
+
$cls = New-Object System.Text.StringBuilder 256
|
|
97
|
+
[void][W32]::GetClassNameW($h, $cls, 256)
|
|
98
|
+
$procId = 0
|
|
99
|
+
[void][W32]::GetWindowThreadProcessId($h, [ref]$procId)
|
|
100
|
+
$procName = ''
|
|
101
|
+
try { $procName = (Get-Process -Id $procId -ErrorAction SilentlyContinue).ProcessName } catch { $procName = '' }
|
|
102
|
+
[void]$list.Add([pscustomobject]@{
|
|
103
|
+
hwnd = $h.ToInt64().ToString()
|
|
104
|
+
title = $title
|
|
105
|
+
className = $cls.ToString()
|
|
106
|
+
x = $r.Left
|
|
107
|
+
y = $r.Top
|
|
108
|
+
width = $w
|
|
109
|
+
height = $hh
|
|
110
|
+
pid = $procId
|
|
111
|
+
process = $procName
|
|
112
|
+
foreground = ([W32]::GetForegroundWindow() -eq $h)
|
|
113
|
+
})
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
} catch { }
|
|
118
|
+
return $true
|
|
119
|
+
}
|
|
120
|
+
[void][W32]::EnumWindows($cb, [IntPtr]::Zero)
|
|
121
|
+
return @($list)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function Set-Orientation([string]$mode) {
|
|
125
|
+
$angle = if ($mode -eq 'portrait') { 270 } else { 0 }
|
|
126
|
+
if (-not ('RotHelper' -as [type])) {
|
|
127
|
+
Add-Type @"
|
|
128
|
+
using System; using System.Runtime.InteropServices;
|
|
129
|
+
public static class RotHelper {
|
|
130
|
+
const int EC=-1; const uint O=0x80,W=0x80000,H=0x100000,REG=1,TEST=2,AT=1,PR=4;
|
|
131
|
+
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct DD { public int cb;
|
|
132
|
+
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string dn;
|
|
133
|
+
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string ds;
|
|
134
|
+
public uint sf;
|
|
135
|
+
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string di;
|
|
136
|
+
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string dk; }
|
|
137
|
+
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct DM {
|
|
138
|
+
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string n;
|
|
139
|
+
public ushort a,b,c,d; public uint f; public int px,py; public uint o,fo;
|
|
140
|
+
public short cc,dd,yy,tt,co;
|
|
141
|
+
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string fn;
|
|
142
|
+
public ushort lp; public uint bpp,w,h,fl,fr,icm,icmi,mt,dt,r1,r2,pw,ph; }
|
|
143
|
+
[DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern bool EnumDisplayDevices(string d, uint i, ref DD dd, uint f);
|
|
144
|
+
[DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern bool EnumDisplaySettings(string d, int m, ref DM dm);
|
|
145
|
+
[DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern int ChangeDisplaySettingsEx(string d, ref DM dm, IntPtr h, uint f, IntPtr l);
|
|
146
|
+
public static string Primary() { for (uint i=0;i<64;i++){ DD dd=new DD(); dd.cb=Marshal.SizeOf(typeof(DD));
|
|
147
|
+
if(!EnumDisplayDevices(null,i,ref dd,0)) break; if((dd.sf&AT)==0) continue; if((dd.sf&PR)!=0) return dd.dn; } return null; }
|
|
148
|
+
public static int Rotate(string dev,int angle){ DM m=new DM(); m.c=(ushort)Marshal.SizeOf(typeof(DM));
|
|
149
|
+
if(!EnumDisplaySettings(dev,EC,ref m)) return -100; int oo=(int)m.o, no=angle/90;
|
|
150
|
+
bool op=oo==1||oo==3, np=no==1||no==3; if(op!=np){uint t=m.w;m.w=m.h;m.h=t;}
|
|
151
|
+
m.o=(uint)no; m.f=O|W|H;
|
|
152
|
+
int t1=ChangeDisplaySettingsEx(dev,ref m,IntPtr.Zero,TEST,IntPtr.Zero); if(t1!=0) return t1*100;
|
|
153
|
+
return ChangeDisplaySettingsEx(dev,ref m,IntPtr.Zero,REG,IntPtr.Zero); }
|
|
154
|
+
}
|
|
155
|
+
"@
|
|
156
|
+
}
|
|
157
|
+
$dev = [RotHelper]::Primary()
|
|
158
|
+
if (-not $dev) { return -101 }
|
|
159
|
+
return [RotHelper]::Rotate($dev, $angle)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function Set-Foreground([IntPtr]$hwnd) {
|
|
163
|
+
[void][W32]::ShowWindow($hwnd, 9)
|
|
164
|
+
[W32]::keybd_event(0x12, 0, 0, [UIntPtr]::Zero)
|
|
165
|
+
[W32]::keybd_event(0x12, 0, 2, [UIntPtr]::Zero)
|
|
166
|
+
$fgPid = 0
|
|
167
|
+
$targetPid = 0
|
|
168
|
+
$fgThread = [W32]::GetWindowThreadProcessId([W32]::GetForegroundWindow(), [ref]$fgPid)
|
|
169
|
+
$targetThread = [W32]::GetWindowThreadProcessId($hwnd, [ref]$targetPid)
|
|
170
|
+
if ($fgThread -ne 0 -and $targetThread -ne 0 -and $fgThread -ne $targetThread) {
|
|
171
|
+
[void][W32]::AttachThreadInput($fgThread, $targetThread, $true)
|
|
172
|
+
[void][W32]::BringWindowToTop($hwnd)
|
|
173
|
+
[void][W32]::SetForegroundWindow($hwnd)
|
|
174
|
+
[void][W32]::AttachThreadInput($fgThread, $targetThread, $false)
|
|
175
|
+
} else {
|
|
176
|
+
[void][W32]::BringWindowToTop($hwnd)
|
|
177
|
+
[void][W32]::SetForegroundWindow($hwnd)
|
|
178
|
+
}
|
|
179
|
+
if ([W32]::GetForegroundWindow() -ne $hwnd -and $targetPid -gt 0) {
|
|
180
|
+
try { Add-Type -AssemblyName Microsoft.VisualBasic; [Microsoft.VisualBasic.Interaction]::AppActivate($targetPid) } catch { }
|
|
181
|
+
}
|
|
182
|
+
if ([W32]::GetForegroundWindow() -ne $hwnd) { [void][W32]::SwitchToThisWindow($hwnd, $true) }
|
|
183
|
+
for ($i = 0; $i -lt 10; $i += 1) {
|
|
184
|
+
if ([W32]::GetForegroundWindow() -eq $hwnd) { return $true }
|
|
185
|
+
Start-Sleep -Milliseconds 100
|
|
186
|
+
}
|
|
187
|
+
return $false
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function Get-Hwnd([string]$value) {
|
|
191
|
+
return [IntPtr][Int64]::Parse($value)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function Capture-Window([IntPtr]$hwnd, [int]$maxWidth) {
|
|
195
|
+
$r = New-Object W32+RECT
|
|
196
|
+
if (-not [W32]::GetWindowRect($hwnd, [ref]$r)) { throw 'window not found' }
|
|
197
|
+
$w = $r.Right - $r.Left
|
|
198
|
+
$h = $r.Bottom - $r.Top
|
|
199
|
+
if ($w -le 0 -or $h -le 0) { throw 'invalid window size' }
|
|
200
|
+
$bmp = New-Object System.Drawing.Bitmap $w, $h
|
|
201
|
+
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
|
202
|
+
$hdc = $g.GetHdc()
|
|
203
|
+
try {
|
|
204
|
+
# 2 = PW_RENDERFULLCONTENT: capture DWM-composed content
|
|
205
|
+
$ok = [W32]::PrintWindow($hwnd, $hdc, 2)
|
|
206
|
+
} finally {
|
|
207
|
+
$g.ReleaseHdc($hdc)
|
|
208
|
+
$g.Dispose()
|
|
209
|
+
}
|
|
210
|
+
if (-not $ok) { $bmp.Dispose(); throw 'capture failed' }
|
|
211
|
+
if ($maxWidth -gt 0 -and $w -gt $maxWidth) {
|
|
212
|
+
$scale = $maxWidth / $w
|
|
213
|
+
$nw = [int]$maxWidth
|
|
214
|
+
$nh = [int]($h * $scale)
|
|
215
|
+
$small = New-Object System.Drawing.Bitmap $nw, $nh
|
|
216
|
+
$g2 = [System.Drawing.Graphics]::FromImage($small)
|
|
217
|
+
$g2.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
|
|
218
|
+
$g2.DrawImage($bmp, 0, 0, $nw, $nh)
|
|
219
|
+
$g2.Dispose()
|
|
220
|
+
$bmp.Dispose()
|
|
221
|
+
$bmp = $small
|
|
222
|
+
}
|
|
223
|
+
$outW = $bmp.Width
|
|
224
|
+
$outH = $bmp.Height
|
|
225
|
+
$ms = New-Object System.IO.MemoryStream
|
|
226
|
+
$codec = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.MimeType -eq 'image/jpeg' }
|
|
227
|
+
$encoderParams = New-Object System.Drawing.Imaging.EncoderParameters 1
|
|
228
|
+
$encoderParams.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality), 70L
|
|
229
|
+
$bmp.Save($ms, $codec, $encoderParams)
|
|
230
|
+
$bmp.Dispose()
|
|
231
|
+
$bytes = $ms.ToArray()
|
|
232
|
+
$ms.Dispose()
|
|
233
|
+
return @{ width = $outW; height = $outH; data = [Convert]::ToBase64String($bytes) }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function Client-Point([IntPtr]$hwnd, [int]$x, [int]$y) {
|
|
237
|
+
$pt = New-Object W32+POINT
|
|
238
|
+
$pt.X = $x
|
|
239
|
+
$pt.Y = $y
|
|
240
|
+
[void][W32]::ClientToScreen($hwnd, [ref]$pt)
|
|
241
|
+
return $pt
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
$KEYMAP = @{
|
|
245
|
+
enter = 0x0D; tab = 0x09; esc = 0x1B; backspace = 0x08; delete = 0x2E
|
|
246
|
+
up = 0x26; down = 0x28; left = 0x25; right = 0x27
|
|
247
|
+
ctrl = 0x11; alt = 0x12; shift = 0x10; win = 0x5B
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
[void][W32]::SetProcessDPIAware()
|
|
251
|
+
|
|
252
|
+
function Invoke-AgentLine([string]$line) {
|
|
253
|
+
$response = @{ ok = $false }
|
|
254
|
+
try {
|
|
255
|
+
$req = $line | ConvertFrom-Json
|
|
256
|
+
$expected = [string]$env:DSH_AGENT_TOKEN
|
|
257
|
+
if ($expected -ne '' -and [string]$req.token -ne $expected) { throw 'unauthorized' }
|
|
258
|
+
$response.id = $req.id
|
|
259
|
+
switch ($req.cmd) {
|
|
260
|
+
'list' {
|
|
261
|
+
$response.ok = $true
|
|
262
|
+
$response.windows = @(Get-Windows)
|
|
263
|
+
$response.screenWidth = [W32]::GetSystemMetrics(0)
|
|
264
|
+
$response.screenHeight = [W32]::GetSystemMetrics(1)
|
|
265
|
+
}
|
|
266
|
+
'capture' {
|
|
267
|
+
$hwnd = Get-Hwnd $req.hwnd
|
|
268
|
+
$shot = Capture-Window $hwnd ([int]($req.maxWidth))
|
|
269
|
+
$response.ok = $true
|
|
270
|
+
$response.width = $shot.width
|
|
271
|
+
$response.height = $shot.height
|
|
272
|
+
$response.data = $shot.data
|
|
273
|
+
}
|
|
274
|
+
'open' {
|
|
275
|
+
if (-not $req.path) { throw 'missing path' }
|
|
276
|
+
if (-not (Test-Path -LiteralPath $req.path)) { throw 'file not found' }
|
|
277
|
+
$proc = Start-Process -FilePath $req.path -PassThru
|
|
278
|
+
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($req.path)
|
|
279
|
+
# 等窗口出现,然后恢复并置前(否则会藏在其它窗口后面)
|
|
280
|
+
$target = [IntPtr]::Zero
|
|
281
|
+
for ($i = 0; $i -lt 24; $i += 1) {
|
|
282
|
+
Start-Sleep -Milliseconds 250
|
|
283
|
+
if ($null -ne $proc) { $proc.Refresh() }
|
|
284
|
+
if ($null -ne $proc -and $proc.MainWindowHandle -ne [IntPtr]::Zero) { $target = $proc.MainWindowHandle; break }
|
|
285
|
+
$found = Get-Windows | Where-Object { $_.pid -eq $proc.Id } | Select-Object -First 1
|
|
286
|
+
if ($null -ne $found) { $target = Get-Hwnd $found.hwnd; break }
|
|
287
|
+
if ($baseName.Length -gt 0) {
|
|
288
|
+
$found = Get-Windows | Where-Object { $_.title -like "*$baseName*" } | Select-Object -First 1
|
|
289
|
+
if ($null -ne $found) { $target = Get-Hwnd $found.hwnd; break }
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if ($null -ne $target -and $target -ne [IntPtr]::Zero) {
|
|
293
|
+
[void][W32]::ShowWindow($target, 9)
|
|
294
|
+
[void](Set-Foreground $target)
|
|
295
|
+
}
|
|
296
|
+
$response.ok = $true
|
|
297
|
+
$response.path = $req.path
|
|
298
|
+
$response.pid = if ($null -ne $proc) { $proc.Id } else { 0 }
|
|
299
|
+
$response.hwnd = if ($null -ne $target -and $target -ne [IntPtr]::Zero) { $target.ToInt64().ToString() } else { '' }
|
|
300
|
+
}
|
|
301
|
+
'close' {
|
|
302
|
+
$hwnd = if ($req.hwnd) { Get-Hwnd $req.hwnd } else { [W32]::GetForegroundWindow() }
|
|
303
|
+
[void][W32]::PostMessageW($hwnd, 0x0010, [IntPtr]::Zero, [IntPtr]::Zero)
|
|
304
|
+
$response.ok = $true
|
|
305
|
+
$response.hwnd = $hwnd.ToInt64().ToString()
|
|
306
|
+
}
|
|
307
|
+
'kill' {
|
|
308
|
+
$hwnd = Get-Hwnd $req.hwnd
|
|
309
|
+
$procId = 0
|
|
310
|
+
[void][W32]::GetWindowThreadProcessId($hwnd, [ref]$procId)
|
|
311
|
+
if ($procId -le 0) { throw 'cannot resolve pid' }
|
|
312
|
+
$procName = ''
|
|
313
|
+
try { $procName = (Get-Process -Id $procId -ErrorAction Stop).ProcessName } catch { throw 'process not found' }
|
|
314
|
+
$blocked = @('system','idle','registry','smss','csrss','wininit','winlogon','services','lsass','svchost','dwm','explorer','fontdrvhost','spoolsv','audiodg','sihost','ctfmon','deepseek harness','searchhost','startmenuexperiencehost')
|
|
315
|
+
if ($blocked -contains $procName.ToLower()) { throw "protected process: $procName" }
|
|
316
|
+
Stop-Process -Id $procId -Force -ErrorAction Stop
|
|
317
|
+
$response.ok = $true
|
|
318
|
+
$response.pid = $procId
|
|
319
|
+
}
|
|
320
|
+
'focus' {
|
|
321
|
+
$hwnd = Get-Hwnd $req.hwnd
|
|
322
|
+
$response.ok = Set-Foreground $hwnd
|
|
323
|
+
$response.hwnd = $hwnd.ToInt64().ToString()
|
|
324
|
+
}
|
|
325
|
+
'rotate' {
|
|
326
|
+
$result = Set-Orientation ([string]$req.mode)
|
|
327
|
+
$response.ok = ($result -eq 0)
|
|
328
|
+
$response.result = $result
|
|
329
|
+
$response.screenWidth = [W32]::GetSystemMetrics(0)
|
|
330
|
+
$response.screenHeight = [W32]::GetSystemMetrics(1)
|
|
331
|
+
}
|
|
332
|
+
'cursor' {
|
|
333
|
+
Add-Type -AssemblyName System.Windows.Forms
|
|
334
|
+
$pt = [System.Windows.Forms.Cursor]::Position
|
|
335
|
+
$response.ok = $true
|
|
336
|
+
$response.x = $pt.X
|
|
337
|
+
$response.y = $pt.Y
|
|
338
|
+
}
|
|
339
|
+
'click' {
|
|
340
|
+
$hwnd = Get-Hwnd $req.hwnd
|
|
341
|
+
[void][W32]::SetForegroundWindow($hwnd)
|
|
342
|
+
$pt = Client-Point $hwnd ([int]$req.x) ([int]$req.y)
|
|
343
|
+
[void][W32]::SetCursorPos($pt.X, $pt.Y)
|
|
344
|
+
$btn = [string]$req.button
|
|
345
|
+
if ($btn -eq 'right') {
|
|
346
|
+
[W32]::mouse_event($MouseRightDown, 0, 0, 0, [UIntPtr]::Zero)
|
|
347
|
+
[W32]::mouse_event($MouseRightUp, 0, 0, 0, [UIntPtr]::Zero)
|
|
348
|
+
} else {
|
|
349
|
+
[W32]::mouse_event($MouseLeftDown, 0, 0, 0, [UIntPtr]::Zero)
|
|
350
|
+
[W32]::mouse_event($MouseLeftUp, 0, 0, 0, [UIntPtr]::Zero)
|
|
351
|
+
}
|
|
352
|
+
$response.ok = $true
|
|
353
|
+
}
|
|
354
|
+
'wheel' {
|
|
355
|
+
$hwnd = Get-Hwnd $req.hwnd
|
|
356
|
+
[void][W32]::SetForegroundWindow($hwnd)
|
|
357
|
+
[W32]::mouse_event($MouseWheel, 0, 0, [int]$req.delta, [UIntPtr]::Zero)
|
|
358
|
+
$response.ok = $true
|
|
359
|
+
}
|
|
360
|
+
'key' {
|
|
361
|
+
$hwnd = Get-Hwnd $req.hwnd
|
|
362
|
+
[void][W32]::SetForegroundWindow($hwnd)
|
|
363
|
+
if ($req.text) { [void][W32]::SendUnicode([string]$req.text) }
|
|
364
|
+
if ($req.keys) {
|
|
365
|
+
foreach ($name in @($req.keys)) {
|
|
366
|
+
$vk = $KEYMAP[[string]$name]
|
|
367
|
+
if ($null -ne $vk) {
|
|
368
|
+
[W32]::keybd_event([byte]$vk, 0, 0, [UIntPtr]::Zero)
|
|
369
|
+
[W32]::keybd_event([byte]$vk, 0, $KeyUp, [UIntPtr]::Zero)
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
$response.ok = $true
|
|
374
|
+
}
|
|
375
|
+
default {
|
|
376
|
+
$response.error = "unknown command: $($req.cmd)"
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
} catch {
|
|
380
|
+
$response.ok = $false
|
|
381
|
+
$response.error = $_.Exception.Message
|
|
382
|
+
}
|
|
383
|
+
return ($response | ConvertTo-Json -Compress -Depth 5)
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function Write-AgentLog([string]$message) {
|
|
387
|
+
try {
|
|
388
|
+
$dir = Join-Path $env:LOCALAPPDATA 'dsh-homing'
|
|
389
|
+
if (-not (Test-Path -LiteralPath $dir)) { [void](New-Item -ItemType Directory -Path $dir -Force) }
|
|
390
|
+
$file = Join-Path $dir 'window-agent.log'
|
|
391
|
+
# 简单轮转:超过 2MB 就改名为 .1(只保留一个备份)
|
|
392
|
+
if ((Test-Path -LiteralPath $file) -and ((Get-Item -LiteralPath $file).Length -gt 2MB)) {
|
|
393
|
+
$backup = Join-Path $dir 'window-agent.log.1'
|
|
394
|
+
if (Test-Path -LiteralPath $backup) { Remove-Item -LiteralPath $backup -Force -ErrorAction SilentlyContinue }
|
|
395
|
+
Move-Item -LiteralPath $file -Destination $backup -Force -ErrorAction SilentlyContinue
|
|
396
|
+
}
|
|
397
|
+
$line = (Get-Date).ToString('s') + ' ' + $message
|
|
398
|
+
Add-Content -LiteralPath $file -Value $line -Encoding UTF8
|
|
399
|
+
} catch { }
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
if ($PipeName -ne '') {
|
|
403
|
+
$stop = $false
|
|
404
|
+
Write-AgentLog ('serve start pipe=' + $PipeName)
|
|
405
|
+
while (-not $stop) {
|
|
406
|
+
$pipe = $null
|
|
407
|
+
try {
|
|
408
|
+
$pipe = New-Object System.IO.Pipes.NamedPipeServerStream($PipeName, [System.IO.Pipes.PipeDirection]::InOut, 1, [System.IO.Pipes.PipeTransmissionMode]::Byte, [System.IO.Pipes.PipeOptions]::Asynchronous)
|
|
409
|
+
} catch {
|
|
410
|
+
Write-AgentLog ('pipe busy: ' + $_.Exception.Message)
|
|
411
|
+
exit 3
|
|
412
|
+
}
|
|
413
|
+
try {
|
|
414
|
+
$task = $pipe.WaitForConnectionAsync()
|
|
415
|
+
if (-not $task.Wait([Math]::Max(1, $IdleSeconds) * 1000)) {
|
|
416
|
+
Write-AgentLog 'idle exit'
|
|
417
|
+
break
|
|
418
|
+
}
|
|
419
|
+
$reader = New-Object System.IO.StreamReader($pipe)
|
|
420
|
+
$writer = New-Object System.IO.StreamWriter($pipe)
|
|
421
|
+
$writer.AutoFlush = $true
|
|
422
|
+
while ($true) {
|
|
423
|
+
$line = $reader.ReadLine()
|
|
424
|
+
if ($null -eq $line) { break }
|
|
425
|
+
if ($line.Trim() -eq '') { continue }
|
|
426
|
+
$out = Invoke-AgentLine $line
|
|
427
|
+
$writer.WriteLine($out)
|
|
428
|
+
try {
|
|
429
|
+
$req = $line | ConvertFrom-Json
|
|
430
|
+
if ($req.cmd -eq 'shutdown' -and [string]$req.token -eq [string]$env:DSH_AGENT_TOKEN) {
|
|
431
|
+
$stop = $true
|
|
432
|
+
break
|
|
433
|
+
}
|
|
434
|
+
} catch { }
|
|
435
|
+
}
|
|
436
|
+
$writer.Dispose()
|
|
437
|
+
$reader.Dispose()
|
|
438
|
+
} catch {
|
|
439
|
+
Write-AgentLog ('client error: ' + $_.Exception.Message)
|
|
440
|
+
} finally {
|
|
441
|
+
if ($null -ne $pipe) { $pipe.Dispose() }
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
Write-AgentLog 'serve stop'
|
|
445
|
+
exit 0
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
while ($true) {
|
|
449
|
+
$line = [Console]::In.ReadLine()
|
|
450
|
+
if ($null -eq $line) { break }
|
|
451
|
+
if ($line.Trim() -eq '') { continue }
|
|
452
|
+
[Console]::Out.WriteLine((Invoke-AgentLine $line))
|
|
453
|
+
[Console]::Out.Flush()
|
|
454
|
+
}
|
package/lib/window-remote.mjs
CHANGED
|
@@ -31,6 +31,7 @@ const TOKEN = loadOrCreateToken()
|
|
|
31
31
|
|
|
32
32
|
let socket = null
|
|
33
33
|
let rl = null
|
|
34
|
+
let socketGeneration = 0
|
|
34
35
|
let seq = 0
|
|
35
36
|
let pending = new Map()
|
|
36
37
|
let chain = Promise.resolve()
|
|
@@ -48,6 +49,8 @@ function fail(error) {
|
|
|
48
49
|
|
|
49
50
|
function attach(stream) {
|
|
50
51
|
socket = stream
|
|
52
|
+
socketGeneration += 1
|
|
53
|
+
const generation = socketGeneration
|
|
51
54
|
rl = readline.createInterface({ input: stream })
|
|
52
55
|
rl.on('line', (line) => {
|
|
53
56
|
const text = line.trim()
|
|
@@ -59,8 +62,9 @@ function attach(stream) {
|
|
|
59
62
|
pending.delete(message.id)
|
|
60
63
|
resolve(message)
|
|
61
64
|
})
|
|
62
|
-
|
|
63
|
-
stream.on('
|
|
65
|
+
// 只处理"当前连接"的关闭;旧连接(超时被销毁后)不能清掉新连接的 pending
|
|
66
|
+
stream.on('close', () => { if (generation === socketGeneration) fail(new Error('窗口代理连接已断开')) })
|
|
67
|
+
stream.on('error', () => { if (generation === socketGeneration) fail(new Error('窗口代理连接错误')) })
|
|
64
68
|
}
|
|
65
69
|
|
|
66
70
|
function connectOnce(timeoutMs = 400) {
|
|
@@ -149,6 +153,10 @@ async function rawCall(request, timeoutMs) {
|
|
|
149
153
|
return new Promise((resolve) => {
|
|
150
154
|
const timer = setTimeout(() => {
|
|
151
155
|
pending.delete(id)
|
|
156
|
+
// 超时说明连接/守护进程可能已卡死:销毁套接字,下一次调用重新拉起
|
|
157
|
+
try { socket?.destroy() } catch { /* 忽略 */ }
|
|
158
|
+
socket = null
|
|
159
|
+
rl = null
|
|
152
160
|
resolve({ id, ok: false, error: 'timeout' })
|
|
153
161
|
}, timeoutMs)
|
|
154
162
|
pending.set(id, (message) => {
|
|
@@ -174,15 +182,22 @@ function call(request, timeoutMs = 15_000) {
|
|
|
174
182
|
return next
|
|
175
183
|
}
|
|
176
184
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
185
|
+
let listInFlight = null
|
|
186
|
+
|
|
187
|
+
/** 窗口列表:并发调用共享同一个请求,避免轮询把请求链塞满 */
|
|
188
|
+
export const listWindows = () => {
|
|
189
|
+
if (listInFlight !== null) return listInFlight
|
|
190
|
+
listInFlight = (async () => {
|
|
191
|
+
const result = await call({ cmd: 'list' }, 8_000)
|
|
192
|
+
return {
|
|
193
|
+
ok: result.ok === true,
|
|
194
|
+
windows: Array.isArray(result.windows) ? result.windows : [],
|
|
195
|
+
screenWidth: Number(result.screenWidth) || 0,
|
|
196
|
+
screenHeight: Number(result.screenHeight) || 0,
|
|
197
|
+
error: result.error ?? null,
|
|
198
|
+
}
|
|
199
|
+
})()
|
|
200
|
+
return listInFlight.finally(() => { listInFlight = null })
|
|
186
201
|
}
|
|
187
202
|
|
|
188
203
|
export const captureWindow = async (hwnd, maxWidth = 1280) => {
|
|
@@ -200,7 +215,8 @@ export const keyWindow = (hwnd, { text = '', keys = [] } = {}) => call({ cmd: 'k
|
|
|
200
215
|
export const focusWindow = (hwnd) => call({ cmd: 'focus', hwnd: String(hwnd) })
|
|
201
216
|
export const closeWindow = (hwnd = '') => call({ cmd: 'close', hwnd: String(hwnd) })
|
|
202
217
|
export const killWindow = (hwnd) => call({ cmd: 'kill', hwnd: String(hwnd) })
|
|
203
|
-
export const rotateScreen = (mode) => call({ cmd: 'rotate', mode: String(mode) },
|
|
218
|
+
export const rotateScreen = (mode, timeoutMs = 20_000) => call({ cmd: 'rotate', mode: String(mode) }, timeoutMs)
|
|
219
|
+
export const restoreOrientation = (timeoutMs = 10_000) => call({ cmd: 'restore' }, timeoutMs)
|
|
204
220
|
export const cursorPos = () => call({ cmd: 'cursor' })
|
|
205
221
|
export const openPath = (filePath) => call({ cmd: 'open', path: String(filePath) }, 20_000)
|
|
206
222
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andy.ian/dsh-homing",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.10",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
|
|
6
6
|
"keywords": [
|
|
@@ -56,7 +56,8 @@
|
|
|
56
56
|
"SECURITY.md",
|
|
57
57
|
"permissions.json",
|
|
58
58
|
"bin/window-agent-daemon.mjs",
|
|
59
|
-
"bin/inbox.mjs"
|
|
59
|
+
"bin/inbox.mjs",
|
|
60
|
+
"lib/*.ps1"
|
|
60
61
|
],
|
|
61
62
|
"publishConfig": {
|
|
62
63
|
"access": "public",
|