dsh-side-window 0.0.0-stage → 0.5.8

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/shell/main.js ADDED
@@ -0,0 +1,923 @@
1
+ /**
2
+ * dsh-shell —— 自写的极简 DSH 外壳(无边框 / 贴右 / 抽屉 / 热键 / 失焦收起)。
3
+ *
4
+ * 启动参数:--url-file[=路径] | --url=<地址> | --width=<像素> | --owner-pid=<宿主 pid>
5
+ * --state-dir=<目录>
6
+ * 状态目录:宿主通过 `--state-dir=` 指定(`$DSH_HOME\side-window\state`);
7
+ * 单独手跑时退回同一个位置(`$DSH_HOME\side-window\state`,DSH_HOME 缺省 `~/.dsh`)。
8
+ * 目录里是 shell.json / shell.url / shell.pid / shell.log / toggle.flag / hotkey.json。
9
+ * { "enabled": true, "width": 460, "autoHideOnBlur": true,
10
+ * "alwaysOnTop": false, "hotkey": "Ctrl+Shift+L" }
11
+ * hotkey.json 是**只读状态**(外壳写给人/设置页看),不是配置。
12
+ *
13
+ * 关于启动:进程起来后窗口**处于收起状态**(建在屏幕外、show:false),屏幕上不出现任何东西、
14
+ * 不抢焦点;按呼出热键(默认 Ctrl+Shift+L)、设置页或桌宠菜单才滑出。配置只读不写,缺字段用内置默认值。
15
+ * 关于置顶:默认**不**置顶。侧栏显示时会拿到焦点,普通窗口在获得焦点时本来就在最前,
16
+ * 所以「绝大部分时候在最上面」成立,同时不会压住别的应用的置顶窗口;需要永远盖住
17
+ * 其它窗口时,用设置页的「窗口置顶」开关(保存后立即生效,见 watchLiveSettings)。
18
+ *
19
+ * 关于生命周期:外壳盯住宿主进程(--owner-pid,没传时用 process.ppid)。DSH 退出后
20
+ * 外壳最多 1 秒自己退出,不会留下一个连不上旧端口的死窗口;下次 DSH 启动由宿主重新拉起。
21
+ */
22
+ const fs = require('node:fs')
23
+ const path = require('node:path')
24
+ const os = require('node:os')
25
+ const { spawn, execFileSync } = require('node:child_process')
26
+ const { app, BrowserWindow, screen, globalShortcut, ipcMain } = require('electron')
27
+
28
+ const dshHome = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
29
+ const dir =
30
+ argValue('state-dir') ||
31
+ path.join(dshHome, 'side-window', 'state')
32
+ const logFile = path.join(dir, 'shell.log')
33
+ const flagFile = path.join(dir, 'toggle.flag')
34
+ const openFile = path.join(dir, 'open.json')
35
+ const urlFile = path.join(dir, 'shell.url')
36
+ const cfgFile = path.join(dir, 'shell.json')
37
+ const hotkeyFile = path.join(dir, 'hotkey.json')
38
+ const pauseFile = path.join(dir, 'hotkey.pause')
39
+ /** 呼出热键的兜底值:shell.json 缺失或没写 hotkey 时用;正常以宿主写入的为准。 */
40
+ const DEFAULT_HOTKEY = 'Ctrl+Shift+L'
41
+ /** 暂停最长多久:设置页崩了/被关掉没来得及恢复时,外壳自己把热键装回去。 */
42
+ const HOTKEY_PAUSE_LIMIT_MS = 120000
43
+
44
+ function log(message) {
45
+ try {
46
+ fs.mkdirSync(dir, { recursive: true })
47
+ fs.appendFileSync(logFile, new Date().toISOString() + ' ' + message + '\n', 'utf8')
48
+ } catch {
49
+ /* 日志失败不影响主流程 */
50
+ }
51
+ }
52
+
53
+ function readConfig() {
54
+ const fallback = {
55
+ width: 460,
56
+ autoHideOnBlur: true,
57
+ followMainSession: true,
58
+ alwaysOnTop: false,
59
+ autoShow: false,
60
+ hotkey: DEFAULT_HOTKEY,
61
+ }
62
+ try {
63
+ // 只读不写:文件缺失就用内存里的 fallback。
64
+ // 以前这里会把 fallback 落盘,等于替宿主造了一份「没有 enabled」的壳配置,
65
+ // 宿主再按「文件存在」判老用户,默认值就被悄悄翻转了。
66
+ fs.mkdirSync(dir, { recursive: true })
67
+ // 去 BOM:用记事本 / PowerShell 手改过的文件会带 BOM,JSON.parse 会直接抛
68
+ const text = fs.readFileSync(cfgFile, 'utf8').replace(/^\uFEFF/, '')
69
+ return { ...fallback, ...JSON.parse(text) }
70
+ } catch {
71
+ return fallback
72
+ }
73
+ }
74
+
75
+ function argValue(name) {
76
+ const prefix = '--' + name + '='
77
+ const hit = process.argv.find((a) => a.startsWith(prefix))
78
+ return hit === undefined ? undefined : hit.slice(prefix.length)
79
+ }
80
+
81
+ function resolveUrl() {
82
+ const direct = argValue('url')
83
+ if (direct) return direct
84
+ const file = argValue('url-file') || urlFile
85
+ for (let i = 0; i < 40; i++) {
86
+ try {
87
+ const value = fs.readFileSync(file, 'utf8').trim()
88
+ if (value.startsWith('http')) return value
89
+ } catch {
90
+ /* 文件还没写出来,稍后再读 */
91
+ }
92
+ const until = Date.now() + 200
93
+ while (Date.now() < until) {
94
+ /* 启动阶段同步等待,逻辑更简单 */
95
+ }
96
+ }
97
+ return ''
98
+ }
99
+
100
+ const config = readConfig()
101
+ const width = Number(argValue('width')) || config.width
102
+ /**
103
+ * 要盯着的宿主进程 pid。
104
+ *
105
+ * 显式参数优先;没传时用 process.ppid —— 外壳是宿主 spawn 出来的,父进程就是 DSH 宿主本身
106
+ * (Windows 上父进程退出后 ppid 不会被改写成别人,所以这个值一直指向当初拉起我们的进程)。
107
+ * 因此这一步不需要宿主配合,重启外壳即可生效。
108
+ */
109
+ const ownerPid = Number(argValue('owner-pid')) || process.ppid
110
+ /**
111
+ * 当前是否置顶。
112
+ *
113
+ * 默认 false:不抢 topmost 层,靠「显示时拿到焦点」自然排在普通窗口前面,
114
+ * 别的应用的置顶窗口(悬浮视频、桌宠之类)仍然可以盖住它。
115
+ */
116
+ let topMost = config.alwaysOnTop === true
117
+ let win = null
118
+ /**
119
+ * 用户点了「固定」:不自动收起 + 置顶。
120
+ *
121
+ * 只在内存里,外壳重启(含「保存并重启」)或 DSH 重启后失效 —— 这是刻意的:
122
+ * 固定是「我现在要它钉住」,不是长期偏好;长期偏好是设置页那两个开关。
123
+ */
124
+ let pinned = false
125
+ /**
126
+ * 工具条展开期间的软固定:窗口不因失焦收起,但**不动**置顶。
127
+ *
128
+ * 没有它的话,点开工具条后手一离开窗口,窗口就滑走了,工具条跟着没。
129
+ */
130
+ let holdOpen = false
131
+ /** 目标状态:true = 应收起。动画开始时就置位,别等动画结束(否则动画期间的 blur 会被当成「还没收起」而丢掉)。 */
132
+ let hidden = false
133
+ /** 正在做进出动画。 */
134
+ let busy = false
135
+ /** 动画期间收到的收起请求:动画结束后补做,不然窗口会卡在「显示但失焦」。 */
136
+ let pendingHide = null
137
+ /**
138
+ * 宿主转来的「在侧栏窗口打开」请求:页面还没装好监听时先存着,页面 ready 后自己来取。
139
+ * 只放内存,不落盘 —— 请求是一次性的,外壳重启就没了(宿主那边也不会重放)。
140
+ */
141
+ let pendingOpen = null
142
+ /** 常驻的 focus.ps1 子进程(读 stdin,收到 force <pid> 就切前台,收到 fg 就报前台)。 */
143
+ let focusHelper = null
144
+ let helperRestarts = 0
145
+ /** 助手 stdout 的行缓冲。 */
146
+ let helperOut = ''
147
+ /** 已经确认过「系统前台是本窗口」——只有确认过才敢按前台变化来收起。 */
148
+ let foregroundArmed = false
149
+ /** 武装后连续几次发现前台不是我们。 */
150
+ let foregroundMisses = 0
151
+ /** 本次显示已经强制切前台几次。 */
152
+ let forceAttempts = 0
153
+ /** 上一次看到的前台 pid,用来只在变化时记一行日志。 */
154
+ let lastForegroundPid = -1
155
+ /** 确认拿到前台的时刻:刚拿到的 800ms 内被别人抢走算拉锯,补抢而不是收起。 */
156
+ let armedAt = 0
157
+ /** 正在退出:别再拉起助手。 */
158
+ let quitting = false
159
+ let lastFlag = 0
160
+ /** shell.json 里要求的呼出热键(可能还没注册上)与当前**确实注册成功**的热键。 */
161
+ let hotkeyRequested = ''
162
+ let hotkeyActive = ''
163
+ /** shell.json 上次处理过的 mtime:变了才重跑即时生效的设置。 */
164
+ let lastCfgMtime = 0
165
+ /** 设置页正在录制快捷键:热键临时卸掉,恢复时要装回去的那个组合放 pausedHotkey。 */
166
+ let hotkeyPaused = false
167
+ let pausedHotkey = ''
168
+
169
+ function workArea() {
170
+ return screen.getDisplayNearestPoint(screen.getCursorScreenPoint()).workArea
171
+ }
172
+
173
+ function ease(t) {
174
+ return 1 - Math.pow(1 - t, 3)
175
+ }
176
+
177
+ async function slideTo(targetX) {
178
+ if (!win || win.isDestroyed()) return
179
+ const area = workArea()
180
+ const from = win.getBounds().x
181
+ for (let i = 1; i <= 14; i++) {
182
+ if (!win || win.isDestroyed()) return
183
+ const x = Math.round(from + (targetX - from) * ease(i / 14))
184
+ win.setBounds({ x, y: area.y, width, height: area.height })
185
+ await new Promise((r) => setTimeout(r, 12))
186
+ }
187
+ }
188
+
189
+ async function hideWindow(reason) {
190
+ if (!win || win.isDestroyed() || hidden) return
191
+ if (busy) {
192
+ pendingHide = reason
193
+ return
194
+ }
195
+ // 收起时一定松开软固定:否则下次呼出来会「再也不自动收起」(页面那边也会自己收工具条)
196
+ holdOpen = false
197
+ hidden = true
198
+ busy = true
199
+ try {
200
+ const area = workArea()
201
+ await slideTo(area.x + area.width)
202
+ if (!win || win.isDestroyed()) return
203
+ win.hide()
204
+ log('hidden (' + reason + ')')
205
+ } finally {
206
+ busy = false
207
+ }
208
+ }
209
+
210
+ async function showWindow(reason) {
211
+ if (!win || win.isDestroyed() || !hidden || busy) return
212
+ hidden = false
213
+ pendingHide = null
214
+ foregroundArmed = false
215
+ foregroundMisses = 0
216
+ forceAttempts = 0
217
+ lastForegroundPid = -1
218
+ armedAt = 0
219
+ busy = true
220
+ try {
221
+ const area = workArea()
222
+ win.show()
223
+ win.setBounds({ x: area.x + area.width, y: area.y, width, height: area.height })
224
+ await slideTo(area.x + area.width - width)
225
+ log('shown (' + reason + ')')
226
+ } finally {
227
+ busy = false
228
+ }
229
+ if (!win || win.isDestroyed()) return
230
+ // 滑动这几百毫秒里用户已经点到别处了:直接收起,别把窗口晾在屏幕上。
231
+ if (pendingHide !== null) {
232
+ const why = pendingHide
233
+ pendingHide = null
234
+ void hideWindow(why)
235
+ return
236
+ }
237
+ ensureFocus()
238
+ }
239
+
240
+ /**
241
+ * 清掉上一次留下的助手进程。
242
+ *
243
+ * 外壳被 taskkill 强杀时,助手偶尔来不及收到 stdin EOF 就活成了孤儿;
244
+ * 每次重启留一个 powershell 不划算,所以启动时按「命令行里带 focus.ps1 且父进程不是自己」扫一遍。
245
+ */
246
+ function killStaleHelper() {
247
+ const script = path.join(__dirname, 'focus.ps1')
248
+ // 只认这个脚本的完整路径:命令行里只是提过 focus.ps1 的进程(例如排查用的 pwsh)不能被误杀。
249
+ const sweep = [
250
+ 'Get-CimInstance Win32_Process -Filter "Name=\'powershell.exe\'"',
251
+ "| Where-Object { $_.CommandLine -like '*" + script + "*' -and $_.ParentProcessId -ne " + process.pid + ' }',
252
+ '| ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }',
253
+ ].join(' ')
254
+ try {
255
+ execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', sweep], {
256
+ stdio: 'ignore',
257
+ windowsHide: true,
258
+ })
259
+ } catch (error) {
260
+ log('stale helper sweep failed: ' + (error && error.message))
261
+ }
262
+ }
263
+
264
+ /**
265
+ * 拉起常驻的前台助手(focus.ps1):它读 stdin,收到 `force <pid>` 就调 SwitchToThisWindow。
266
+ *
267
+ * Windows 的前台锁会静默拒绝后台进程的 SetForegroundWindow,而 `autoHideOnBlur` 只有 blur
268
+ * 一个触发点 —— 窗口没真正成为系统前台,用户点别处就不会产生 blur,于是「点别处收不起来」。
269
+ * 热键触发时进程有前台权限所以正常,路由/flag 触发就不一定,这就是问题时好时坏的原因。
270
+ */
271
+ function startFocusHelper() {
272
+ const script = path.join(__dirname, 'focus.ps1')
273
+ if (!fs.existsSync(script)) {
274
+ log('focus helper missing: ' + script)
275
+ return
276
+ }
277
+ focusHelper = spawn(
278
+ 'powershell.exe',
279
+ ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-WindowStyle', 'Hidden', '-File', script],
280
+ { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true },
281
+ )
282
+ focusHelper.stdout.setEncoding('utf8')
283
+ focusHelper.stdout.on('data', (chunk) => {
284
+ helperOut += chunk
285
+ let cut = helperOut.indexOf('\n')
286
+ while (cut >= 0) {
287
+ const line = helperOut.slice(0, cut).trim()
288
+ helperOut = helperOut.slice(cut + 1)
289
+ if (line !== '') onHelperLine(line)
290
+ cut = helperOut.indexOf('\n')
291
+ }
292
+ })
293
+ focusHelper.on('error', (error) => {
294
+ log('focus helper error: ' + (error && error.message))
295
+ focusHelper = null
296
+ })
297
+ focusHelper.on('exit', (code) => {
298
+ log('focus helper exit ' + code)
299
+ focusHelper = null
300
+ // 助手意外退出就补一次;失败太多次就别再折腾,退回「只靠 blur」的行为。
301
+ if (!quitting && helperRestarts < 3) {
302
+ helperRestarts += 1
303
+ setTimeout(startFocusHelper, 1000)
304
+ }
305
+ })
306
+ }
307
+
308
+ /** 让 focus.ps1 把本进程的窗口切到系统前台(期望一行回执,写进日志)。 */
309
+ function forceForeground() {
310
+ if (focusHelper === null || focusHelper.killed) return
311
+ try {
312
+ focusHelper.stdin.write('force ' + process.pid + '\n')
313
+ } catch (error) {
314
+ log('force foreground failed: ' + (error && error.message))
315
+ }
316
+ }
317
+
318
+ /**
319
+ * 显示后把焦点落实:先走 Electron 的 focus(),再交给 focus.ps1 强制切前台。
320
+ * 不做「focus() 失败就最小化再还原」那套 —— 那样会闪一下,而且 SetForegroundWindow 照样被拒。
321
+ */
322
+ function ensureFocus() {
323
+ if (!win || win.isDestroyed() || hidden) return
324
+ win.focus()
325
+ if (!shouldAutoHide()) return
326
+ forceForeground()
327
+ }
328
+
329
+ /**
330
+ * 前台监听:每 250ms 问一次 focus.ps1「现在前台是谁」。
331
+ *
332
+ * 这是 autoHideOnBlur 的主力。Electron 的 blur 事件在这种场景下不可靠
333
+ * (实测同一份代码,有时候 0.7 秒就 blur,有时候 72 秒都没有),
334
+ * 所以不猜事件,直接看系统前台的 pid:
335
+ * 1. 先确认过「前台是我们」才武装;
336
+ * 2. 武装后连续两次不是我们 → 收起。
337
+ * 没武装之前反复强制切前台(最多 12 次 ≈ 3 秒),避免显示出来却没有焦点。
338
+ */
339
+ function probeForeground() {
340
+ if (focusHelper === null || focusHelper.killed) return
341
+ try {
342
+ focusHelper.stdin.write('fg\n')
343
+ } catch {
344
+ /* 助手刚死,下一拍会重连 */
345
+ }
346
+ }
347
+
348
+ function onForeground(pid) {
349
+ if (!win || win.isDestroyed() || hidden || busy) return
350
+ // 固定 / 工具条展开期间不看前台:看也不收,省得白记日志
351
+ if (!shouldAutoHide()) return
352
+ if (pid !== lastForegroundPid) {
353
+ lastForegroundPid = pid
354
+ log('foreground -> ' + pid + (pid === process.pid ? ' (us)' : ''))
355
+ }
356
+ if (pid === process.pid) {
357
+ if (!foregroundArmed) {
358
+ foregroundArmed = true
359
+ armedAt = Date.now()
360
+ log('foreground armed after ' + forceAttempts + ' force attempt(s)')
361
+ }
362
+ foregroundMisses = 0
363
+ return
364
+ }
365
+ if (!foregroundArmed) {
366
+ // 还没拿到前台:每一拍都补一脚,别等;超过 30 次(约 7 秒)就认输并记日志。
367
+ if (forceAttempts < 30) {
368
+ forceAttempts += 1
369
+ forceForeground()
370
+ } else if (forceAttempts === 30) {
371
+ forceAttempts += 1
372
+ log('foreground never armed')
373
+ }
374
+ return
375
+ }
376
+ // 刚抢到就被别人抢走:当成焦点拉锯,补一脚而不是收起(否则窗口会闪一下就没)。
377
+ if (Date.now() - armedAt < 800) {
378
+ forceForeground()
379
+ return
380
+ }
381
+ foregroundMisses += 1
382
+ if (foregroundMisses >= 2) {
383
+ foregroundMisses = 0
384
+ foregroundArmed = false
385
+ void hideWindow('focus-left')
386
+ }
387
+ }
388
+
389
+ function onHelperLine(line) {
390
+ if (line.startsWith('fg ')) {
391
+ const parts = line.slice(3).split(' ')
392
+ const pid = Number(parts[1])
393
+ onForeground(Number.isFinite(pid) ? pid : -1)
394
+ return
395
+ }
396
+ log('focus helper: ' + line)
397
+ }
398
+
399
+ function startForegroundWatch() {
400
+ setInterval(() => {
401
+ if (!win || win.isDestroyed() || hidden || busy) return
402
+ if (!shouldAutoHide()) return
403
+ probeForeground()
404
+ }, 250)
405
+ }
406
+
407
+ /**
408
+ * 宿主存活:DSH 退出后外壳自己退出。
409
+ *
410
+ * 为什么必须这样做:DSH 每次启动都换端口和 token,外壳只会在启动时读一次 shell.url。
411
+ * 旧外壳如果活到下一次启动,页面就永远连的是死地址;而宿主启动时看到 shell.pid 还活着
412
+ * 又会跳过拉起,于是「侧栏连不上」。
413
+ *
414
+ * 判定只认 ESRCH(进程确实不存在):EPERM 等一律当存活,宁可多留一秒也不误退。
415
+ * 宿主退出后最多 1 秒收敛;退出时窗口直接关掉,不做滑出动画(DSH 都没了,动画没有意义)。
416
+ */
417
+ function startOwnerWatch() {
418
+ if (!(ownerPid > 0)) {
419
+ log('owner watch skipped (ownerPid=' + ownerPid + ')')
420
+ return
421
+ }
422
+ log('owner watch pid=' + ownerPid)
423
+ setInterval(() => {
424
+ try {
425
+ process.kill(ownerPid, 0)
426
+ } catch (error) {
427
+ if (error && error.code === 'ESRCH') {
428
+ log('owner gone (pid ' + ownerPid + ') -> quit')
429
+ app.quit()
430
+ }
431
+ }
432
+ }, 1000).unref?.()
433
+ }
434
+
435
+ async function toggle(reason) {
436
+ if (!win || win.isDestroyed()) return
437
+ if (hidden) {
438
+ await showWindow(reason)
439
+ return
440
+ }
441
+ // 不置顶时窗口可能被别的窗口整个盖住:热键先把窗口提到前面(再按一次才收起),
442
+ // 否则「按呼出热键把它拉回来」会变成「先把它藏起来」,看起来像失灵。
443
+ if (!topMost && !win.isFocused()) {
444
+ ensureFocus()
445
+ log('raised (hotkey, not topmost)')
446
+ return
447
+ }
448
+ await hideWindow(reason)
449
+ }
450
+
451
+ /** 应用置顶状态:true 用 floating 层,false 回到普通层。 */
452
+ function applyAlwaysOnTop(on) {
453
+ if (!win || win.isDestroyed()) return
454
+ if (on) win.setAlwaysOnTop(true, 'floating')
455
+ else win.setAlwaysOnTop(false)
456
+ }
457
+
458
+ /**
459
+ * 有效置顶 = 固定 或 设置里的置顶。
460
+ *
461
+ * 置顶只能是派生值:设置页每 500ms 把文件里的 alwaysOnTop 同步过来,
462
+ * 要是直接赋给 topMost,固定就会被一次设置轮询悄悄拉掉。
463
+ */
464
+ function effectiveTop() {
465
+ return pinned || config.alwaysOnTop === true
466
+ }
467
+
468
+ /** 把有效置顶同步到窗口和 topMost(别处不要直接写 topMost)。 */
469
+ function syncTop() {
470
+ topMost = effectiveTop()
471
+ applyAlwaysOnTop(topMost)
472
+ }
473
+
474
+ /** 该不该因为失焦而收起:设置里关了、用户固定了、工具条还开着,三种情况都不收。 */
475
+ function shouldAutoHide() {
476
+ return config.autoHideOnBlur !== false && !pinned && !holdOpen
477
+ }
478
+
479
+ /** 注册一个全局热键;非法写法或被别的程序占用时 Electron 返回 false(也可能直接抛)。 */
480
+ function registerHotkey(accelerator) {
481
+ try {
482
+ return (
483
+ globalShortcut.register(accelerator, () => {
484
+ void toggle('hotkey')
485
+ }) === true
486
+ )
487
+ } catch (error) {
488
+ log('hotkey register threw: ' + (error && error.message))
489
+ return false
490
+ }
491
+ }
492
+
493
+ /**
494
+ * 把热键注册结果写成 hotkey.json,供设置页显示「已生效 / 注册失败」。
495
+ *
496
+ * 外壳**不写** shell.json(那是宿主的配置),只写这份自己的状态,所以宿主/设置页怎么读都不会
497
+ * 反向改配置。失败信息很重要:被别的程序占用的组合按下去毫无反应,不说清楚就像功能坏了。
498
+ */
499
+ function writeHotkeyStatus(requested, active, ok, message) {
500
+ try {
501
+ fs.mkdirSync(dir, { recursive: true })
502
+ fs.writeFileSync(
503
+ hotkeyFile,
504
+ JSON.stringify({ requested, active, ok, message, at: Date.now() }, null, 2),
505
+ 'utf8',
506
+ )
507
+ } catch (error) {
508
+ log('hotkey status write failed: ' + (error && error.message))
509
+ }
510
+ }
511
+
512
+ /**
513
+ * 切换呼出热键:先卸旧的,再注册新的。
514
+ *
515
+ * 新组合注册失败(写法非法 / 被其它程序占用)时必须兜底:先装回上一个能用的,再退到默认值。
516
+ * 启动时(previous 为空)尤其重要 —— 文件里存着一个被占用的组合,不能因此一条热键都没有。
517
+ * @returns 是否注册成功。
518
+ */
519
+ function applyHotkey(target) {
520
+ const next = typeof target === 'string' && target.trim() !== '' ? target.trim() : DEFAULT_HOTKEY
521
+ // 录制期间暂停:只记下要求,等恢复时再注册(否则刚卸掉又被这里装回去)
522
+ if (hotkeyPaused) {
523
+ hotkeyRequested = next
524
+ return true
525
+ }
526
+ if (next === hotkeyActive) return true
527
+ const previous = hotkeyActive
528
+ if (previous !== '') {
529
+ try {
530
+ globalShortcut.unregister(previous)
531
+ } catch {
532
+ /* 已经不在注册表里了 */
533
+ }
534
+ hotkeyActive = ''
535
+ }
536
+ if (registerHotkey(next)) {
537
+ hotkeyActive = next
538
+ log('hotkey ' + next + ' -> registered')
539
+ writeHotkeyStatus(next, next, true, '')
540
+ return true
541
+ }
542
+ const fallbacks = []
543
+ if (previous !== '' && previous !== next) fallbacks.push(previous)
544
+ if (DEFAULT_HOTKEY !== next && DEFAULT_HOTKEY !== previous) fallbacks.push(DEFAULT_HOTKEY)
545
+ log('hotkey ' + next + ' -> failed' + (fallbacks.length === 0 ? ', no fallback available' : ''))
546
+ for (const candidate of fallbacks) {
547
+ if (!registerHotkey(candidate)) continue
548
+ hotkeyActive = candidate
549
+ log('hotkey fell back to ' + candidate)
550
+ writeHotkeyStatus(next, candidate, false, '该组合可能被其它程序占用,仍在使用 ' + candidate)
551
+ return false
552
+ }
553
+ writeHotkeyStatus(next, '', false, '该组合可能被其它程序占用,现在没有可用的呼出快捷键')
554
+ return false
555
+ }
556
+
557
+ /**
558
+ * 录制期间临时卸掉全局热键(`hotkey.pause` 由宿主按设置页的请求写入)。
559
+ *
560
+ * 为什么必须卸:`globalShortcut` 注册着的组合会被操作系统截走,页面收不到 keydown,
561
+ * 用户照着字段里那个值按一遍既录不到、还会把侧栏窗口叫出来抢走焦点。卸掉之后录制就和
562
+ * 普通输入框一样。恢复时装回 `hotkeyRequested`(录制期间改过值就以新值为准)。
563
+ *
564
+ * 兜底:设置页崩了/被关掉没来得及恢复时,`hotkey.pause` 里的时间戳超过 2 分钟就不再理会,
565
+ * 免得一条热键被永久停掉。
566
+ */
567
+ function pollHotkeyPause() {
568
+ let paused = false
569
+ try {
570
+ const parsed = JSON.parse(fs.readFileSync(pauseFile, 'utf8').replace(/^\uFEFF/, ''))
571
+ const at = Number(parsed.at) || 0
572
+ paused = parsed.paused === true && Date.now() - at < HOTKEY_PAUSE_LIMIT_MS
573
+ } catch {
574
+ paused = false // 文件不存在 = 没在录制
575
+ }
576
+ if (paused === hotkeyPaused) return
577
+ hotkeyPaused = paused
578
+ if (paused) {
579
+ if (hotkeyActive === '') {
580
+ log('hotkey paused (none active)')
581
+ return
582
+ }
583
+ pausedHotkey = hotkeyActive
584
+ try {
585
+ globalShortcut.unregister(hotkeyActive)
586
+ } catch {
587
+ /* 已经不在注册表里了 */
588
+ }
589
+ hotkeyActive = ''
590
+ log('hotkey paused ' + pausedHotkey)
591
+ return
592
+ }
593
+ const target = hotkeyRequested !== '' ? hotkeyRequested : pausedHotkey
594
+ pausedHotkey = ''
595
+ log('hotkey resume -> ' + target)
596
+ if (target !== '') applyHotkey(target)
597
+ }
598
+
599
+ /**
600
+ * 即时生效的设置:窗口置顶 + 呼出热键。
601
+ *
602
+ * 其余窗口类设置(宽度、自动收起)仍然只在启动时读一次,改完要重启外壳;
603
+ * 这两个是纯 z-order / 键盘注册操作,改一下没有布局代价,所以做成 500ms 轮询即时生效。
604
+ *
605
+ * 判断依据是**文件 mtime**而不是「值变了」:上一次注册失败的组合,用户原样再保存一遍
606
+ * (或者手动改回同一个值)必须能再试一次 —— 只比较值的话它会永远停在失败态。
607
+ */
608
+ function watchLiveSettings() {
609
+ setInterval(() => {
610
+ if (!win || win.isDestroyed()) return
611
+ let stat
612
+ let parsed
613
+ try {
614
+ stat = fs.statSync(cfgFile)
615
+ parsed = JSON.parse(fs.readFileSync(cfgFile, 'utf8').replace(/^\uFEFF/, ''))
616
+ } catch {
617
+ // 文件正在被写(读到半截)或还没建出来:这一拍跳过,下一拍再试
618
+ return
619
+ }
620
+ if (parsed === null || typeof parsed !== 'object') return
621
+ if (stat.mtimeMs === lastCfgMtime) return
622
+ lastCfgMtime = stat.mtimeMs
623
+ const nextTop = parsed.alwaysOnTop === true
624
+ if (config.alwaysOnTop !== nextTop) {
625
+ config.alwaysOnTop = nextTop
626
+ // 置顶是派生值:固定着的时候,改设置不能把固定悄悄拉掉
627
+ syncTop()
628
+ log('alwaysOnTop -> ' + nextTop + (pinned ? ' (pinned overrides)' : ''))
629
+ }
630
+ const nextHotkey = typeof parsed.hotkey === 'string' ? parsed.hotkey.trim() : ''
631
+ // 空值当作「文件里没写」:别因为手改坏一个字段就把热键卸掉
632
+ if (nextHotkey !== '') {
633
+ hotkeyRequested = nextHotkey
634
+ applyHotkey(nextHotkey)
635
+ }
636
+ }, 500)
637
+ }
638
+
639
+ /**
640
+ * 注入的只有「结构透明」:把 html / body / #root 的背景清掉,让页面自己画的面
641
+ * (或者将来换肤插件铺的壁纸/玻璃)决定看见什么。
642
+ *
643
+ * 以前这里还会给 body 刷一层 rgba(24,24,28,α) 当"透明度",但那层在页面自己的容器下面,
644
+ * 调 α 几乎看不出变化(0.5 的下限更是白设),所以 0.5.1 直接删掉:壳不再着色。
645
+ */
646
+ function injectStyle() {
647
+ if (!win || win.isDestroyed()) return
648
+ const css = [
649
+ 'html, body, #root { background: transparent !important; }',
650
+ '::-webkit-scrollbar { width: 6px; }',
651
+ '::-webkit-scrollbar-thumb { background: rgba(255,255,255,.18); border-radius: 3px; }',
652
+ ].join('\n')
653
+ win.webContents.insertCSS(css).catch((e) => log('css failed: ' + (e && e.message)))
654
+ log('css injected (structural transparency, no tint)')
655
+ }
656
+
657
+ /**
658
+ * 侧栏窗口不弹系统通知:通知由 DSH 主窗口负责。
659
+ *
660
+ * 主窗口和侧栏加载同一个页面,各跑一份 dsh-pet 客户端;dsh-pet 的 toast() 只看「本页是否可见且聚焦」,
661
+ * 于是同一条「完成」会被两个页面各弹一次 —— 侧栏隐藏时它甚至会在你正看着主窗口时也弹。
662
+ * 这里直接把这个 Electron 会话的 notifications 权限拒掉:页面里 Notification.permission 变成 denied,
663
+ * dsh-pet 自己就跳过了。侧栏是独立进程、独立 session,主窗口不受影响。
664
+ */
665
+ function denyNotifications(target) {
666
+ const session = target.webContents.session
667
+ session.setPermissionRequestHandler((webContents, permission, callback) => {
668
+ callback(permission !== 'notifications')
669
+ })
670
+ session.setPermissionCheckHandler((webContents, permission) => permission !== 'notifications')
671
+ }
672
+
673
+ /** 启动时记一行页面看到的通知权限,方便确认上面那道闸真的生效了。 */
674
+ function reportNotificationPermission() {
675
+ if (!win || win.isDestroyed()) return
676
+ win.webContents
677
+ .executeJavaScript('typeof Notification === "undefined" ? "missing" : Notification.permission', true)
678
+ .then((permission) => log('notification permission=' + permission))
679
+ .catch((error) => log('notification permission check failed: ' + (error && error.message)))
680
+ }
681
+
682
+ function createWindow(url) {
683
+ const area = workArea()
684
+ // 启动即**收起**:建在屏幕外、不显示、不抢焦点。
685
+ // 以前窗口一创建就显示在右边缘,于是每次 DSH 启动都会「弹出来一次」再被失焦收起。
686
+ hidden = true
687
+ win = new BrowserWindow({
688
+ x: area.x + area.width,
689
+ y: area.y,
690
+ width,
691
+ height: area.height,
692
+ show: false,
693
+ frame: false,
694
+ resizable: false,
695
+ skipTaskbar: true,
696
+ alwaysOnTop: topMost,
697
+ transparent: true,
698
+ hasShadow: false,
699
+ backgroundColor: '#00000000',
700
+ webPreferences: {
701
+ contextIsolation: true,
702
+ nodeIntegration: false,
703
+ // 收着的时候页面也要能跑:跟随对话、状态轮询、日志转发都是定时器,
704
+ // 默认的后台节流会把隐藏窗口的定时器压到几乎不触发。
705
+ backgroundThrottling: false,
706
+ // 给页面注入「这是侧栏窗口」的标记,插件靠它决定要不要跟随主窗口切对话
707
+ preload: path.join(__dirname, 'marker.js'),
708
+ },
709
+ })
710
+ applyAlwaysOnTop(topMost)
711
+ denyNotifications(win)
712
+ win.loadURL(url).then(() => log('url loaded')).catch((e) => log('load failed: ' + (e && e.message)))
713
+ win.webContents.on('did-finish-load', injectStyle)
714
+ win.webContents.once('did-finish-load', reportNotificationPermission)
715
+ // 「启动弹出」:勾上后 DSH 启动时直接滑出来;不勾就保持后台待命(= 0.4.1 起的行为)。
716
+ // 排在 injectStyle 之后注册,保证动画开始时页面底色已经被清过,不会闪一下白窗。
717
+ if (config.autoShow === true) {
718
+ win.webContents.once('did-finish-load', () => {
719
+ log('auto-show requested')
720
+ void showWindow('auto-show')
721
+ })
722
+ }
723
+ // 把页面里带 [dsh-side-window] 前缀的日志转到 shell.log,排查「跟随切换对话」这类窗口内行为时用得上。
724
+ // 事件签名跨 Electron 版本不同:老版 (event, level, message),新版 (event, details)。
725
+ win.webContents.on('console-message', (event, levelOrDetails, maybeMessage) => {
726
+ const message = levelOrDetails !== null && typeof levelOrDetails === 'object'
727
+ ? levelOrDetails.message
728
+ : maybeMessage
729
+ if (typeof message === 'string' && message.indexOf('[dsh-side-window]') >= 0) log('page: ' + message)
730
+ })
731
+ win.on('focus', () => log('evt focus'))
732
+ win.on('blur', () => log('evt blur (hidden=' + hidden + ' busy=' + busy + ')'))
733
+ win.on('blur', () => {
734
+ if (shouldAutoHide()) void hideWindow('blur')
735
+ })
736
+ win.on('closed', () => {
737
+ win = null
738
+ })
739
+ log('window created width=' + width + ' alwaysOnTop=' + topMost + ' hidden=' + hidden)
740
+ }
741
+
742
+ /**
743
+ * 页面通道:只认侧栏窗口自己发来的请求。
744
+ *
745
+ * 主窗口、别的标签页、任何网页都碰不到这条 IPC —— 页面只能通过 preload 暴露的三个函数
746
+ * 把话递进来,而 preload 只挂在侧栏窗口上。
747
+ */
748
+ function fromSidebar(event) {
749
+ return win !== null && !win.isDestroyed() && event.sender === win.webContents
750
+ }
751
+
752
+ /** 设置「固定」:不自动收起 + 置顶。返回当前值,页面拿它校正乐观更新。 */
753
+ function setPinned(next) {
754
+ const value = next === true
755
+ if (value === pinned) return pinned
756
+ pinned = value
757
+ syncTop()
758
+ log('pinned -> ' + pinned + ' (topmost=' + topMost + ')')
759
+ // 广播回去:按钮的状态以这里为准,页面自己那点本地 state 只是先手显示
760
+ if (win !== null && !win.isDestroyed()) win.webContents.send('dsh-side-window:pin', pinned)
761
+ return pinned
762
+ }
763
+
764
+ /** 工具条展开/收起:展开期间不收起窗口(软固定),收起后恢复正常。 */
765
+ function setHold(next) {
766
+ const value = next === true
767
+ if (value === holdOpen) return holdOpen
768
+ holdOpen = value
769
+ log('hold -> ' + holdOpen)
770
+ return holdOpen
771
+ }
772
+
773
+ /** 请求文件的 mtime;没有文件时返回 0。 */
774
+ function openMtime() {
775
+ try {
776
+ return fs.statSync(openFile).mtimeMs
777
+ } catch {
778
+ return 0
779
+ }
780
+ }
781
+
782
+ /**
783
+ * 读一条「在侧栏窗口打开」请求。
784
+ *
785
+ * 两种形状都收:`{ address, … }`(文件)和 `{ url, … }`(链接)。只认 address 的话,
786
+ * 链接请求会被静默丢掉 —— 现象就是「菜单点了没反应」。
787
+ * @returns 请求对象;没有或读不懂时返回 null。
788
+ */
789
+ function readOpenRequest() {
790
+ try {
791
+ const parsed = JSON.parse(fs.readFileSync(openFile, 'utf8'))
792
+ if (parsed === null || typeof parsed !== 'object') return null
793
+ const address = typeof parsed.address === 'string' ? parsed.address : ''
794
+ const url = typeof parsed.url === 'string' ? parsed.url : ''
795
+ if (address === '' && url === '') return null
796
+ return parsed
797
+ } catch {
798
+ return null
799
+ }
800
+ }
801
+
802
+ /**
803
+ * 把一条请求变成动作:滑出窗口,再把地址推给页面。
804
+ *
805
+ * 页面可能还没装好监听(外壳刚起来、页面还在加载的那一两秒),所以同时留一份 pendingOpen,
806
+ * 页面就绪后用 `open:take` 再来取一次;两种投递重复到达也无害,侧栏只会聚焦已开的 tab。
807
+ * @param entry - 宿主写的请求对象。
808
+ */
809
+ function pushOpen(entry) {
810
+ if (entry === null || typeof entry !== 'object') return
811
+ const target = typeof entry.address === 'string' && entry.address !== '' ? entry.address : entry.url
812
+ if (typeof target !== 'string' || target === '') return
813
+ pendingOpen = entry
814
+ log('open request #' + entry.seq + ' -> ' + target.slice(0, 96))
815
+ // 正在做进出动画时 showWindow 会自己放弃(它只认稳定态),滑完再说一次
816
+ const show = () => {
817
+ if (win === null || win.isDestroyed() || !hidden) return
818
+ void showWindow('open-resource')
819
+ }
820
+ show()
821
+ if (busy) setTimeout(show, 400)
822
+ if (win !== null && !win.isDestroyed()) win.webContents.send('dsh-side-window:open', entry)
823
+ // 8 秒够页面来取;之后清掉,免得一次 HMR 重载又把同一个文件重开一遍
824
+ const seq = entry.seq
825
+ setTimeout(() => {
826
+ if (pendingOpen !== null && pendingOpen.seq === seq) pendingOpen = null
827
+ }, 8000)
828
+ }
829
+
830
+ ipcMain.handle('dsh-side-window:pin:get', () => pinned)
831
+ ipcMain.handle('dsh-side-window:pin:set', (event, on) => (fromSidebar(event) ? setPinned(on) : pinned))
832
+ ipcMain.handle('dsh-side-window:hold:set', (event, on) => (fromSidebar(event) ? setHold(on) : holdOpen))
833
+ ipcMain.handle('dsh-side-window:hide', (event) => {
834
+ if (!fromSidebar(event)) return false
835
+ // 先松开软固定再收起,否则下次呼出来会「再也不自动收起」
836
+ setHold(false)
837
+ void hideWindow('toolbar')
838
+ return true
839
+ })
840
+ // 「在侧栏窗口打开」:页面 ready 后自己来取还没送到的请求(冷启动那次多半走这条)
841
+ ipcMain.handle('dsh-side-window:open:take', (event) => {
842
+ if (!fromSidebar(event)) return null
843
+ const entry = pendingOpen
844
+ pendingOpen = null
845
+ return entry
846
+ })
847
+
848
+ app.whenReady().then(() => {
849
+ const url = resolveUrl()
850
+ if (url === '') {
851
+ log('missing url file=' + urlFile)
852
+ app.quit()
853
+ return
854
+ }
855
+ log('url=' + url.slice(0, 56))
856
+ try {
857
+ fs.writeFileSync(path.join(dir, 'shell.pid'), String(process.pid), 'utf8')
858
+ log('pid file written ' + process.pid)
859
+ } catch (error) {
860
+ log('pid file failed: ' + (error && error.message))
861
+ }
862
+ createWindow(url)
863
+ killStaleHelper()
864
+ startFocusHelper()
865
+ startForegroundWatch()
866
+ startOwnerWatch()
867
+ watchLiveSettings()
868
+
869
+ // 呼出热键来自 shell.json(默认 Ctrl+Shift+L):注册成功与否都写进 hotkey.json,
870
+ // 设置页据此提示「已生效 / 被别的程序占用」。之后改设置由 watchLiveSettings 热切换。
871
+ hotkeyRequested =
872
+ typeof config.hotkey === 'string' && config.hotkey.trim() !== '' ? config.hotkey.trim() : DEFAULT_HOTKEY
873
+ applyHotkey(hotkeyRequested)
874
+
875
+ fs.mkdirSync(dir, { recursive: true })
876
+ if (!fs.existsSync(flagFile)) fs.writeFileSync(flagFile, 'init', 'utf8')
877
+ lastFlag = fs.statSync(flagFile).mtimeMs
878
+ let lastOpen = openMtime()
879
+ setInterval(() => {
880
+ try {
881
+ const m = fs.statSync(flagFile).mtimeMs
882
+ if (m !== lastFlag) {
883
+ lastFlag = m
884
+ void toggle('flag')
885
+ }
886
+ } catch {
887
+ /* 跳过这一拍 */
888
+ }
889
+ // 宿主写的「在侧栏窗口打开」请求:mtime 变了就读一条。
890
+ // 和开合同一个节拍,不新增定时器。
891
+ try {
892
+ const m = openMtime()
893
+ if (m === lastOpen) return
894
+ lastOpen = m
895
+ const entry = readOpenRequest()
896
+ if (entry !== null) pushOpen(entry)
897
+ } catch {
898
+ /* 跳过这一拍 */
899
+ }
900
+ }, 120)
901
+ // 和开合信号同一个节拍:录制快捷键时临时卸掉热键,结束再装回去
902
+ setInterval(pollHotkeyPause, 120)
903
+ })
904
+
905
+ app.on('before-quit', () => {
906
+ quitting = true
907
+ try {
908
+ if (focusHelper !== null) focusHelper.kill()
909
+ } catch {
910
+ /* 已经退出了 */
911
+ }
912
+ // 清掉自己的 pid 文件:留着一个已经死掉的 pid,下次宿主启动时可能被系统复用后误判「外壳还活着」
913
+ try {
914
+ const pidFile = path.join(dir, 'shell.pid')
915
+ if (fs.readFileSync(pidFile, 'utf8').trim() === String(process.pid)) fs.rmSync(pidFile, { force: true })
916
+ } catch {
917
+ /* 文件已经被删或读不到 */
918
+ }
919
+ })
920
+
921
+ app.on('window-all-closed', () => {
922
+ app.quit()
923
+ })