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,299 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Win32 access through koffi: screen capture (GDI BitBlt with CAPTUREBLT, so layered and
|
|
3
|
+
* transparent windows are included), SendInput for mouse and keyboard, the top-level window
|
|
4
|
+
* list, focusing a window, and the last-input tick used to notice the user.
|
|
5
|
+
*
|
|
6
|
+
* Coordinates are physical pixels of the virtual screen: the primary display's top-left corner is
|
|
7
|
+
* (0, 0), displays left of or above it are negative. The process declares itself per-monitor DPI
|
|
8
|
+
* aware (v2) before anything else, so no API here returns scaled values.
|
|
9
|
+
* This module runs only inside the engine child process.
|
|
10
|
+
*/
|
|
11
|
+
import koffi from 'koffi';
|
|
12
|
+
import { EngineFailure } from './fail.ts';
|
|
13
|
+
import type { NativeDisplay } from './display.ts';
|
|
14
|
+
import type { ForegroundWindow } from './foreground.ts';
|
|
15
|
+
|
|
16
|
+
const user32 = koffi.load('user32.dll');
|
|
17
|
+
const gdi32 = koffi.load('gdi32.dll');
|
|
18
|
+
const kernel32 = koffi.load('kernel32.dll');
|
|
19
|
+
const dwmapi = koffi.load('dwmapi.dll');
|
|
20
|
+
|
|
21
|
+
koffi.alias('HANDLE', 'void *');
|
|
22
|
+
koffi.alias('HWND', 'HANDLE');
|
|
23
|
+
|
|
24
|
+
const POINT = koffi.struct('POINT', { x: 'long', y: 'long' });
|
|
25
|
+
const RECT = koffi.struct('RECT', { left: 'long', top: 'long', right: 'long', bottom: 'long' });
|
|
26
|
+
const LASTINPUTINFO = koffi.struct('LASTINPUTINFO', { cbSize: 'uint32_t', dwTime: 'uint32_t' });
|
|
27
|
+
const BITMAPINFOHEADER = koffi.struct('BITMAPINFOHEADER', {
|
|
28
|
+
biSize: 'uint32_t', biWidth: 'int32_t', biHeight: 'int32_t', biPlanes: 'uint16_t', biBitCount: 'uint16_t',
|
|
29
|
+
biCompression: 'uint32_t', biSizeImage: 'uint32_t', biXPelsPerMeter: 'int32_t', biYPelsPerMeter: 'int32_t',
|
|
30
|
+
biClrUsed: 'uint32_t', biClrImportant: 'uint32_t',
|
|
31
|
+
});
|
|
32
|
+
const MOUSEINPUT = koffi.struct('MOUSEINPUT', { dx: 'long', dy: 'long', mouseData: 'uint32_t', dwFlags: 'uint32_t', time: 'uint32_t', dwExtraInfo: 'uintptr_t' });
|
|
33
|
+
const KEYBDINPUT = koffi.struct('KEYBDINPUT', { wVk: 'uint16_t', wScan: 'uint16_t', dwFlags: 'uint32_t', time: 'uint32_t', dwExtraInfo: 'uintptr_t' });
|
|
34
|
+
const HARDWAREINPUT = koffi.struct('HARDWAREINPUT', { uMsg: 'uint32_t', wParamL: 'uint16_t', wParamH: 'uint16_t' });
|
|
35
|
+
const INPUT = koffi.struct('INPUT', { type: 'uint32_t', u: koffi.union({ mi: MOUSEINPUT, ki: KEYBDINPUT, hi: HARDWAREINPUT }) });
|
|
36
|
+
const MONITORINFOEXW = koffi.struct('MONITORINFOEXW', { cbSize: 'uint32_t', rcMonitor: RECT, rcWork: RECT, dwFlags: 'uint32_t', szDevice: koffi.array('char16_t', 32, 'String') });
|
|
37
|
+
const MonitorEnumProc = koffi.proto('bool __stdcall MonitorEnumProc(HANDLE monitor, HANDLE dc, void *rect, intptr_t data)');
|
|
38
|
+
const EnumWindowsProc = koffi.proto('bool __stdcall EnumWindowsProc(HWND hwnd, intptr_t lParam)');
|
|
39
|
+
|
|
40
|
+
const SetProcessDpiAwarenessContext = user32.func('bool __stdcall SetProcessDpiAwarenessContext(intptr_t value)');
|
|
41
|
+
const EnumDisplayMonitors = user32.func('bool __stdcall EnumDisplayMonitors(HANDLE dc, void *clip, MonitorEnumProc *cb, intptr_t data)');
|
|
42
|
+
const GetMonitorInfoW = user32.func('bool __stdcall GetMonitorInfoW(HANDLE monitor, _Inout_ MONITORINFOEXW *info)');
|
|
43
|
+
const SetCursorPos = user32.func('bool __stdcall SetCursorPos(int x, int y)');
|
|
44
|
+
const GetDC = user32.func('HANDLE __stdcall GetDC(HWND hwnd)');
|
|
45
|
+
const ReleaseDC = user32.func('int __stdcall ReleaseDC(HWND hwnd, HANDLE dc)');
|
|
46
|
+
const CreateCompatibleDC = gdi32.func('HANDLE __stdcall CreateCompatibleDC(HANDLE dc)');
|
|
47
|
+
const CreateCompatibleBitmap = gdi32.func('HANDLE __stdcall CreateCompatibleBitmap(HANDLE dc, int w, int h)');
|
|
48
|
+
const SelectObject = gdi32.func('HANDLE __stdcall SelectObject(HANDLE dc, HANDLE obj)');
|
|
49
|
+
const DeleteObject = gdi32.func('bool __stdcall DeleteObject(HANDLE obj)');
|
|
50
|
+
const DeleteDC = gdi32.func('bool __stdcall DeleteDC(HANDLE dc)');
|
|
51
|
+
const BitBlt = gdi32.func('bool __stdcall BitBlt(HANDLE dst, int x, int y, int w, int h, HANDLE src, int sx, int sy, uint32_t rop)');
|
|
52
|
+
const GetDIBits = gdi32.func('int __stdcall GetDIBits(HANDLE dc, HANDLE bmp, uint32_t start, uint32_t lines, void *bits, _Inout_ BITMAPINFOHEADER *bmi, uint32_t usage)');
|
|
53
|
+
const GetCursorPos = user32.func('bool __stdcall GetCursorPos(_Out_ POINT *p)');
|
|
54
|
+
const SendInput = user32.func('uint32_t __stdcall SendInput(uint32_t count, INPUT *inputs, int size)');
|
|
55
|
+
const GetLastInputInfo = user32.func('bool __stdcall GetLastInputInfo(_Inout_ LASTINPUTINFO *info)');
|
|
56
|
+
const GetTickCount = kernel32.func('uint32_t __stdcall GetTickCount()');
|
|
57
|
+
const EnumWindows = user32.func('bool __stdcall EnumWindows(EnumWindowsProc *cb, intptr_t lParam)');
|
|
58
|
+
const IsWindowVisible = user32.func('bool __stdcall IsWindowVisible(HWND hwnd)');
|
|
59
|
+
const IsIconic = user32.func('bool __stdcall IsIconic(HWND hwnd)');
|
|
60
|
+
const GetWindowTextW = user32.func('int __stdcall GetWindowTextW(HWND hwnd, _Out_ uint16_t *buf, int max)');
|
|
61
|
+
const GetWindowRect = user32.func('bool __stdcall GetWindowRect(HWND hwnd, _Out_ RECT *rect)');
|
|
62
|
+
const GetWindowLongPtrW = user32.func('intptr_t __stdcall GetWindowLongPtrW(HWND hwnd, int index)');
|
|
63
|
+
const GetWindowThreadProcessId = user32.func('uint32_t __stdcall GetWindowThreadProcessId(HWND hwnd, _Out_ uint32_t *pid)');
|
|
64
|
+
const OpenProcess = kernel32.func('HANDLE __stdcall OpenProcess(uint32_t access, bool inherit, uint32_t pid)');
|
|
65
|
+
const QueryFullProcessImageNameW = kernel32.func('bool __stdcall QueryFullProcessImageNameW(HANDLE process, uint32_t flags, _Out_ uint16_t *name, _Inout_ uint32_t *size)');
|
|
66
|
+
const CloseHandle = kernel32.func('bool __stdcall CloseHandle(HANDLE handle)');
|
|
67
|
+
const PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
|
|
68
|
+
const GetForegroundWindow = user32.func('HWND __stdcall GetForegroundWindow()');
|
|
69
|
+
const SetForegroundWindow = user32.func('bool __stdcall SetForegroundWindow(HWND hwnd)');
|
|
70
|
+
const ShowWindow = user32.func('bool __stdcall ShowWindow(HWND hwnd, int cmd)');
|
|
71
|
+
const BringWindowToTop = user32.func('bool __stdcall BringWindowToTop(HWND hwnd)');
|
|
72
|
+
const DwmGetWindowAttributeInt = dwmapi.func('long __stdcall DwmGetWindowAttribute(HWND hwnd, uint32_t attr, _Out_ int *value, uint32_t size)');
|
|
73
|
+
const DwmGetWindowAttributeRect = dwmapi.func('long __stdcall DwmGetWindowAttribute(HWND hwnd, uint32_t attr, _Out_ RECT *value, uint32_t size)');
|
|
74
|
+
// exported by user32 since Windows XP without a header declaration; returns MB_TIMEDOUT when the time runs out
|
|
75
|
+
const MessageBoxTimeoutW = user32.func('int __stdcall MessageBoxTimeoutW(HWND hwnd, str16 text, str16 caption, uint32_t type, uint16_t lang, uint32_t ms)');
|
|
76
|
+
|
|
77
|
+
const SRCCOPY = 0x00CC0020, CAPTUREBLT = 0x40000000;
|
|
78
|
+
const INPUT_MOUSE = 0, INPUT_KEYBOARD = 1;
|
|
79
|
+
const MOUSEEVENTF = { LEFTDOWN: 0x2, LEFTUP: 0x4, RIGHTDOWN: 0x8, RIGHTUP: 0x10, MIDDLEDOWN: 0x20, MIDDLEUP: 0x40, WHEEL: 0x800, HWHEEL: 0x1000 };
|
|
80
|
+
const MONITORINFOF_PRIMARY = 1;
|
|
81
|
+
const KEYEVENTF = { EXTENDEDKEY: 0x1, KEYUP: 0x2, UNICODE: 0x4 };
|
|
82
|
+
const GWL_EXSTYLE = -20, WS_EX_TOOLWINDOW = 0x80;
|
|
83
|
+
const DWMWA_EXTENDED_FRAME_BOUNDS = 9, DWMWA_CLOAKED = 14;
|
|
84
|
+
const SW_RESTORE = 9;
|
|
85
|
+
const MB_YESNO = 0x4, MB_ICONQUESTION = 0x20, MB_SETFOREGROUND = 0x10000, MB_TOPMOST = 0x40000;
|
|
86
|
+
const IDYES = 6, MB_TIMEDOUT = 32000;
|
|
87
|
+
|
|
88
|
+
SetProcessDpiAwarenessContext(-4);
|
|
89
|
+
|
|
90
|
+
export interface Rect { x: number; y: number; width: number; height: number }
|
|
91
|
+
|
|
92
|
+
/** The active displays; the device name (\\.\DISPLAY1) identifies each. */
|
|
93
|
+
export function displays(): NativeDisplay[] {
|
|
94
|
+
const out: NativeDisplay[] = [];
|
|
95
|
+
EnumDisplayMonitors(null, null, (monitor: unknown) => {
|
|
96
|
+
const info = { cbSize: koffi.sizeof(MONITORINFOEXW), rcMonitor: { left: 0, top: 0, right: 0, bottom: 0 }, rcWork: { left: 0, top: 0, right: 0, bottom: 0 }, dwFlags: 0, szDevice: '' };
|
|
97
|
+
if (!GetMonitorInfoW(monitor, info)) return true;
|
|
98
|
+
const r = info.rcMonitor;
|
|
99
|
+
out.push({ id: info.szDevice, primary: (info.dwFlags & MONITORINFOF_PRIMARY) !== 0, x: r.left, y: r.top, width: r.right - r.left, height: r.bottom - r.top, scale: 1 });
|
|
100
|
+
return true;
|
|
101
|
+
}, 0);
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Display `d` as top-down BGRA. */
|
|
106
|
+
export function capture(d: NativeDisplay): { width: number; height: number; bgra: Uint8Array } {
|
|
107
|
+
const { width, height } = d;
|
|
108
|
+
// the screen DC spans the virtual screen in its own coordinates
|
|
109
|
+
const screen = GetDC(null);
|
|
110
|
+
const mem = CreateCompatibleDC(screen);
|
|
111
|
+
const bmp = CreateCompatibleBitmap(screen, width, height);
|
|
112
|
+
const old = SelectObject(mem, bmp);
|
|
113
|
+
try {
|
|
114
|
+
if (!BitBlt(mem, 0, 0, width, height, screen, d.x, d.y, SRCCOPY | CAPTUREBLT)) throw new EngineFailure('winBitBlt');
|
|
115
|
+
const bgra = Buffer.alloc(width * height * 4);
|
|
116
|
+
const header = { biSize: koffi.sizeof(BITMAPINFOHEADER), biWidth: width, biHeight: -height, biPlanes: 1, biBitCount: 32, biCompression: 0, biSizeImage: 0, biXPelsPerMeter: 0, biYPelsPerMeter: 0, biClrUsed: 0, biClrImportant: 0 };
|
|
117
|
+
// the full BITMAPINFO carries a color table after the header; 32 bpp BI_RGB uses none
|
|
118
|
+
const lines = GetDIBits(mem, bmp, 0, height, bgra, header, 0);
|
|
119
|
+
if (lines !== height) throw new EngineFailure('winGetDIBits', [lines, height]);
|
|
120
|
+
return { width, height, bgra };
|
|
121
|
+
} finally {
|
|
122
|
+
SelectObject(mem, old);
|
|
123
|
+
DeleteObject(bmp);
|
|
124
|
+
DeleteDC(mem);
|
|
125
|
+
ReleaseDC(null, screen);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function cursor(): { x: number; y: number } {
|
|
130
|
+
const p = { x: 0, y: 0 };
|
|
131
|
+
GetCursorPos(p);
|
|
132
|
+
return p;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Tick (ms since boot, wraps at 2^32) of the last input from any source; null when the query fails. */
|
|
136
|
+
export function lastInputTick(): number | null {
|
|
137
|
+
const info = { cbSize: koffi.sizeof(LASTINPUTINFO), dwTime: 0 };
|
|
138
|
+
return GetLastInputInfo(info) ? info.dwTime : null;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function tick(): number {
|
|
142
|
+
return GetTickCount();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function send(inputs: unknown[]): void {
|
|
146
|
+
const sent = SendInput(inputs.length, inputs, koffi.sizeof(INPUT));
|
|
147
|
+
if (sent !== inputs.length) throw new EngineFailure('winSendInput', [sent, inputs.length]);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const mouse = (dwFlags: number, dx = 0, dy = 0, mouseData = 0) => ({ type: INPUT_MOUSE, u: { mi: { dx, dy, mouseData, dwFlags, time: 0, dwExtraInfo: 0 } } });
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Moves the pointer to a point of the virtual screen. SetCursorPos takes it exactly, where SendInput's
|
|
154
|
+
* absolute moves are scaled to 0–65535 across the virtual screen and land off by a pixel at the edges between displays.
|
|
155
|
+
*/
|
|
156
|
+
export function moveTo(x: number, y: number): void {
|
|
157
|
+
if (!SetCursorPos(Math.round(x), Math.round(y))) throw new EngineFailure('winSetCursorPos', [Math.round(x), Math.round(y)]);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export type Button = 'left' | 'right' | 'middle';
|
|
161
|
+
const BUTTON_FLAGS: Record<Button, [number, number]> = {
|
|
162
|
+
left: [MOUSEEVENTF.LEFTDOWN, MOUSEEVENTF.LEFTUP],
|
|
163
|
+
right: [MOUSEEVENTF.RIGHTDOWN, MOUSEEVENTF.RIGHTUP],
|
|
164
|
+
middle: [MOUSEEVENTF.MIDDLEDOWN, MOUSEEVENTF.MIDDLEUP],
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
export function buttonDown(b: Button): void { send([mouse(BUTTON_FLAGS[b][0])]); }
|
|
168
|
+
export function buttonUp(b: Button): void { send([mouse(BUTTON_FLAGS[b][1])]); }
|
|
169
|
+
|
|
170
|
+
/** One wheel notch is 120; positive `down` scrolls toward the end of a document. */
|
|
171
|
+
export function wheel(down: number, right: number): void {
|
|
172
|
+
const inputs = [];
|
|
173
|
+
if (down) inputs.push(mouse(MOUSEEVENTF.WHEEL, 0, 0, (-down * 120) >>> 0));
|
|
174
|
+
if (right) inputs.push(mouse(MOUSEEVENTF.HWHEEL, 0, 0, (right * 120) >>> 0));
|
|
175
|
+
if (inputs.length) send(inputs);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const key = (vk: number, up: boolean, extended: boolean) => ({ type: INPUT_KEYBOARD, u: { ki: { wVk: vk, wScan: 0, dwFlags: (up ? KEYEVENTF.KEYUP : 0) | (extended ? KEYEVENTF.EXTENDEDKEY : 0), time: 0, dwExtraInfo: 0 } } });
|
|
179
|
+
|
|
180
|
+
/** Presses `vks` in order, then releases them in reverse. */
|
|
181
|
+
export function chord(vks: Array<{ vk: number; extended: boolean }>): void {
|
|
182
|
+
send([...vks.map((k) => key(k.vk, false, k.extended)), ...[...vks].reverse().map((k) => key(k.vk, true, k.extended))]);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Presses `vks` in order and leaves them down. */
|
|
186
|
+
export function keysDown(vks: Array<{ vk: number; extended: boolean }>): void {
|
|
187
|
+
send(vks.map((k) => key(k.vk, false, k.extended)));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Releases `vks` in reverse order. */
|
|
191
|
+
export function keysUp(vks: Array<{ vk: number; extended: boolean }>): void {
|
|
192
|
+
send([...vks].reverse().map((k) => key(k.vk, true, k.extended)));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Types text as Unicode key events, independent of the keyboard layout and IME state. */
|
|
196
|
+
export function typeUnicode(text: string): void {
|
|
197
|
+
const inputs = [];
|
|
198
|
+
for (let i = 0; i < text.length; i++) {
|
|
199
|
+
const unit = text.charCodeAt(i);
|
|
200
|
+
if (text[i] === '\n') {
|
|
201
|
+
inputs.push(key(0x0D, false, false), key(0x0D, true, false));
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
if (text[i] === '\r') continue;
|
|
205
|
+
inputs.push({ type: INPUT_KEYBOARD, u: { ki: { wVk: 0, wScan: unit, dwFlags: KEYEVENTF.UNICODE, time: 0, dwExtraInfo: 0 } } });
|
|
206
|
+
inputs.push({ type: INPUT_KEYBOARD, u: { ki: { wVk: 0, wScan: unit, dwFlags: KEYEVENTF.UNICODE | KEYEVENTF.KEYUP, time: 0, dwExtraInfo: 0 } } });
|
|
207
|
+
}
|
|
208
|
+
if (inputs.length) send(inputs);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export interface WindowInfo {
|
|
212
|
+
handle: string;
|
|
213
|
+
title: string;
|
|
214
|
+
pid: number;
|
|
215
|
+
rect: Rect;
|
|
216
|
+
minimized: boolean;
|
|
217
|
+
foreground: boolean;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function frameRect(hwnd: unknown): Rect {
|
|
221
|
+
const r = { left: 0, top: 0, right: 0, bottom: 0 };
|
|
222
|
+
if (DwmGetWindowAttributeRect(hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, r, koffi.sizeof(RECT)) !== 0) GetWindowRect(hwnd, r);
|
|
223
|
+
return { x: r.left, y: r.top, width: r.right - r.left, height: r.bottom - r.top };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Handles from the last enumeration; `focus` takes a handle string from it. */
|
|
227
|
+
const known = new Map<string, unknown>();
|
|
228
|
+
|
|
229
|
+
export function foregroundWindow(): ForegroundWindow | null {
|
|
230
|
+
const hwnd = GetForegroundWindow();
|
|
231
|
+
if (!hwnd) return null;
|
|
232
|
+
const buf = new Uint16Array(512);
|
|
233
|
+
const n = GetWindowTextW(hwnd, buf, buf.length);
|
|
234
|
+
const pid = [0];
|
|
235
|
+
GetWindowThreadProcessId(hwnd, pid);
|
|
236
|
+
return { title: String.fromCharCode(...buf.subarray(0, n)), app: processName(pid[0]), rect: frameRect(hwnd) };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Visible, titled, uncloaked top-level windows in z-order (topmost first). */
|
|
240
|
+
export function windows(): WindowInfo[] {
|
|
241
|
+
known.clear();
|
|
242
|
+
const fg = koffi.address(GetForegroundWindow());
|
|
243
|
+
const out: WindowInfo[] = [];
|
|
244
|
+
const buf = new Uint16Array(512);
|
|
245
|
+
EnumWindows((hwnd: unknown) => {
|
|
246
|
+
if (!IsWindowVisible(hwnd)) return true;
|
|
247
|
+
if (Number(GetWindowLongPtrW(hwnd, GWL_EXSTYLE)) & WS_EX_TOOLWINDOW) return true;
|
|
248
|
+
const cloaked = [0];
|
|
249
|
+
if (DwmGetWindowAttributeInt(hwnd, DWMWA_CLOAKED, cloaked, 4) === 0 && cloaked[0] !== 0) return true;
|
|
250
|
+
const n = GetWindowTextW(hwnd, buf, buf.length);
|
|
251
|
+
if (n <= 0) return true;
|
|
252
|
+
const title = String.fromCharCode(...buf.subarray(0, n));
|
|
253
|
+
const pid = [0];
|
|
254
|
+
GetWindowThreadProcessId(hwnd, pid);
|
|
255
|
+
const address = koffi.address(hwnd);
|
|
256
|
+
known.set(address.toString(16), hwnd);
|
|
257
|
+
out.push({ handle: address.toString(16), title, pid: pid[0], rect: frameRect(hwnd), minimized: IsIconic(hwnd), foreground: address === fg });
|
|
258
|
+
return true;
|
|
259
|
+
}, 0);
|
|
260
|
+
return out;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** The executable's file name of process `pid` ("cmd.exe"), null when it cannot be read. */
|
|
264
|
+
export function processName(pid: number): string | null {
|
|
265
|
+
const process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
|
|
266
|
+
if (!process) return null;
|
|
267
|
+
try {
|
|
268
|
+
const buf = new Uint16Array(1024);
|
|
269
|
+
const size = [buf.length];
|
|
270
|
+
if (!QueryFullProcessImageNameW(process, 0, buf, size)) return null;
|
|
271
|
+
const path = String.fromCharCode(...buf.subarray(0, size[0]));
|
|
272
|
+
return path.slice(path.lastIndexOf('\\') + 1);
|
|
273
|
+
} finally {
|
|
274
|
+
CloseHandle(process);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Restores and raises a window; Windows only lets the foreground process hand focus away, so an Alt tap goes first. */
|
|
279
|
+
export function focus(handle: string): boolean {
|
|
280
|
+
if (!known.has(handle)) windows();
|
|
281
|
+
const hwnd = known.get(handle);
|
|
282
|
+
if (!hwnd) return false;
|
|
283
|
+
if (IsIconic(hwnd)) ShowWindow(hwnd, SW_RESTORE);
|
|
284
|
+
chord([{ vk: 0x12, extended: false }]);
|
|
285
|
+
const ok = SetForegroundWindow(hwnd);
|
|
286
|
+
BringWindowToTop(hwnd);
|
|
287
|
+
return ok;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** A yes/no system dialog above every window. Runs on a koffi worker thread, so the engine keeps serving other requests. */
|
|
291
|
+
/** Windows names the two buttons itself, in its own language. */
|
|
292
|
+
export function askYesNo(text: string, caption: string, _labels: { yes: string; no: string }, timeoutMs: number): Promise<'yes' | 'no' | 'timeout'> {
|
|
293
|
+
return new Promise((resolve, reject) => {
|
|
294
|
+
MessageBoxTimeoutW.async(null, text, caption, MB_YESNO | MB_ICONQUESTION | MB_SETFOREGROUND | MB_TOPMOST, 0, timeoutMs, (err: unknown, r: number) => {
|
|
295
|
+
if (err) reject(err as Error);
|
|
296
|
+
else resolve(r === IDYES ? 'yes' : r === MB_TIMEDOUT ? 'timeout' : 'no');
|
|
297
|
+
});
|
|
298
|
+
});
|
|
299
|
+
}
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Engine child process: owns every call into the operating system so a native fault takes
|
|
3
|
+
* down this process, not the bot's. Imports no `cortico/*`.
|
|
4
|
+
*
|
|
5
|
+
* Yielding to the user: before sending input, the engine waits until the user has been idle
|
|
6
|
+
* for `yield.idleMs`. User activity is input newer than the engine's own last injection
|
|
7
|
+
* (GetLastInputInfo) or the pointer found away from where the engine left it. Typing checks
|
|
8
|
+
* again between chunks and stops as soon as the user moves in; a hold waits only before pressing.
|
|
9
|
+
*
|
|
10
|
+
* Displays are numbered from 1, left to right and then top to bottom; positions in requests and
|
|
11
|
+
* results are physical pixels of one display, and the global coordinates of each platform stay in
|
|
12
|
+
* here (engine/display.ts). An input request names the arrangement it was aimed at and fails when the
|
|
13
|
+
* displays have changed since.
|
|
14
|
+
*
|
|
15
|
+
* A `cancel` message is honoured at the same points: the wait for the user ends with nothing
|
|
16
|
+
* sent, typing stops between chunks of whole graphemes, and a hold releases its keys at once. A
|
|
17
|
+
* click, drag, scroll, key sequence or focus that has started is sent in full. A button pressed by
|
|
18
|
+
* `mouseDown` stays down until `mouseUp`; `release` and the disconnect before the process exits
|
|
19
|
+
* release every key and button still down.
|
|
20
|
+
*/
|
|
21
|
+
import type { Button, ChildToMain, EngineRequest, HoldResult, InputResult, MainToChild, ScreenInfo, ScreenshotResult, Target, TypeResult, WindowEntry, Yield, ZoomResult } from './engine-ipc.ts';
|
|
22
|
+
import type { KeyCode } from './engine/keys.ts';
|
|
23
|
+
// the operating system's own calls: Win32 on Windows, CoreGraphics and AppleScript on macOS, X11 on Linux
|
|
24
|
+
const os: typeof import('./engine/win32.ts') = process.platform === 'darwin' ? await import('./engine/darwin.ts')
|
|
25
|
+
: process.platform === 'linux' ? await import('./engine/linux.ts') : await import('./engine/win32.ts');
|
|
26
|
+
import { downscale, drawCursor, encodeJpeg, fit } from './engine/image.ts';
|
|
27
|
+
import { EngineFailure } from './engine/fail.ts';
|
|
28
|
+
import { crop, displayAt, layoutOf, ordered, physicalSize, toLocal, toNative, type NativeDisplay } from './engine/display.ts';
|
|
29
|
+
import { UserActivity } from './engine/user-activity.ts';
|
|
30
|
+
import { INPUT_POLL_MS, recordActivity, waitIdle } from './engine/wait-idle.ts';
|
|
31
|
+
|
|
32
|
+
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
33
|
+
const activity = new UserActivity();
|
|
34
|
+
|
|
35
|
+
function markOwn(): void {
|
|
36
|
+
activity.markOwn(os.tick(), os.cursor());
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function userActivity() {
|
|
40
|
+
const cursor = os.cursor();
|
|
41
|
+
const lastInputTick = os.lastInputTick();
|
|
42
|
+
return activity.sample({ now: os.tick(), lastInputTick, cursor });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Whether a cancel has arrived for the request being handled. */
|
|
46
|
+
type Cancelled = () => boolean;
|
|
47
|
+
|
|
48
|
+
/** The displays as they are now, in the order they are numbered. */
|
|
49
|
+
function current(): { list: NativeDisplay[]; layout: string } {
|
|
50
|
+
const list = ordered(os.displays());
|
|
51
|
+
return { list, layout: layoutOf(list) };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 1-based number of the display holding a global point, null when none does. */
|
|
55
|
+
const numberAt = (list: NativeDisplay[], x: number, y: number) => {
|
|
56
|
+
const i = displayAt(list, x, y);
|
|
57
|
+
return i < 0 ? null : i + 1;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
function info(): ScreenInfo {
|
|
61
|
+
const { list, layout } = current();
|
|
62
|
+
const fg = os.foregroundWindow();
|
|
63
|
+
const c = os.cursor();
|
|
64
|
+
const on = numberAt(list, c.x, c.y);
|
|
65
|
+
return {
|
|
66
|
+
displays: list.map((d, i) => ({ index: i + 1, primary: d.primary, ...physicalSize(d) })),
|
|
67
|
+
layout,
|
|
68
|
+
cursor: on === null ? null : { display: on, ...toLocal(list[on - 1]!, c.x, c.y) },
|
|
69
|
+
foreground: fg ? fg.title : null,
|
|
70
|
+
foregroundApp: fg?.app ?? null,
|
|
71
|
+
foregroundDisplay: fg?.rect ? numberAt(list, fg.rect.x + fg.rect.width / 2, fg.rect.y + fg.rect.height / 2) : null,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The display a request names, as long as the arrangement is still the one it was aimed at. */
|
|
76
|
+
function target(at: Target): NativeDisplay {
|
|
77
|
+
const { list, layout } = current();
|
|
78
|
+
if (layout !== at.layout) throw new EngineFailure('layoutChanged');
|
|
79
|
+
return display(list, at.display);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function display(list: NativeDisplay[], n: number): NativeDisplay {
|
|
83
|
+
const d = list[n - 1];
|
|
84
|
+
if (!d) throw new EngineFailure('noDisplay', [n, list.length]);
|
|
85
|
+
return d;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Moves the pointer to a physical pixel of `d`. */
|
|
89
|
+
function moveOn(d: NativeDisplay, x: number, y: number): void {
|
|
90
|
+
const p = toNative(d, x, y);
|
|
91
|
+
os.moveTo(p.x, p.y);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** What the engine pressed and has not released: the keys of a hold, the buttons of clicks, drags and mouseDown. */
|
|
95
|
+
const held = { keys: [] as KeyCode[], buttons: new Set<Button>() };
|
|
96
|
+
|
|
97
|
+
function press(b: Button): void {
|
|
98
|
+
os.buttonDown(b);
|
|
99
|
+
held.buttons.add(b);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function lift(b: Button): void {
|
|
103
|
+
os.buttonUp(b);
|
|
104
|
+
held.buttons.delete(b);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function releaseKeys(): void {
|
|
108
|
+
if (held.keys.length) os.keysUp(held.keys);
|
|
109
|
+
held.keys = [];
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function releaseAll(): void {
|
|
113
|
+
releaseKeys();
|
|
114
|
+
for (const b of [...held.buttons]) lift(b);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function withInput(y: Yield, cancelled: Cancelled, act: () => Promise<void> | void): Promise<InputResult> {
|
|
118
|
+
const w = await waitIdle(y, cancelled, userActivity);
|
|
119
|
+
if (!w.yielded && !w.cancelled) {
|
|
120
|
+
await act();
|
|
121
|
+
markOwn();
|
|
122
|
+
}
|
|
123
|
+
return { ...info(), ...w };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function handle(req: EngineRequest, cancelled: Cancelled): Promise<unknown> {
|
|
127
|
+
switch (req.op) {
|
|
128
|
+
case 'info': return info();
|
|
129
|
+
case 'screenshot': {
|
|
130
|
+
const base = info();
|
|
131
|
+
const n = req.display ?? base.foregroundDisplay ?? base.displays.find((d) => d.primary)?.index ?? 1;
|
|
132
|
+
const d = display(current().list, n);
|
|
133
|
+
const cap = os.capture(d);
|
|
134
|
+
const size = fit(cap.width, cap.height, req.maxWidth, req.maxHeight);
|
|
135
|
+
const rgba = downscale(cap.bgra, cap.width, cap.height, size);
|
|
136
|
+
// per physical pixel, whatever size the capture came at
|
|
137
|
+
const scale = size.width / physicalSize(d).width;
|
|
138
|
+
const c = base.cursor;
|
|
139
|
+
if (c && c.display === n) drawCursor(rgba, size.width, size.height, c.x * scale, c.y * scale);
|
|
140
|
+
const out: ScreenshotResult = { ...base, display: n, jpeg: encodeJpeg(rgba, size.width, size.height, req.quality), width: size.width, height: size.height, scale };
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
case 'zoom': {
|
|
144
|
+
const d = target(req.at);
|
|
145
|
+
const cap = os.capture(d);
|
|
146
|
+
const k = cap.width / physicalSize(d).width;
|
|
147
|
+
const x = Math.max(0, Math.min(cap.width - 1, Math.round(req.x * k))), y = Math.max(0, Math.min(cap.height - 1, Math.round(req.y * k)));
|
|
148
|
+
const w = Math.max(1, Math.min(cap.width - x, Math.round(req.width * k))), h = Math.max(1, Math.min(cap.height - y, Math.round(req.height * k)));
|
|
149
|
+
const size = fit(w, h, req.maxWidth, req.maxHeight);
|
|
150
|
+
const rgba = downscale(crop(cap.bgra, cap.width, x, y, w, h), w, h, size);
|
|
151
|
+
return { jpeg: encodeJpeg(rgba, size.width, size.height, req.quality), width: size.width, height: size.height } satisfies ZoomResult;
|
|
152
|
+
}
|
|
153
|
+
case 'move': { const d = target(req.at); return withInput(req.yield, cancelled, () => moveOn(d, req.x, req.y)); }
|
|
154
|
+
case 'click': { const d = target(req.at); return withInput(req.yield, cancelled, async () => {
|
|
155
|
+
moveOn(d, req.x, req.y);
|
|
156
|
+
await sleep(40);
|
|
157
|
+
for (let i = 0; i < req.count; i++) {
|
|
158
|
+
press(req.button);
|
|
159
|
+
await sleep(15);
|
|
160
|
+
lift(req.button);
|
|
161
|
+
if (i < req.count - 1) await sleep(60);
|
|
162
|
+
}
|
|
163
|
+
}); }
|
|
164
|
+
case 'drag': { const d = target(req.at); return withInput(req.yield, cancelled, async () => {
|
|
165
|
+
moveOn(d, req.x1, req.y1);
|
|
166
|
+
await sleep(40);
|
|
167
|
+
press('left');
|
|
168
|
+
const steps = 16;
|
|
169
|
+
for (let i = 1; i <= steps; i++) {
|
|
170
|
+
await sleep(16);
|
|
171
|
+
moveOn(d, req.x1 + (req.x2 - req.x1) * i / steps, req.y1 + (req.y2 - req.y1) * i / steps);
|
|
172
|
+
}
|
|
173
|
+
await sleep(40);
|
|
174
|
+
lift('left');
|
|
175
|
+
}); }
|
|
176
|
+
case 'mouseDown': { const d = target(req.at); return withInput(req.yield, cancelled, async () => {
|
|
177
|
+
moveOn(d, req.x, req.y);
|
|
178
|
+
await sleep(40);
|
|
179
|
+
press(req.button);
|
|
180
|
+
}); }
|
|
181
|
+
case 'mouseUp': return withInput(req.yield, cancelled, () => lift(req.button));
|
|
182
|
+
case 'scroll': { const d = target(req.at); return withInput(req.yield, cancelled, async () => {
|
|
183
|
+
moveOn(d, req.x, req.y);
|
|
184
|
+
await sleep(30);
|
|
185
|
+
const n = Math.max(Math.abs(req.down), Math.abs(req.right));
|
|
186
|
+
for (let i = 0; i < n; i++) {
|
|
187
|
+
os.wheel(i < Math.abs(req.down) ? Math.sign(req.down) : 0, i < Math.abs(req.right) ? Math.sign(req.right) : 0);
|
|
188
|
+
await sleep(30);
|
|
189
|
+
}
|
|
190
|
+
}); }
|
|
191
|
+
case 'type': {
|
|
192
|
+
const w = await waitIdle(req.yield, cancelled, userActivity);
|
|
193
|
+
if (w.yielded || w.cancelled) return { ...info(), ...w, typed: 0, stoppedBy: null } satisfies TypeResult;
|
|
194
|
+
const graphemes = [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(req.text)].map((s) => s.segment);
|
|
195
|
+
let typed = 0;
|
|
196
|
+
let stoppedBy: TypeResult['stoppedBy'] = null;
|
|
197
|
+
for (let i = 0; i < graphemes.length; i += 16) {
|
|
198
|
+
if (i > 0 && cancelled()) { stoppedBy = 'cancel'; break; }
|
|
199
|
+
if (i > 0) {
|
|
200
|
+
const input = userActivity();
|
|
201
|
+
if (input.idleMs < 300) {
|
|
202
|
+
recordActivity(w.activity, input, 300);
|
|
203
|
+
stoppedBy = 'user';
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const chunk = graphemes.slice(i, i + 16).join('');
|
|
208
|
+
os.typeUnicode(chunk);
|
|
209
|
+
typed += [...chunk].length;
|
|
210
|
+
markOwn();
|
|
211
|
+
await sleep(req.chunkDelayMs);
|
|
212
|
+
}
|
|
213
|
+
return { ...info(), ...w, typed, stoppedBy } satisfies TypeResult;
|
|
214
|
+
}
|
|
215
|
+
case 'key': return withInput(req.yield, cancelled, async () => {
|
|
216
|
+
for (const chord of req.chords) {
|
|
217
|
+
os.chord(chord);
|
|
218
|
+
await sleep(40);
|
|
219
|
+
}
|
|
220
|
+
});
|
|
221
|
+
case 'hold': {
|
|
222
|
+
const w = await waitIdle(req.yield, cancelled, userActivity);
|
|
223
|
+
if (w.yielded || w.cancelled) return { ...info(), ...w, heldMs: 0 } satisfies HoldResult;
|
|
224
|
+
// the user is not watched while the keys are down: on Linux the X server repeats a held key,
|
|
225
|
+
// and the repeats count in the idle time read here as the user's own keys do
|
|
226
|
+
os.keysDown(req.keys);
|
|
227
|
+
held.keys = req.keys;
|
|
228
|
+
const start = Date.now();
|
|
229
|
+
while (Date.now() - start < req.holdMs && !cancelled()) await sleep(Math.min(INPUT_POLL_MS, req.holdMs - (Date.now() - start)));
|
|
230
|
+
const heldMs = Date.now() - start;
|
|
231
|
+
releaseKeys();
|
|
232
|
+
markOwn();
|
|
233
|
+
return { ...info(), ...w, heldMs } satisfies HoldResult;
|
|
234
|
+
}
|
|
235
|
+
case 'release': return releaseAll();
|
|
236
|
+
case 'windows': {
|
|
237
|
+
const { list } = current();
|
|
238
|
+
return os.windows().map((w): WindowEntry => {
|
|
239
|
+
const n = numberAt(list, w.rect.x + w.rect.width / 2, w.rect.y + w.rect.height / 2);
|
|
240
|
+
if (n === null) return { ...w, display: null };
|
|
241
|
+
const d = list[n - 1]!, at = toLocal(d, w.rect.x, w.rect.y);
|
|
242
|
+
return { ...w, display: n, rect: { ...at, width: Math.round(w.rect.width * d.scale), height: Math.round(w.rect.height * d.scale) } };
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
case 'confirm': return os.askYesNo(req.text, req.caption, { yes: req.yes, no: req.no }, req.timeoutMs);
|
|
246
|
+
case 'focus': {
|
|
247
|
+
const w = await waitIdle(req.yield, cancelled, userActivity);
|
|
248
|
+
if (w.yielded || w.cancelled) return { ...info(), ...w, focused: false };
|
|
249
|
+
const focused = os.focus(req.handle);
|
|
250
|
+
markOwn();
|
|
251
|
+
await sleep(120);
|
|
252
|
+
return { ...info(), ...w, focused };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Requests being handled, by id; true once a cancel has arrived for it. */
|
|
258
|
+
const inFlight = new Map<number, boolean>();
|
|
259
|
+
|
|
260
|
+
process.on('message', (msg: MainToChild) => {
|
|
261
|
+
if ('cancel' in msg) {
|
|
262
|
+
if (inFlight.has(msg.cancel)) inFlight.set(msg.cancel, true);
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
const { id } = msg;
|
|
266
|
+
inFlight.set(id, false);
|
|
267
|
+
void handle(msg.req, () => inFlight.get(id) === true).then(
|
|
268
|
+
(value) => process.send?.({ id, ok: true, value } satisfies ChildToMain),
|
|
269
|
+
(err: Error) => process.send?.({ id, ok: false, error: err.message, ...(err instanceof EngineFailure ? { code: err.code, args: err.args } : {}) } satisfies ChildToMain),
|
|
270
|
+
).finally(() => inFlight.delete(id));
|
|
271
|
+
});
|
|
272
|
+
process.on('disconnect', () => {
|
|
273
|
+
try { releaseAll(); } finally { process.exit(0); }
|
|
274
|
+
});
|