cortico-world-agent-speed 0.2.0 → 0.2.2
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 +64 -0
- package/LICENSE +0 -14
- package/README.md +29 -11
- package/THIRD_PARTY_NOTICES.md +69 -0
- package/activity.d.ts +15 -0
- package/activity.js +88 -3
- package/describe.json +806 -0
- package/dist/webui.css +2 -0
- package/dist/webui.css.map +7 -0
- package/dist/webui.js +2 -0
- package/dist/webui.js.map +7 -0
- package/host/app-store.cjs +68 -0
- package/host/cursor.cjs +67 -0
- package/host/electron-main.cjs +666 -0
- package/host/input-shape.cjs +63 -0
- package/host/mouse-lease.cjs +77 -0
- package/host/overlay.cjs +139 -0
- package/host/portrait.cjs +52 -0
- package/host/preload.cjs +60 -14
- package/host/renderer-gone.cjs +24 -0
- package/host/windows.cjs +251 -0
- package/package.json +27 -7
- package/scripts/build-webui.mjs +40 -0
- package/scripts/speech-bank/build.py +166 -0
- package/scripts/speech-bank/dicts.py +76 -0
- package/src/ENV_PROMPT.en.md +51 -0
- package/src/ENV_PROMPT.md +51 -0
- package/src/asr/address.ts +25 -0
- package/src/asr/hotkey.ts +335 -0
- package/src/asr/result.ts +51 -0
- package/src/asr/segmenter.ts +269 -0
- package/src/asr/sherpa.ts +280 -0
- package/src/asr/simplify.ts +38 -0
- package/src/asr/system-recognizer.ts +292 -0
- package/src/asr/system-sapi.ps1 +173 -0
- package/src/asr/transcription-api.ts +176 -0
- package/src/chat.ts +212 -0
- package/src/config.ts +481 -0
- package/src/cua/ENV_PROMPT.en.md +29 -0
- package/src/cua/ENV_PROMPT.md +29 -0
- package/src/cua/config.ts +88 -0
- package/src/cua/cua.ts +712 -0
- package/src/cua/engine/darwin.ts +410 -0
- package/src/cua/engine/display.ts +55 -0
- package/src/cua/engine/fail.ts +15 -0
- package/src/cua/engine/foreground.ts +8 -0
- package/src/cua/engine/image.ts +57 -0
- package/src/cua/engine/keys.ts +70 -0
- package/src/cua/engine/linux-keys.ts +29 -0
- package/src/cua/engine/linux.ts +343 -0
- package/src/cua/engine/mac-keys.ts +57 -0
- package/src/cua/engine/user-activity.ts +54 -0
- package/src/cua/engine/wait-idle.ts +31 -0
- package/src/cua/engine/win32.ts +299 -0
- package/src/cua/engine-child.ts +274 -0
- package/src/cua/engine-ipc.ts +140 -0
- package/src/cua/i18n/de.ts +53 -0
- package/src/cua/i18n/en.ts +63 -0
- package/src/cua/i18n/es-419.ts +53 -0
- package/src/cua/i18n/fr.ts +53 -0
- package/src/cua/i18n/index.ts +26 -0
- package/src/cua/i18n/it.ts +53 -0
- package/src/cua/i18n/ja.ts +53 -0
- package/src/cua/i18n/ko.ts +53 -0
- package/src/cua/i18n/pt-BR.ts +53 -0
- package/src/cua/i18n/ru.ts +59 -0
- package/src/cua/i18n/zh-Hant.ts +53 -0
- package/src/cua/i18n/zh.ts +59 -0
- package/src/cua/model-text.ts +252 -0
- package/src/cua/terminal.ts +31 -0
- package/src/cua/tools.ts +153 -0
- package/src/definition.ts +146 -0
- package/src/host-reason.ts +32 -0
- package/src/i18n/de.ts +409 -0
- package/src/i18n/en.ts +443 -0
- package/src/i18n/es-419.ts +409 -0
- package/src/i18n/fr.ts +409 -0
- package/src/i18n/index.ts +56 -0
- package/src/i18n/it.ts +409 -0
- package/src/i18n/ja.ts +409 -0
- package/src/i18n/ko.ts +409 -0
- package/src/i18n/pt-BR.ts +409 -0
- package/src/i18n/ru.ts +415 -0
- package/src/i18n/zh-Hant.ts +409 -0
- package/src/i18n/zh.ts +440 -0
- package/src/index.ts +15 -0
- package/src/model-text.ts +344 -0
- package/src/moves.ts +101 -0
- package/src/pack-import.ts +361 -0
- package/src/packs.ts +449 -0
- package/src/runtime/download.ts +29 -0
- package/src/runtime/store.ts +293 -0
- package/src/script.ts +202 -0
- package/src/self.ts +247 -0
- package/src/server.ts +479 -0
- package/src/speech/data/CMUDICT-LICENSE +33 -0
- package/src/speech/data/IPADIC-COPYING +71 -0
- package/src/speech/data/UNICODE-LICENSE +39 -0
- package/src/speech/data/en.tsv.gz +0 -0
- package/src/speech/data/ja-ipadic.tsv.gz +0 -0
- package/src/speech/data/ja-unihan.tsv.gz +0 -0
- package/src/speech/data/zh.json +1 -0
- package/src/speech/index.ts +204 -0
- package/src/speech/ipa.ts +83 -0
- package/src/speech/japanese.ts +105 -0
- package/src/speech/jukujikun.ts +22 -0
- package/src/speech/korean.ts +35 -0
- package/src/speech/lang.ts +151 -0
- package/src/speech/rules.ts +72 -0
- package/src/speech/syllable.ts +76 -0
- package/src/status.ts +164 -0
- package/src/tools.ts +110 -0
- package/src/webui/api-rows.css +2 -0
- package/src/webui/api-rows.ts +44 -0
- package/src/webui/client.ts +451 -0
- package/src/webui/dress-dialog.css +14 -0
- package/src/webui/dress-dialog.ts +117 -0
- package/src/webui/dress-panel.ts +160 -0
- package/src/webui/key-capture.ts +60 -0
- package/src/webui/shared/modal.css +13 -0
- package/src/webui/shared/modal.ts +77 -0
- package/src/webui/shared/problem.css +15 -0
- package/src/webui/shared/problem.ts +217 -0
- package/src/webui/shared/strings.ts +5 -0
- package/src/webui/style.css +50 -0
- package/src/window-host.ts +116 -0
- package/src/world.ts +2926 -0
- package/web/activity-motion.js +117 -0
- package/web/appearance.js +60 -0
- package/web/body-host.js +257 -0
- package/web/coo/coo.js +384 -0
- package/web/coo/figure.js +15 -0
- package/web/coo/figure.json +1224 -0
- package/web/dist/dress-dialog.css +1 -0
- package/web/dist/dress-dialog.js +1 -0
- package/web/drag-row.js +49 -0
- package/web/drag.js +149 -0
- package/web/dress.css +170 -0
- package/web/dress.html +37 -0
- package/web/dress.js +786 -0
- package/web/figure-frame.html +16 -0
- package/web/figure-frame.js +128 -0
- package/web/frame-loop.js +55 -0
- package/web/hints.js +77 -0
- package/web/i18n/de.js +170 -0
- package/web/i18n/en.js +177 -0
- package/web/i18n/es-419.js +170 -0
- package/web/i18n/fr.js +170 -0
- package/web/i18n/it.js +170 -0
- package/web/i18n/ja.js +170 -0
- package/web/i18n/ko.js +170 -0
- package/web/i18n/pt-BR.js +170 -0
- package/web/i18n/ru.js +170 -0
- package/web/i18n/zh-Hant.js +170 -0
- package/web/i18n/zh.js +175 -0
- package/web/i18n.js +54 -0
- package/{renderer/vendor → web}/kit/body.js +31 -58
- package/web/looks.js +70 -0
- package/web/mic-worklet.js +36 -0
- package/web/mic.js +117 -0
- package/web/motion-frames.js +80 -0
- package/web/motion-level.js +40 -0
- package/web/new-year-2027.svg +238 -0
- package/web/overlay.html +16 -0
- package/web/overlay.js +100 -0
- package/web/pet-app.js +3000 -0
- package/web/pet.css +642 -0
- package/web/pet.html +21 -0
- package/web/scale-slider.js +259 -0
- package/web/show-hide.js +49 -0
- package/web/sound.js +245 -0
- package/web/speech/zh.json +1 -0
- package/web/speech/zh.ogg +0 -0
- package/web/speech.js +197 -0
- package/web/stage.js +160 -0
- package/web/swap-motion.js +119 -0
- package/web/ui.js +195 -0
- package/host/launch.js +0 -187
- package/host/library.cjs +0 -638
- package/host/main.cjs +0 -389
- package/index.js +0 -93
- package/renderer/index.html +0 -22
- package/renderer/pet-sandbox.html +0 -11
- package/renderer/pet.css +0 -38
- package/renderer/pet.js +0 -251
- package/renderer/vendor/activity-motion.js +0 -101
- package/renderer/vendor/figure-frame.js +0 -115
- package/renderer/vendor/pack.css +0 -2
- /package/{renderer/vendor → web}/kit/rig.js +0 -0
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Electron main process for the pet window.
|
|
3
|
+
*
|
|
4
|
+
* Run as `electron electron-main.cjs --pet-url=http://127.0.0.1:<port>/pet`, or call
|
|
5
|
+
* `runPetHost({ url, parentPid })` from an app's own main process. With `--parent-pid=<pid>`
|
|
6
|
+
* the window closes once that process exits. The window covers the work area of one display
|
|
7
|
+
* (the primary one at start), short of the edge an auto-hidden taskbar waits on, is transparent
|
|
8
|
+
* and always on top, and ignores the mouse until the page reports the pointer is over the figure,
|
|
9
|
+
* a bubble or the menu; in a Wayland session it takes the mouse only over the parts of the page
|
|
10
|
+
* the page reports (input-shape.cjs). On GNOME it is a dock window instead, which goes below every
|
|
11
|
+
* window while one is full screen on its display. When the pet is carried onto
|
|
12
|
+
* another display, the window moves to that display mid-drag; when its display is unplugged, it
|
|
13
|
+
* moves to the primary one. A tray icon shows, hides and closes it; an embedding app that has its
|
|
14
|
+
* own tray passes `tray: false`.
|
|
15
|
+
*
|
|
16
|
+
* On macOS the window shows on every Space and over full-screen apps, the process keeps out of
|
|
17
|
+
* the Dock, and microphone permission is only requested when the page needs it. The keyboard is
|
|
18
|
+
* not taken for a question's number keys there: macOS gives no way to hand it back to the app that had it.
|
|
19
|
+
*
|
|
20
|
+
* The tray's words follow the app language the page reports (`petHost.setLanguage`), from the pages'
|
|
21
|
+
* tables (web/i18n); the windows' titles are the pages' own.
|
|
22
|
+
*/
|
|
23
|
+
const { app, BrowserWindow, Menu, Tray, ipcMain, nativeImage, screen, session, shell, systemPreferences } = require('electron');
|
|
24
|
+
const { mkdirSync } = require('node:fs');
|
|
25
|
+
const { join } = require('node:path');
|
|
26
|
+
const { pathToFileURL } = require('node:url');
|
|
27
|
+
const { createCursorSource } = require('./cursor.cjs');
|
|
28
|
+
const { createInputShape } = require('./input-shape.cjs');
|
|
29
|
+
const { createMouseLease, FORWARD_MOVES } = require('./mouse-lease.cjs');
|
|
30
|
+
const { createOverlaySource } = require('./overlay.cjs');
|
|
31
|
+
const { capturePortrait } = require('./portrait.cjs');
|
|
32
|
+
const { createWindowSource, ledgesFrom, windowsFrom } = require('./windows.cjs');
|
|
33
|
+
const { createAppStoreRule } = require('./app-store.cjs');
|
|
34
|
+
const { watchRenderer } = require('./renderer-gone.cjs');
|
|
35
|
+
|
|
36
|
+
/** A line the World logs as a warning (src/window-host.ts); other lines of this process are logged at debug. */
|
|
37
|
+
const warn = (line) => console.log(`[warn] ${line}`);
|
|
38
|
+
|
|
39
|
+
/** The pages' text table of `code`, falling back as web/i18n.js does. */
|
|
40
|
+
async function pageText(code) {
|
|
41
|
+
const load = async (c) => {
|
|
42
|
+
if (!/^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(c)) return null;
|
|
43
|
+
try { return (await import(pathToFileURL(join(__dirname, '..', 'web', 'i18n', `${c}.js`)).href)).default; } catch { return null; }
|
|
44
|
+
};
|
|
45
|
+
return { ...await load('en'), ...await load(code === 'zh' || code === 'zh-Hant' ? 'zh' : 'en'), ...await load(code) };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Milliseconds between the cursor reports the page gets. On Windows the reports are all the page
|
|
50
|
+
* learns of a cursor moving over the click-through window (see FORWARD_MOVES), so they come at
|
|
51
|
+
* the system timer's default resolution.
|
|
52
|
+
*/
|
|
53
|
+
const CURSOR_EVERY_MS = process.platform === 'win32' ? 15 : 100;
|
|
54
|
+
/** Milliseconds between the reads of the other windows, while the page asks for them. */
|
|
55
|
+
const WINDOWS_EVERY_MS = 700;
|
|
56
|
+
/**
|
|
57
|
+
* Milliseconds between the reads of the foreground window on Windows, for the topmost assertion and the
|
|
58
|
+
* check for a fullscreen window covering the pet's display.
|
|
59
|
+
*/
|
|
60
|
+
const FOREGROUND_EVERY_MS = 200;
|
|
61
|
+
/** Most pixels one backdrop sample returns. */
|
|
62
|
+
const BACKDROP_SAMPLES = 1500;
|
|
63
|
+
/** The Windows message a window gets when the scale of its display changes. */
|
|
64
|
+
const WM_DPICHANGED = 0x02e0;
|
|
65
|
+
/**
|
|
66
|
+
* Whether the desktop is GNOME, by XDG_CURRENT_DESKTOP, XDG_SESSION_DESKTOP or DESKTOP_SESSION. There the pet
|
|
67
|
+
* window is a dock window: mutter's window_would_be_covered() refuses focus to every new window that an
|
|
68
|
+
* always-on-top window overlaps, and the pet window covers the work area.
|
|
69
|
+
*/
|
|
70
|
+
const GNOME = process.platform === 'linux'
|
|
71
|
+
&& ['XDG_CURRENT_DESKTOP', 'XDG_SESSION_DESKTOP', 'DESKTOP_SESSION'].some((name) => /gnome/i.test(process.env[name] ?? ''));
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* GDI calls for copying a small patch of the screen, or null off Windows or when koffi does not
|
|
75
|
+
* load. A patch through BitBlt costs about a millisecond; a desktopCapturer frame of the whole
|
|
76
|
+
* screen stalls the cursor.
|
|
77
|
+
*/
|
|
78
|
+
const gdi = (() => {
|
|
79
|
+
if (process.platform !== 'win32') return null;
|
|
80
|
+
try {
|
|
81
|
+
const koffi = require('koffi');
|
|
82
|
+
const user32 = koffi.load('user32.dll'), gdi32 = koffi.load('gdi32.dll');
|
|
83
|
+
return {
|
|
84
|
+
GetDC: user32.func('void * __stdcall GetDC(void *hwnd)'),
|
|
85
|
+
ReleaseDC: user32.func('int __stdcall ReleaseDC(void *hwnd, void *hdc)'),
|
|
86
|
+
CreateCompatibleDC: gdi32.func('void * __stdcall CreateCompatibleDC(void *hdc)'),
|
|
87
|
+
CreateCompatibleBitmap: gdi32.func('void * __stdcall CreateCompatibleBitmap(void *hdc, int w, int h)'),
|
|
88
|
+
SelectObject: gdi32.func('void * __stdcall SelectObject(void *hdc, void *obj)'),
|
|
89
|
+
StretchBlt: gdi32.func('int __stdcall StretchBlt(void *dst, int dx, int dy, int dw, int dh, void *src, int sx, int sy, int sw, int sh, uint32_t rop)'),
|
|
90
|
+
GetDIBits: gdi32.func('int __stdcall GetDIBits(void *hdc, void *hbm, uint32_t start, uint32_t lines, void *bits, void *bmi, uint32_t usage)'),
|
|
91
|
+
DeleteObject: gdi32.func('int __stdcall DeleteObject(void *obj)'),
|
|
92
|
+
DeleteDC: gdi32.func('int __stdcall DeleteDC(void *hdc)'),
|
|
93
|
+
};
|
|
94
|
+
} catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
})();
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The window with the keyboard, and moving the keyboard between windows while the pet asks
|
|
101
|
+
* something. Windows keeps a background process from bringing its window forward (`win.focus()`
|
|
102
|
+
* alone does nothing), unless its thread shares input with the foreground one for the call. Null off Windows or when koffi does not load.
|
|
103
|
+
*/
|
|
104
|
+
const foreground = (() => {
|
|
105
|
+
if (process.platform !== 'win32') return null;
|
|
106
|
+
try {
|
|
107
|
+
const koffi = require('koffi');
|
|
108
|
+
const user32 = koffi.load('user32.dll'), kernel32 = koffi.load('kernel32.dll');
|
|
109
|
+
const GetForegroundWindow = user32.func('intptr_t __stdcall GetForegroundWindow()');
|
|
110
|
+
const SetForegroundWindow = user32.func('int __stdcall SetForegroundWindow(intptr_t hwnd)');
|
|
111
|
+
const BringWindowToTop = user32.func('int __stdcall BringWindowToTop(intptr_t hwnd)');
|
|
112
|
+
const GetWindowThreadProcessId = user32.func('uint32_t __stdcall GetWindowThreadProcessId(intptr_t hwnd, void *pid)');
|
|
113
|
+
const AttachThreadInput = user32.func('int __stdcall AttachThreadInput(uint32_t from, uint32_t to, int attach)');
|
|
114
|
+
const GetCurrentThreadId = kernel32.func('uint32_t __stdcall GetCurrentThreadId()');
|
|
115
|
+
return {
|
|
116
|
+
/** The window with the keyboard now, 0n for none. */
|
|
117
|
+
current: () => BigInt(GetForegroundWindow()),
|
|
118
|
+
/** Gives `hwnd` the keyboard; true when Windows let it. */
|
|
119
|
+
give(hwnd) {
|
|
120
|
+
const cur = GetForegroundWindow();
|
|
121
|
+
const them = cur ? GetWindowThreadProcessId(cur, null) : 0, me = GetCurrentThreadId();
|
|
122
|
+
const attached = them && them !== me && AttachThreadInput(me, them, 1);
|
|
123
|
+
try {
|
|
124
|
+
BringWindowToTop(hwnd);
|
|
125
|
+
return !!SetForegroundWindow(hwnd);
|
|
126
|
+
} finally {
|
|
127
|
+
if (attached) AttachThreadInput(me, them, 0);
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
} catch {
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
})();
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The screen edge the taskbar waits on while it hides itself ('left', 'top', 'right' or
|
|
138
|
+
* 'bottom'), or null when it does not hide. Every display's taskbar shares the primary one's edge
|
|
139
|
+
* and auto-hide setting. Always null off Windows or when koffi does not load.
|
|
140
|
+
*/
|
|
141
|
+
const autoHideTaskbarEdge = (() => {
|
|
142
|
+
if (process.platform !== 'win32') return () => null;
|
|
143
|
+
try {
|
|
144
|
+
const koffi = require('koffi');
|
|
145
|
+
const shell32 = koffi.load('shell32.dll');
|
|
146
|
+
const RECT = koffi.struct('RECT', { left: 'int32_t', top: 'int32_t', right: 'int32_t', bottom: 'int32_t' });
|
|
147
|
+
const APPBARDATA = koffi.struct('APPBARDATA', { cbSize: 'uint32_t', hWnd: 'void *', uCallbackMessage: 'uint32_t', uEdge: 'uint32_t', rc: RECT, lParam: 'intptr_t' });
|
|
148
|
+
const SHAppBarMessage = shell32.func('uintptr_t __stdcall SHAppBarMessage(uint32_t msg, _Inout_ APPBARDATA *data)');
|
|
149
|
+
const ABM_GETSTATE = 4, ABM_GETTASKBARPOS = 5, ABS_AUTOHIDE = 1;
|
|
150
|
+
const data = () => ({ cbSize: koffi.sizeof(APPBARDATA), hWnd: null, uCallbackMessage: 0, uEdge: 0, rc: { left: 0, top: 0, right: 0, bottom: 0 }, lParam: 0 });
|
|
151
|
+
return () => {
|
|
152
|
+
if (!(Number(SHAppBarMessage(ABM_GETSTATE, data())) & ABS_AUTOHIDE)) return null;
|
|
153
|
+
const pos = data();
|
|
154
|
+
if (!SHAppBarMessage(ABM_GETTASKBARPOS, pos)) return null;
|
|
155
|
+
return ['left', 'top', 'right', 'bottom'][pos.uEdge] ?? null;
|
|
156
|
+
};
|
|
157
|
+
} catch {
|
|
158
|
+
return () => null;
|
|
159
|
+
}
|
|
160
|
+
})();
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* DIP the window keeps off the display edge an auto-hidden taskbar waits on. Windows treats a
|
|
164
|
+
* window covering a whole display as a full-screen app and keeps the taskbar from showing over it;
|
|
165
|
+
* Chromium leaves 2 physical pixels on that edge of a maximized window for this. The display's
|
|
166
|
+
* size in DIP is rounded and Electron rounds a window's far edge outward to whole pixels, so a gap
|
|
167
|
+
* of g DIP comes out as at least (g − ½) × scale pixels rounded down: 3 DIP leaves 2 pixels from
|
|
168
|
+
* 100% up, 2 DIP can leave 1 at 125%.
|
|
169
|
+
*/
|
|
170
|
+
const AUTOHIDE_TASKBAR_GAP = 3;
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* DIP the window stays off the bottom of the display when it reaches down over a taskbar there: a window
|
|
174
|
+
* covering the whole display would be taken for a full-screen app (see AUTOHIDE_TASKBAR_GAP).
|
|
175
|
+
*/
|
|
176
|
+
const OVERHANG_GAP = 3;
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* The part of display `d` the window covers: its work area, off the edge an auto-hidden taskbar waits on.
|
|
180
|
+
* On Windows with `overTaskbar`, over a taskbar at the bottom it reaches down past the work area by `below`
|
|
181
|
+
* DIP, so what a figure draws under the floor (legs hanging over the edge while it sits) shows over the
|
|
182
|
+
* taskbar; the page keeps the floor at the work area's bottom.
|
|
183
|
+
*/
|
|
184
|
+
function coverArea(d, overTaskbar) {
|
|
185
|
+
let { x, y, width, height } = d.workArea;
|
|
186
|
+
const b = d.bounds, edge = autoHideTaskbarEdge(), gap = AUTOHIDE_TASKBAR_GAP;
|
|
187
|
+
// only where the work area reaches that edge of the display
|
|
188
|
+
if (edge === 'left' && x === b.x) { x += gap; width -= gap; }
|
|
189
|
+
if (edge === 'top' && y === b.y) { y += gap; height -= gap; }
|
|
190
|
+
if (edge === 'right' && x + width === b.x + b.width) width -= gap;
|
|
191
|
+
if (edge === 'bottom' && y + height === b.y + b.height) height -= gap;
|
|
192
|
+
const strip = b.y + b.height - (y + height);
|
|
193
|
+
const below = overTaskbar && process.platform === 'win32' ? Math.max(0, strip - OVERHANG_GAP) : 0;
|
|
194
|
+
return { x, y, width, height: height + below, below };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** A window's HWND as a BigInt. */
|
|
198
|
+
function hwndOf(win) {
|
|
199
|
+
const b = win.getNativeWindowHandle();
|
|
200
|
+
return b.length === 8 ? b.readBigInt64LE(0) : BigInt(b.readInt32LE(0));
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Whether the foreground window `hwnd` fills the whole monitor the window `own` is on, as a game, a video
|
|
205
|
+
* or a browser in full screen does. A window still carrying a title bar never counts: a maximized
|
|
206
|
+
* window reaches past the monitor's edges where no taskbar reserves a strip (an auto-hidden one, or
|
|
207
|
+
* none on that monitor), and what tells it apart from a full screen window is that going full screen
|
|
208
|
+
* clears that bar
|
|
209
|
+
* (Chromium keeps the maximized state behind, so the state alone cannot separate the two). Nor do
|
|
210
|
+
* the pet window and the desktop. Null off Windows or when koffi does not load.
|
|
211
|
+
*/
|
|
212
|
+
const fullscreen = (() => {
|
|
213
|
+
if (process.platform !== 'win32') return null;
|
|
214
|
+
try {
|
|
215
|
+
const koffi = require('koffi');
|
|
216
|
+
const user32 = koffi.load('user32.dll');
|
|
217
|
+
const GetWindowLongW = user32.func('int32_t __stdcall GetWindowLongW(intptr_t hwnd, int index)');
|
|
218
|
+
const GetClassNameW = user32.func('int __stdcall GetClassNameW(intptr_t hwnd, void *buf, int max)');
|
|
219
|
+
const GetWindowRect = user32.func('int __stdcall GetWindowRect(intptr_t hwnd, void *rect)');
|
|
220
|
+
const MonitorFromWindow = user32.func('intptr_t __stdcall MonitorFromWindow(intptr_t hwnd, uint32_t flags)');
|
|
221
|
+
const GetMonitorInfoW = user32.func('int __stdcall GetMonitorInfoW(intptr_t monitor, void *info)');
|
|
222
|
+
// MONITORINFO is its own size, the monitor RECT, the work RECT and flags
|
|
223
|
+
const MONITORINFO_BYTES = 40, MONITOR_DEFAULTTONEAREST = 2;
|
|
224
|
+
// going full screen clears the title bar a maximized window keeps
|
|
225
|
+
const GWL_STYLE = -16, WS_CAPTION = 0x00c00000;
|
|
226
|
+
// the desktop's own windows: they cover the monitor but are not an application
|
|
227
|
+
const DESKTOP_CLASSES = new Set(['Progman', 'WorkerW']);
|
|
228
|
+
return (hwnd, own) => {
|
|
229
|
+
if (hwnd === 0n || hwnd === own) return false;
|
|
230
|
+
// a title bar means an ordinary window that happens to reach the monitor's edges, always on top or not
|
|
231
|
+
if ((GetWindowLongW(hwnd, GWL_STYLE) & WS_CAPTION) !== 0) return false;
|
|
232
|
+
const monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
|
|
233
|
+
if (monitor !== MonitorFromWindow(own, MONITOR_DEFAULTTONEAREST)) return false;
|
|
234
|
+
const name = Buffer.alloc(128);
|
|
235
|
+
if (GetClassNameW(hwnd, name, 64) > 0 && DESKTOP_CLASSES.has(name.toString('utf16le').split('\0')[0])) return false;
|
|
236
|
+
const rect = Buffer.alloc(16), info = Buffer.alloc(MONITORINFO_BYTES);
|
|
237
|
+
info.writeUInt32LE(MONITORINFO_BYTES, 0);
|
|
238
|
+
if (!GetWindowRect(hwnd, rect) || !GetMonitorInfoW(monitor, info)) return false;
|
|
239
|
+
return rect.readInt32LE(0) <= info.readInt32LE(4) && rect.readInt32LE(4) <= info.readInt32LE(8)
|
|
240
|
+
&& rect.readInt32LE(8) >= info.readInt32LE(12) && rect.readInt32LE(12) >= info.readInt32LE(16);
|
|
241
|
+
};
|
|
242
|
+
} catch {
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
})();
|
|
246
|
+
|
|
247
|
+
/** `w`×`h` screen pixels from (x, y) in physical pixels, shrunk to `ow`×`oh`, as top-down BGRA. */
|
|
248
|
+
function grabScreen(x, y, w, h, ow, oh) {
|
|
249
|
+
const screenDc = gdi.GetDC(null), memDc = gdi.CreateCompatibleDC(screenDc), bmp = gdi.CreateCompatibleBitmap(screenDc, ow, oh);
|
|
250
|
+
try {
|
|
251
|
+
const old = gdi.SelectObject(memDc, bmp);
|
|
252
|
+
const SRCCOPY = 0x00CC0020;
|
|
253
|
+
const ok = gdi.StretchBlt(memDc, 0, 0, ow, oh, screenDc, x, y, w, h, SRCCOPY);
|
|
254
|
+
gdi.SelectObject(memDc, old);
|
|
255
|
+
if (!ok) return null;
|
|
256
|
+
// BITMAPINFOHEADER: 32-bit, uncompressed, negative height for top-down rows
|
|
257
|
+
const bmi = Buffer.alloc(44);
|
|
258
|
+
bmi.writeUInt32LE(40, 0); bmi.writeInt32LE(ow, 4); bmi.writeInt32LE(-oh, 8); bmi.writeUInt16LE(1, 12); bmi.writeUInt16LE(32, 14);
|
|
259
|
+
const bits = Buffer.alloc(ow * oh * 4);
|
|
260
|
+
return gdi.GetDIBits(memDc, bmp, 0, oh, bits, bmi, 0) === oh ? bits : null;
|
|
261
|
+
} finally {
|
|
262
|
+
gdi.DeleteObject(bmp); gdi.DeleteDC(memDc); gdi.ReleaseDC(null, screenDc);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Screen pixels under `rect`, leaving out those inside any of `skip`; both in page coordinates
|
|
268
|
+
* (DIP, relative to `win`). The pet window may show in the copy, so the page skips its own figure
|
|
269
|
+
* and bubbles. Returns a flat [r, g, b, r, g, b, …] of at most BACKDROP_SAMPLES pixels, [] when
|
|
270
|
+
* this copy failed, or null where the screen cannot be read cheaply at all.
|
|
271
|
+
*/
|
|
272
|
+
function sampleBackdrop(win, { rect, skip = [] }) {
|
|
273
|
+
if (!gdi) return null;
|
|
274
|
+
if (!rect || !(rect.width > 0) || !(rect.height > 0)) return [];
|
|
275
|
+
const b = win.getBounds();
|
|
276
|
+
// physical pixels at the scale of the display the window is on
|
|
277
|
+
const { x, y, width, height } = screen.dipToScreenRect(win, { x: b.x + rect.x, y: b.y + rect.y, width: rect.width, height: rect.height });
|
|
278
|
+
const w = Math.max(1, width), h = Math.max(1, height);
|
|
279
|
+
const step = Math.max(1, Math.sqrt(w * h / BACKDROP_SAMPLES));
|
|
280
|
+
const ow = Math.max(1, Math.round(w / step)), oh = Math.max(1, Math.round(h / step));
|
|
281
|
+
const bits = grabScreen(x, y, w, h, ow, oh);
|
|
282
|
+
if (!bits) return [];
|
|
283
|
+
const out = [];
|
|
284
|
+
for (let j = 0; j < oh; j++) for (let i = 0; i < ow; i++) {
|
|
285
|
+
const px = rect.x + (i + .5) * rect.width / ow, py = rect.y + (j + .5) * rect.height / oh;
|
|
286
|
+
if (skip.some((r) => px >= r.x && px < r.x + r.width && py >= r.y && py < r.y + r.height)) continue;
|
|
287
|
+
const k = (j * ow + i) * 4;
|
|
288
|
+
// BGRA
|
|
289
|
+
out.push(bits[k + 2], bits[k + 1], bits[k]);
|
|
290
|
+
}
|
|
291
|
+
return out;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* 32×32 tray icon drawn in code: the C outline and two ring eyes, white on the brand green; on
|
|
296
|
+
* macOS a black template image the menu bar tints to its own color.
|
|
297
|
+
*/
|
|
298
|
+
function trayIcon() {
|
|
299
|
+
const mac = process.platform === 'darwin';
|
|
300
|
+
const n = 32, buf = Buffer.alloc(n * n * 4);
|
|
301
|
+
const ring = (px, py, cx, cy, r, w) => Math.abs(Math.hypot(px - cx, py - cy) - r) <= w / 2;
|
|
302
|
+
for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {
|
|
303
|
+
const i = (y * n + x) * 4, px = x + .5, py = y + .5;
|
|
304
|
+
const inside = Math.hypot(px - 16, py - 16) <= 15.5;
|
|
305
|
+
const a = Math.atan2(16 - py, px - 16) * 180 / Math.PI;
|
|
306
|
+
const c = ring(px, py, 16, 16, 10.5, 3.6) && Math.abs(a) > 48;
|
|
307
|
+
const eye = ring(px, py, 14.1, 14.6, 2.2, 1.5) || ring(px, py, 20.4, 14.6, 2.2, 1.5);
|
|
308
|
+
const white = c || eye;
|
|
309
|
+
// BGRA
|
|
310
|
+
if (mac) { buf[i] = buf[i + 1] = buf[i + 2] = 0; buf[i + 3] = white ? 255 : 0; continue; }
|
|
311
|
+
buf[i] = white ? 255 : 0x70; buf[i + 1] = white ? 255 : 0xA8; buf[i + 2] = white ? 255 : 0x00; buf[i + 3] = inside ? 255 : 0;
|
|
312
|
+
}
|
|
313
|
+
const img = nativeImage.createFromBitmap(buf, { width: n, height: n, scaleFactor: mac ? 2 : 1 });
|
|
314
|
+
if (mac) img.setTemplateImage(true);
|
|
315
|
+
return img;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function runPetHost({ url, parentPid = 0, tray: withTray = true }) {
|
|
319
|
+
if (!url) throw new Error('pet host needs --pet-url');
|
|
320
|
+
const origin = new URL(url).origin;
|
|
321
|
+
/** Whether `target` is a page of the World's own server, by its parsed origin. */
|
|
322
|
+
const ours = (target) => { try { return new URL(target).origin === origin; } catch { return false; } };
|
|
323
|
+
/**
|
|
324
|
+
* A window the host opens shows only the World's pages: a link to one opens the dressing window,
|
|
325
|
+
* an http(s) link goes to the browser, anything else is dropped, and the window never navigates
|
|
326
|
+
* away (a link dropped on it included).
|
|
327
|
+
*/
|
|
328
|
+
const guard = (wc) => {
|
|
329
|
+
wc.setWindowOpenHandler(({ url: target }) => {
|
|
330
|
+
if (ours(target)) openDress(target);
|
|
331
|
+
else if (/^https?:\/\//i.test(target)) void shell.openExternal(target);
|
|
332
|
+
return { action: 'deny' };
|
|
333
|
+
});
|
|
334
|
+
wc.on('will-navigate', (e, target) => { if (!ours(target)) e.preventDefault(); });
|
|
335
|
+
};
|
|
336
|
+
/** IPC from the pet window's own page only; the preload is loaded nowhere else. */
|
|
337
|
+
const fromPet = (e) => !!win && e.sender === win.webContents && ours(e.senderFrame?.url ?? '');
|
|
338
|
+
const onPet = (channel, fn) => ipcMain.on(channel, (e, ...args) => { if (fromPet(e)) fn(e, ...args); });
|
|
339
|
+
const handlePet = (channel, fn) => ipcMain.handle(channel, (e, ...args) => (fromPet(e) ? fn(e, ...args) : null));
|
|
340
|
+
let win = null, tray = null, dress = null, cursor;
|
|
341
|
+
// in a Wayland session the window takes the mouse over the rects the page reports, elsewhere as a whole
|
|
342
|
+
const shape = createInputShape({ screen });
|
|
343
|
+
app.once('will-quit', () => shape?.close());
|
|
344
|
+
// who holds the mouse, and when it is given back
|
|
345
|
+
const mouse = createMouseLease({ getWindow: () => win, shape });
|
|
346
|
+
// the window as an OBS layer, while the World asks for it
|
|
347
|
+
const key = new URLSearchParams(new URL(url).hash.slice(1)).get('key');
|
|
348
|
+
const overlay = createOverlaySource({ origin, key, getWindow: () => win });
|
|
349
|
+
app.once('will-quit', () => overlay.stop());
|
|
350
|
+
/** Id of the display whose work area the window covers. */
|
|
351
|
+
let displayId = null;
|
|
352
|
+
/** The settings, and whether the first is what hid the window. */
|
|
353
|
+
let hideWhenFullscreen = false, autoHidden = false, passWhenFullscreen = false;
|
|
354
|
+
/** The setting that fades the pet during full screen, and whether it holds now, as last told to the page. */
|
|
355
|
+
let fadeWhenFullscreen = false, fullscreenFaded = false;
|
|
356
|
+
/** The setting: the window reaches down over a taskbar at the bottom (see coverArea). */
|
|
357
|
+
let overTaskbar = true;
|
|
358
|
+
/**
|
|
359
|
+
* Every click passes through while the tray says so or the second setting meets a fullscreen window,
|
|
360
|
+
* except while the page lends them to the pet (the click-through pause key held, the typing box open).
|
|
361
|
+
*/
|
|
362
|
+
let trayThrough = false, fullscreenThrough = false, clicksLent = false;
|
|
363
|
+
const lockMouse = () => mouse.lock((trayThrough || fullscreenThrough) && !clicksLent);
|
|
364
|
+
// the other windows, read only while the page asks (its body's pack needs them) and sent when they change:
|
|
365
|
+
// their tops, and the whole windows with their ids, order and foreground flag
|
|
366
|
+
const windows = createWindowSource({ screen });
|
|
367
|
+
let windowTimer = null, sentWindows = '';
|
|
368
|
+
const readWindows = () => {
|
|
369
|
+
if (!win || !win.isVisible() || win.webContents.isCrashed()) return;
|
|
370
|
+
const rects = windows.list(hwndOf(win));
|
|
371
|
+
const b = win.getBounds();
|
|
372
|
+
// the page's floor: 2 DIP above the bottom of the work area (web/pet-app.js floorGap)
|
|
373
|
+
const origin = { x: b.x, y: b.y }, view = { width: b.width, floor: b.height - 2 - coverArea(display(), overTaskbar).below };
|
|
374
|
+
const desk = rects && { ledges: ledgesFrom(rects, origin, view), windows: windowsFrom(rects, origin, view) };
|
|
375
|
+
const json = JSON.stringify(desk);
|
|
376
|
+
if (json === sentWindows) return;
|
|
377
|
+
sentWindows = json;
|
|
378
|
+
win.webContents.send('pet:windows', desk);
|
|
379
|
+
};
|
|
380
|
+
const watchWindows = (on) => {
|
|
381
|
+
clearInterval(windowTimer);
|
|
382
|
+
windowTimer = null;
|
|
383
|
+
sentWindows = '';
|
|
384
|
+
if (on && windows.available) { windowTimer = setInterval(readWindows, WINDOWS_EVERY_MS); readWindows(); }
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
/** The display the window belongs on: the one it was moved to, or the primary display once that one is gone. */
|
|
388
|
+
const display = () => screen.getAllDisplays().find((d) => d.id === displayId) ?? screen.getPrimaryDisplay();
|
|
389
|
+
|
|
390
|
+
/** Moves the window over display `d`; returns the area it now covers. `reset`: see rescaled below. */
|
|
391
|
+
const cover = (d, reset = false) => {
|
|
392
|
+
const from = screen.getDisplayMatching(win.getBounds());
|
|
393
|
+
displayId = d.id;
|
|
394
|
+
const area = coverArea(d, overTaskbar), { below, ...rect } = area;
|
|
395
|
+
// Windows: setBounds converts the rect with the scale of the display the window is on. Onto a
|
|
396
|
+
// display with another scale the window comes out sized for the old one, can reach back over it
|
|
397
|
+
// and stay counted on it, so setting the rect again changes nothing. A 1x1 window at the new
|
|
398
|
+
// origin lies wholly on the new display, and the rect set after it holds. The same goes for a new
|
|
399
|
+
// scale on the window's own display.
|
|
400
|
+
if (process.platform === 'win32' && (reset || (from.id !== d.id && from.scaleFactor !== d.scaleFactor))) {
|
|
401
|
+
win.setBounds({ x: rect.x, y: rect.y, width: 1, height: 1 });
|
|
402
|
+
}
|
|
403
|
+
win.setBounds(rect);
|
|
404
|
+
// where the floor is: the page keeps it this far above the window's bottom
|
|
405
|
+
win.webContents.send('pet:floor', below);
|
|
406
|
+
return area;
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
const place = () => { if (win) cover(display()); };
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Windows: when the scale of the window's display changes, the window resizes itself to the rect
|
|
413
|
+
* WM_DPICHANGED suggests (its size times the ratio of the two scales), and setBounds changes nothing
|
|
414
|
+
* until display-metrics-changed has also come for the new scale. Whichever of the two comes last
|
|
415
|
+
* places the window again. `metricsScale`: the scale display-metrics-changed last saw.
|
|
416
|
+
*/
|
|
417
|
+
let metricsScale = null, dpiChanged = false;
|
|
418
|
+
const rescaled = (from) => {
|
|
419
|
+
if (from === 'dpi') dpiChanged = true;
|
|
420
|
+
else metricsScale = display().scaleFactor;
|
|
421
|
+
if (!dpiChanged || metricsScale !== display().scaleFactor) { if (from === 'metrics') place(); return; }
|
|
422
|
+
dpiChanged = false;
|
|
423
|
+
setTimeout(() => { if (win) cover(display(), true); }, 0);
|
|
424
|
+
};
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* A hand showed or hid the window, so the fullscreen rule no longer owns it: a manual show while
|
|
428
|
+
* the rule still believed it had hidden the window would keep the rule from hiding it again.
|
|
429
|
+
*/
|
|
430
|
+
const releaseAutoHidden = () => { autoHidden = false; };
|
|
431
|
+
|
|
432
|
+
const create = () => {
|
|
433
|
+
const d = display(), wa = coverArea(d, overTaskbar);
|
|
434
|
+
win = new BrowserWindow({
|
|
435
|
+
x: wa.x, y: wa.y, width: wa.width, height: wa.height,
|
|
436
|
+
transparent: true, frame: false, resizable: false, movable: false, minimizable: false, maximizable: false,
|
|
437
|
+
fullscreenable: false, skipTaskbar: true, hasShadow: false, show: false,
|
|
438
|
+
...(GNOME ? { type: 'dock' } : { alwaysOnTop: true }),
|
|
439
|
+
backgroundColor: '#00000000', title: 'Cortico',
|
|
440
|
+
// Windows: Chromium-based apps treat a topmost window without WS_EX_TOOLWINDOW as covering them and stop painting while the pet takes the mouse
|
|
441
|
+
...(process.platform === 'win32' ? { type: 'toolbar' } : {}),
|
|
442
|
+
webPreferences: {
|
|
443
|
+
preload: join(__dirname, 'preload.cjs'),
|
|
444
|
+
contextIsolation: true, sandbox: true, backgroundThrottling: false,
|
|
445
|
+
autoplayPolicy: 'no-user-gesture-required',
|
|
446
|
+
},
|
|
447
|
+
});
|
|
448
|
+
cover(d);
|
|
449
|
+
// Native candidate windows and Chromium popups must remain above the pet.
|
|
450
|
+
const level = process.platform === 'darwin' ? 'floating' : 'screen-saver';
|
|
451
|
+
if (!GNOME) win.setAlwaysOnTop(true, level);
|
|
452
|
+
// macOS: behind the other windows while App Store is the active application
|
|
453
|
+
const appStore = createAppStoreRule({ window: win, level });
|
|
454
|
+
// on every Space, and over an app in full screen
|
|
455
|
+
if (process.platform === 'darwin') win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true, skipTransformProcessType: true });
|
|
456
|
+
win.setIgnoreMouseEvents(true, { forward: FORWARD_MOVES });
|
|
457
|
+
guard(win.webContents);
|
|
458
|
+
win.once('ready-to-show', () => win.showInactive());
|
|
459
|
+
if (process.platform === 'win32') {
|
|
460
|
+
metricsScale = display().scaleFactor;
|
|
461
|
+
win.hookWindowMessage(WM_DPICHANGED, () => rescaled('dpi'));
|
|
462
|
+
}
|
|
463
|
+
// The page cannot tell for itself that it is hidden (background throttling is off, so it always reads as
|
|
464
|
+
// visible and keeps getting frames): the window tells it, so it stops drawing, and for the settings window's
|
|
465
|
+
// 「在桌面上 / 已隐藏」.
|
|
466
|
+
win.on('show', () => win?.webContents.send('pet:shown', true));
|
|
467
|
+
win.on('hide', () => { win?.webContents.send('pet:shown', false); mouse.release(); });
|
|
468
|
+
// Zoom stays at 1: the cursor below is sent in DIPs and the page hit-tests with them as CSS pixels,
|
|
469
|
+
// so any zoom flips the window between click-through and interactive. A drawing tablet's shortcut
|
|
470
|
+
// keys are a keyboard and can send Ctrl+- to the focused pet, and the zoom is saved per host.
|
|
471
|
+
win.webContents.on('before-input-event', (event, input) => {
|
|
472
|
+
if ((input.control || input.meta) && (['-', '_', '=', '+', '0'].includes(input.key) || ['NumpadAdd', 'NumpadSubtract', 'Numpad0'].includes(input.code))) event.preventDefault();
|
|
473
|
+
});
|
|
474
|
+
// a page loaded afresh asks for the windows again once its body is on
|
|
475
|
+
win.webContents.on('did-finish-load', () => {
|
|
476
|
+
win.webContents.setZoomLevel(0); overlay.pageLoaded(); watchWindows(false); win.webContents.send('pet:floor', coverArea(display(), overTaskbar).below);
|
|
477
|
+
// a page loaded afresh lends no clicks until it says so
|
|
478
|
+
if (clicksLent) { clicksLent = false; lockMouse(); }
|
|
479
|
+
win.webContents.send('pet:fullscreenThrough', fullscreenThrough);
|
|
480
|
+
win.webContents.send('pet:fullscreenFade', fullscreenFaded);
|
|
481
|
+
if (shape) win.webContents.send('pet:inputShape', true);
|
|
482
|
+
});
|
|
483
|
+
// The page learns where the cursor is even when the click-through window misses its moves, and
|
|
484
|
+
// it renews the mouse lease in its answer to every report: the report goes out on every tick,
|
|
485
|
+
// not only when the pointer moved, so a cursor that rests still still gets a verdict.
|
|
486
|
+
let lastVisible = null;
|
|
487
|
+
const cursorTimer = setInterval(() => {
|
|
488
|
+
if (!win) return;
|
|
489
|
+
const visible = win.isVisible();
|
|
490
|
+
// the input shape does not survive the window being mapped: apply the verdict again
|
|
491
|
+
if (visible !== lastVisible) { lastVisible = visible; mouse.forget(); }
|
|
492
|
+
// a page whose renderer ended has no frame to send to until it loads again
|
|
493
|
+
if (!visible || win.webContents.isCrashed()) { mouse.tick(); return; }
|
|
494
|
+
const pt = cursor.read(), b = win.getBounds();
|
|
495
|
+
const inside = pt.x >= b.x && pt.x < b.x + b.width && pt.y >= b.y && pt.y < b.y + b.height;
|
|
496
|
+
const at = inside ? { x: pt.x - b.x, y: pt.y - b.y } : null;
|
|
497
|
+
win.webContents.send('pet:cursor', at);
|
|
498
|
+
mouse.tick();
|
|
499
|
+
}, CURSOR_EVERY_MS);
|
|
500
|
+
// Windows: every topmost window shares one band ordered by activation, so a topmost window that takes
|
|
501
|
+
// the foreground (a borderless full screen game) goes over the pet. The pet asserts topmost again each
|
|
502
|
+
// time another window takes the foreground, and on the first tick it is shown. While the foreground
|
|
503
|
+
// window fills the pet's monitor: hidden with the first setting on, shown again once that ends; with the
|
|
504
|
+
// second, every click passes through and the page is told so; with the third, the page is told it is covered.
|
|
505
|
+
let lastForeground = null;
|
|
506
|
+
const foregroundTimer = foreground && setInterval(() => {
|
|
507
|
+
if (!win) return;
|
|
508
|
+
const own = hwndOf(win), cur = foreground.current();
|
|
509
|
+
const covered = (hideWhenFullscreen || passWhenFullscreen || fadeWhenFullscreen) && !!fullscreen?.(cur, own);
|
|
510
|
+
if (covered && hideWhenFullscreen && !autoHidden && win.isVisible()) { autoHidden = true; win.hide(); }
|
|
511
|
+
else if (!(covered && hideWhenFullscreen) && autoHidden) { autoHidden = false; win.showInactive(); }
|
|
512
|
+
const through = covered && passWhenFullscreen;
|
|
513
|
+
if (through !== fullscreenThrough) { fullscreenThrough = through; lockMouse(); win.webContents.send('pet:fullscreenThrough', through); }
|
|
514
|
+
const faded = covered && fadeWhenFullscreen;
|
|
515
|
+
if (faded !== fullscreenFaded) { fullscreenFaded = faded; win.webContents.send('pet:fullscreenFade', faded); }
|
|
516
|
+
if (!win.isVisible()) { lastForeground = null; return; }
|
|
517
|
+
if (cur === lastForeground) return;
|
|
518
|
+
lastForeground = cur;
|
|
519
|
+
if (cur !== own) win.setAlwaysOnTop(true, level);
|
|
520
|
+
}, FOREGROUND_EVERY_MS);
|
|
521
|
+
win.on('closed', () => { appStore?.stop(); clearInterval(cursorTimer); clearInterval(foregroundTimer); watchWindows(false); win = null; });
|
|
522
|
+
// page console lines reach the World's log through stdout
|
|
523
|
+
win.webContents.on('console-message', (e) => { if (e.level !== 'debug') console.log(`[page:${e.level}] ${e.message}`); });
|
|
524
|
+
win.webContents.on('did-fail-load', (_e, code, desc, failedUrl) => console.log(`[page:error] 加载失败 ${code} ${desc} ${failedUrl}`));
|
|
525
|
+
watchRenderer(win.webContents, { name: '桌宠窗口', log: warn });
|
|
526
|
+
win.loadURL(url);
|
|
527
|
+
};
|
|
528
|
+
|
|
529
|
+
const openDress = (target = `${origin}/dress`) => {
|
|
530
|
+
if (dress) { dress.show(); dress.focus(); return; }
|
|
531
|
+
dress = new BrowserWindow({ width: 980, height: 720, title: 'Cortico', autoHideMenuBar: true, webPreferences: { contextIsolation: true, sandbox: true } });
|
|
532
|
+
guard(dress.webContents);
|
|
533
|
+
watchRenderer(dress.webContents, { name: '装扮窗口', log: warn });
|
|
534
|
+
dress.on('closed', () => { dress = null; });
|
|
535
|
+
dress.loadURL(target);
|
|
536
|
+
};
|
|
537
|
+
|
|
538
|
+
onPet('pet:interactive', (_e, on) => { if (!shape) mouse.ask(on); });
|
|
539
|
+
onPet('pet:inputRects', (_e, rects) => { if (shape && Array.isArray(rects)) mouse.ask(rects); });
|
|
540
|
+
onPet('pet:focus', () => {
|
|
541
|
+
if (!win) return;
|
|
542
|
+
// Explicit text input activates this menu-bar process as well as its window.
|
|
543
|
+
if (process.platform === 'darwin') app.focus({ steal: true });
|
|
544
|
+
win.focus();
|
|
545
|
+
});
|
|
546
|
+
/** The window that had the keyboard before a question took it; it gets it back afterwards. */
|
|
547
|
+
let lent = 0n;
|
|
548
|
+
onPet('pet:grabFocus', () => {
|
|
549
|
+
if (!win || !win.isVisible() || process.platform === 'darwin') return;
|
|
550
|
+
if (foreground) {
|
|
551
|
+
const own = hwndOf(win), cur = foreground.current();
|
|
552
|
+
if (cur !== own && foreground.give(own)) lent = cur;
|
|
553
|
+
}
|
|
554
|
+
win.focus();
|
|
555
|
+
});
|
|
556
|
+
onPet('pet:releaseFocus', () => {
|
|
557
|
+
const back = lent;
|
|
558
|
+
lent = 0n;
|
|
559
|
+
if (!win) return;
|
|
560
|
+
// someone clicked elsewhere meanwhile: the keyboard is already where they want it
|
|
561
|
+
if (foreground) { if (back && foreground.current() === hwndOf(win)) foreground.give(back); }
|
|
562
|
+
else if (win.isFocused()) win.blur();
|
|
563
|
+
});
|
|
564
|
+
onPet('pet:hide', () => { releaseAutoHidden(); if (win) win.hide(); });
|
|
565
|
+
onPet('pet:overlayFrame', (_e, rect, at) => overlay.frame(rect, at));
|
|
566
|
+
onPet('pet:hideWhenFullscreen', (_e, on) => { hideWhenFullscreen = !!on; });
|
|
567
|
+
onPet('pet:passWhenFullscreen', (_e, on) => { passWhenFullscreen = !!on; });
|
|
568
|
+
onPet('pet:fadeWhenFullscreen', (_e, on) => { fadeWhenFullscreen = !!on; });
|
|
569
|
+
onPet('pet:overTaskbar', (_e, on) => { if (overTaskbar !== !!on) { overTaskbar = !!on; place(); } });
|
|
570
|
+
// Windows: WDA_EXCLUDEFROMCAPTURE, which leaves the window out of what other programs capture of the screen
|
|
571
|
+
onPet('pet:hideFromCapture', (_e, on) => win.setContentProtection(!!on));
|
|
572
|
+
onPet('pet:clickThrough', (_e, on) => { trayThrough = !!on; lockMouse(); });
|
|
573
|
+
onPet('pet:lendClicks', (_e, on) => { clicksLent = !!on; lockMouse(); });
|
|
574
|
+
onPet('pet:watchWindows', (_e, on) => watchWindows(!!on));
|
|
575
|
+
onPet('pet:openDress', () => openDress());
|
|
576
|
+
let language = 'zh';
|
|
577
|
+
onPet('pet:language', (_e, code) => {
|
|
578
|
+
if (typeof code !== 'string' || code === language) return;
|
|
579
|
+
language = code;
|
|
580
|
+
void buildTrayMenu();
|
|
581
|
+
});
|
|
582
|
+
handlePet('pet:sampleBackdrop', (_e, query) => {
|
|
583
|
+
try { return win ? sampleBackdrop(win, query || {}) : []; } catch { return []; }
|
|
584
|
+
});
|
|
585
|
+
// a hidden window is not drawn: there is nothing to take a picture of
|
|
586
|
+
handlePet('pet:portrait', async (_e, rect) => {
|
|
587
|
+
try { return win && win.isVisible() ? await capturePortrait(win, rect, nativeImage) : null; } catch { return null; }
|
|
588
|
+
});
|
|
589
|
+
/** The display under the cursor, when it is not the one the window covers. */
|
|
590
|
+
const otherDisplay = () => {
|
|
591
|
+
const pt = cursor.read(), d = screen.getDisplayNearestPoint(pt);
|
|
592
|
+
return d.id === display().id ? null : { pt, d };
|
|
593
|
+
};
|
|
594
|
+
handlePet('pet:cursorElsewhere', () => !!win && !!otherDisplay());
|
|
595
|
+
/**
|
|
596
|
+
* A drag carried or let go of outside the window: when the cursor is over another display, the
|
|
597
|
+
* window moves there and the page gets the cursor's spot in its new coordinates, its new size, and
|
|
598
|
+
* how far a point on screen moved in page coordinates (`dx`, `dy`); null leaves it where it is.
|
|
599
|
+
*/
|
|
600
|
+
handlePet('pet:followCursor', () => {
|
|
601
|
+
const other = win && otherDisplay();
|
|
602
|
+
if (!other) return null;
|
|
603
|
+
const { pt, d } = other, fromDisplay = display();
|
|
604
|
+
const from = coverArea(fromDisplay, overTaskbar), wa = cover(d);
|
|
605
|
+
return { x: pt.x - wa.x, y: pt.y - wa.y, w: wa.width, h: wa.height, dx: from.x - wa.x, dy: from.y - wa.y };
|
|
606
|
+
});
|
|
607
|
+
|
|
608
|
+
// a pet is not an app to switch to
|
|
609
|
+
if (process.platform === 'darwin') app.dock?.hide();
|
|
610
|
+
app.whenReady().then(async () => {
|
|
611
|
+
cursor = createCursorSource({ screen });
|
|
612
|
+
app.once('will-quit', () => cursor.close());
|
|
613
|
+
session.defaultSession.setPermissionRequestHandler((wc, permission, done) => {
|
|
614
|
+
if (permission !== 'media' || !ours(wc.getURL())) return done(false);
|
|
615
|
+
if (process.platform === 'darwin' && systemPreferences.getMediaAccessStatus('microphone') === 'not-determined') {
|
|
616
|
+
void systemPreferences.askForMediaAccess('microphone').then(done, () => done(false));
|
|
617
|
+
} else done(true);
|
|
618
|
+
});
|
|
619
|
+
// requestingOrigin ends with '/'; a check that fails leaves the page one input with no id or label
|
|
620
|
+
session.defaultSession.setPermissionCheckHandler((wc, permission, requestingOrigin) => permission === 'media' && ours(requestingOrigin));
|
|
621
|
+
create();
|
|
622
|
+
screen.on('display-metrics-changed', () => (process.platform === 'win32' ? rescaled('metrics') : place()));
|
|
623
|
+
screen.on('display-added', place);
|
|
624
|
+
screen.on('display-removed', place);
|
|
625
|
+
if (!withTray) return;
|
|
626
|
+
tray = new Tray(trayIcon());
|
|
627
|
+
await buildTrayMenu();
|
|
628
|
+
tray.on('click', () => { if (win) { releaseAutoHidden(); (win.isVisible() ? win.hide() : win.showInactive()); } });
|
|
629
|
+
});
|
|
630
|
+
/** The tray's tooltip and menu in the language the page last reported. */
|
|
631
|
+
async function buildTrayMenu() {
|
|
632
|
+
if (!tray) return;
|
|
633
|
+
const want = language, t = await pageText(want);
|
|
634
|
+
if (want !== language || !tray) return;
|
|
635
|
+
tray.setToolTip('Agent Speed');
|
|
636
|
+
tray.setContextMenu(Menu.buildFromTemplate([
|
|
637
|
+
{ label: t['host.show'], click: () => { releaseAutoHidden(); if (!win) create(); else win.showInactive(); } },
|
|
638
|
+
{ label: t['host.hide'], click: () => { releaseAutoHidden(); if (win) win.hide(); } },
|
|
639
|
+
{ label: t['host.dress'], click: () => openDress() },
|
|
640
|
+
{ type: 'separator' },
|
|
641
|
+
{ label: t['host.close'], click: () => app.quit() },
|
|
642
|
+
]));
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
app.on('window-all-closed', () => { if (!tray) app.quit(); });
|
|
646
|
+
// with --parent-pid the window closes once that process is gone
|
|
647
|
+
if (parentPid) {
|
|
648
|
+
setInterval(() => {
|
|
649
|
+
try { process.kill(parentPid, 0); } catch { app.quit(); }
|
|
650
|
+
}, 2000).unref();
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
module.exports = { runPetHost };
|
|
655
|
+
|
|
656
|
+
// Electron's default app loads the script without making it require.main
|
|
657
|
+
if (process.argv[1] && require('node:path').resolve(process.argv[1]) === __filename) {
|
|
658
|
+
// Do not reuse either Coopanion's profile or the generic Electron profile.
|
|
659
|
+
app.setName('Agent Speed Pet');
|
|
660
|
+
const profile = join(app.getPath('appData'), 'Agent Speed Pet');
|
|
661
|
+
mkdirSync(profile, { recursive: true });
|
|
662
|
+
app.setPath('userData', profile);
|
|
663
|
+
const arg = process.argv.find((a) => a.startsWith('--pet-url='));
|
|
664
|
+
const parent = process.argv.find((a) => a.startsWith('--parent-pid='));
|
|
665
|
+
runPetHost({ url: arg ? arg.slice('--pet-url='.length) : '', parentPid: parent ? Number(parent.slice('--parent-pid='.length)) : 0 });
|
|
666
|
+
}
|