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,410 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* macOS access, the same surface as `win32.ts`: screen capture through the system's
|
|
3
|
+
* `screencapture`, mouse and keyboard as CoreGraphics events posted through koffi, the on-screen
|
|
4
|
+
* window list from CGWindowListCopyWindowInfo, the seconds since the last hardware input, and
|
|
5
|
+
* AppleScript for bringing an app forward and for the yes/no dialog.
|
|
6
|
+
*
|
|
7
|
+
* Coordinates are CoreGraphics points of the global display space (the main display's top-left
|
|
8
|
+
* corner is (0, 0)); each display reports its own pixels per point, and a capture is at pixel size. macOS lets an app capture the screen only under Privacy & Security → Screen Recording,
|
|
9
|
+
* and post input events only under Accessibility; the first use asks for each, and until they are
|
|
10
|
+
* given the calls throw with where to turn them on. This module runs only inside the engine child.
|
|
11
|
+
*/
|
|
12
|
+
import koffi from 'koffi';
|
|
13
|
+
import jpeg from 'jpeg-js';
|
|
14
|
+
import { execFile, execFileSync } from 'node:child_process';
|
|
15
|
+
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
16
|
+
import { tmpdir } from 'node:os';
|
|
17
|
+
import { join } from 'node:path';
|
|
18
|
+
import { appleString, dialogAnswer, macKey, unicodeChunks } from './mac-keys.ts';
|
|
19
|
+
import { EngineFailure } from './fail.ts';
|
|
20
|
+
import type { NativeDisplay } from './display.ts';
|
|
21
|
+
import type { ForegroundWindow } from './foreground.ts';
|
|
22
|
+
|
|
23
|
+
const cg = koffi.load('/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics');
|
|
24
|
+
const cf = koffi.load('/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation');
|
|
25
|
+
const services = koffi.load('/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices');
|
|
26
|
+
|
|
27
|
+
const CGPoint = koffi.struct('CGPoint', { x: 'double', y: 'double' });
|
|
28
|
+
const CGRect = koffi.struct('CGRect', { x: 'double', y: 'double', width: 'double', height: 'double' });
|
|
29
|
+
const CGSize = koffi.struct('CGSize', { width: 'double', height: 'double' });
|
|
30
|
+
const ProcessSerialNumber = koffi.struct('ProcessSerialNumber', { highLongOfPSN: 'uint32_t', lowLongOfPSN: 'uint32_t' });
|
|
31
|
+
const GetFrontProcess = services.func('int16_t GetFrontProcess(_Out_ ProcessSerialNumber *psn)');
|
|
32
|
+
const GetProcessPID = services.func('int32_t GetProcessPID(const ProcessSerialNumber *psn, _Out_ int32_t *pid)');
|
|
33
|
+
const CopyProcessName = services.func('int32_t CopyProcessName(const ProcessSerialNumber *psn, _Out_ void **name)');
|
|
34
|
+
const AXUIElementCreateApplication = services.func('void *AXUIElementCreateApplication(int32_t pid)');
|
|
35
|
+
const AXUIElementSetMessagingTimeout = services.func('int32_t AXUIElementSetMessagingTimeout(void *element, float seconds)');
|
|
36
|
+
const AXUIElementCopyAttributeValue = services.func('int32_t AXUIElementCopyAttributeValue(void *element, void *attribute, _Out_ void **value)');
|
|
37
|
+
const AXValueGetPoint = services.func('bool AXValueGetValue(void *value, uint32_t type, _Out_ CGPoint *point)');
|
|
38
|
+
const AXValueGetSize = services.func('bool AXValueGetValue(void *value, uint32_t type, _Out_ CGSize *size)');
|
|
39
|
+
|
|
40
|
+
const CGMainDisplayID = cg.func('uint32_t CGMainDisplayID()');
|
|
41
|
+
const CGGetActiveDisplayList = cg.func('int32_t CGGetActiveDisplayList(uint32_t max, uint32_t *displays, _Out_ uint32_t *count)');
|
|
42
|
+
const CGDisplayBounds = cg.func('CGRect CGDisplayBounds(uint32_t display)');
|
|
43
|
+
const CGDisplayCopyDisplayMode = cg.func('void *CGDisplayCopyDisplayMode(uint32_t display)');
|
|
44
|
+
const CGDisplayModeGetPixelWidth = cg.func('size_t CGDisplayModeGetPixelWidth(void *mode)');
|
|
45
|
+
const CGDisplayModeGetWidth = cg.func('size_t CGDisplayModeGetWidth(void *mode)');
|
|
46
|
+
const CGDisplayModeRelease = cg.func('void CGDisplayModeRelease(void *mode)');
|
|
47
|
+
const CGPreflightScreenCaptureAccess = cg.func('bool CGPreflightScreenCaptureAccess()');
|
|
48
|
+
const CGRequestScreenCaptureAccess = cg.func('bool CGRequestScreenCaptureAccess()');
|
|
49
|
+
const CGPreflightPostEventAccess = cg.func('bool CGPreflightPostEventAccess()');
|
|
50
|
+
const CGRequestPostEventAccess = cg.func('bool CGRequestPostEventAccess()');
|
|
51
|
+
const CGEventCreate = cg.func('void *CGEventCreate(void *source)');
|
|
52
|
+
const CGEventGetLocation = cg.func('CGPoint CGEventGetLocation(void *event)');
|
|
53
|
+
const CGEventCreateMouseEvent = cg.func('void *CGEventCreateMouseEvent(void *source, uint32_t type, CGPoint pos, uint32_t button)');
|
|
54
|
+
const CGEventCreateKeyboardEvent = cg.func('void *CGEventCreateKeyboardEvent(void *source, uint16_t key, bool down)');
|
|
55
|
+
const CGEventKeyboardSetUnicodeString = cg.func('void CGEventKeyboardSetUnicodeString(void *event, unsigned long length, const uint16_t *chars)');
|
|
56
|
+
const CGEventSetFlags = cg.func('void CGEventSetFlags(void *event, uint64_t flags)');
|
|
57
|
+
const CGEventSetIntegerValueField = cg.func('void CGEventSetIntegerValueField(void *event, uint32_t field, int64_t value)');
|
|
58
|
+
const CGEventPost = cg.func('void CGEventPost(uint32_t tap, void *event)');
|
|
59
|
+
const CGEventSourceSecondsSinceLastEventType = cg.func('double CGEventSourceSecondsSinceLastEventType(int32_t state, uint32_t type)');
|
|
60
|
+
const CGWindowListCopyWindowInfo = cg.func('void *CGWindowListCopyWindowInfo(uint32_t option, uint32_t relativeToWindow)');
|
|
61
|
+
const CGRectMakeWithDictionaryRepresentation = cg.func('bool CGRectMakeWithDictionaryRepresentation(void *dict, _Out_ CGRect *rect)');
|
|
62
|
+
// macOS 13 and later; earlier ones only have the variadic CGEventCreateScrollWheelEvent
|
|
63
|
+
const CGEventCreateScrollWheelEvent2 = (() => {
|
|
64
|
+
try { return cg.func('void *CGEventCreateScrollWheelEvent2(void *source, uint32_t units, uint32_t count, int32_t w1, int32_t w2, int32_t w3)'); } catch { return null; }
|
|
65
|
+
})();
|
|
66
|
+
const CGEventCreateScrollWheelEvent = cg.func('void *CGEventCreateScrollWheelEvent(void *source, uint32_t units, uint32_t count, int32_t w1, ...)');
|
|
67
|
+
|
|
68
|
+
const CFRelease = cf.func('void CFRelease(void *ref)');
|
|
69
|
+
const CFArrayGetCount = cf.func('long CFArrayGetCount(void *array)');
|
|
70
|
+
const CFArrayGetValueAtIndex = cf.func('void *CFArrayGetValueAtIndex(void *array, long index)');
|
|
71
|
+
const CFDictionaryGetValue = cf.func('void *CFDictionaryGetValue(void *dict, void *key)');
|
|
72
|
+
const CFStringCreateWithCString = cf.func('void *CFStringCreateWithCString(void *alloc, const char *s, uint32_t encoding)');
|
|
73
|
+
const CFStringGetCString = cf.func('bool CFStringGetCString(void *s, uint8_t *buf, long size, uint32_t encoding)');
|
|
74
|
+
const CFNumberGetValue = cf.func('bool CFNumberGetValue(void *n, long type, _Out_ int64_t *value)');
|
|
75
|
+
|
|
76
|
+
const UTF8 = 0x08000100;
|
|
77
|
+
const HID_TAP = 0;
|
|
78
|
+
/** kCGEventSourceStateHIDSystemState: input from the hardware, not events posted by apps. */
|
|
79
|
+
const HID_STATE = 1;
|
|
80
|
+
const ANY_INPUT = 0xffffffff;
|
|
81
|
+
const EV = { move: 5, leftDown: 1, leftUp: 2, rightDown: 3, rightUp: 4, otherDown: 25, otherUp: 26, leftDrag: 6, rightDrag: 7, otherDrag: 27 };
|
|
82
|
+
const CLICK_STATE_FIELD = 1;
|
|
83
|
+
const LINE = 1;
|
|
84
|
+
/** Lines one wheel notch scrolls, as Windows scrolls three lines a notch. */
|
|
85
|
+
const LINES_PER_NOTCH = 3;
|
|
86
|
+
/** Most UTF-16 units one keyboard event carries. */
|
|
87
|
+
const UNICODE_CHUNK = 20;
|
|
88
|
+
/** A second press this soon and this close to the last counts as a double (or triple) click. */
|
|
89
|
+
const MULTI_CLICK_MS = 500, MULTI_CLICK_PX = 4;
|
|
90
|
+
/** Each Accessibility query has this budget, including when the foreground app is unresponsive. */
|
|
91
|
+
export const FOREGROUND_QUERY_TIMEOUT_MS = 200;
|
|
92
|
+
|
|
93
|
+
export interface Rect { x: number; y: number; width: number; height: number }
|
|
94
|
+
|
|
95
|
+
const t0 = Date.now();
|
|
96
|
+
|
|
97
|
+
/** Most displays asked for at once. */
|
|
98
|
+
const MAX_DISPLAYS = 16;
|
|
99
|
+
|
|
100
|
+
/** The active displays: bounds in points, and pixels per point from each one's mode. */
|
|
101
|
+
export function displays(): NativeDisplay[] {
|
|
102
|
+
const ids = new Uint32Array(MAX_DISPLAYS), count = [0];
|
|
103
|
+
if (CGGetActiveDisplayList(MAX_DISPLAYS, ids, count) !== 0) return [];
|
|
104
|
+
const main = CGMainDisplayID();
|
|
105
|
+
return [...ids.subarray(0, count[0])].map((id) => {
|
|
106
|
+
const b = CGDisplayBounds(id) as Rect;
|
|
107
|
+
const mode = CGDisplayCopyDisplayMode(id);
|
|
108
|
+
let scale = 1;
|
|
109
|
+
if (mode) {
|
|
110
|
+
const pw = Number(CGDisplayModeGetPixelWidth(mode)), w = Number(CGDisplayModeGetWidth(mode));
|
|
111
|
+
if (pw > 0 && w > 0) scale = pw / w;
|
|
112
|
+
CGDisplayModeRelease(mode);
|
|
113
|
+
}
|
|
114
|
+
return { id: String(id), primary: id === main, x: b.x, y: b.y, width: b.width, height: b.height, scale };
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function needScreen(): void {
|
|
119
|
+
if (CGPreflightScreenCaptureAccess() || CGRequestScreenCaptureAccess()) return;
|
|
120
|
+
throw new EngineFailure('macScreenPermission');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function needInput(): void {
|
|
124
|
+
if (CGPreflightPostEventAccess() || CGRequestPostEventAccess()) return;
|
|
125
|
+
throw new EngineFailure('macInputPermission');
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Display `d` as top-down BGRA at its pixel size. */
|
|
129
|
+
export function capture(d: NativeDisplay): { width: number; height: number; bgra: Uint8Array } {
|
|
130
|
+
needScreen();
|
|
131
|
+
const dir = mkdtempSync(join(tmpdir(), 'cua-shot-'));
|
|
132
|
+
const file = join(dir, 'screen.jpg');
|
|
133
|
+
try {
|
|
134
|
+
// -x: no sound, -R: a rectangle of the global space in points
|
|
135
|
+
execFileSync('/usr/sbin/screencapture', ['-x', `-R${d.x},${d.y},${d.width},${d.height}`, '-t', 'jpg', file], { stdio: 'ignore', timeout: 15_000 });
|
|
136
|
+
const img = jpeg.decode(readFileSync(file), { useTArray: true, formatAsRGBA: true, maxMemoryUsageInMB: 1024 });
|
|
137
|
+
const bgra = Buffer.from(img.data.buffer, img.data.byteOffset, img.data.byteLength);
|
|
138
|
+
for (let i = 0; i < bgra.length; i += 4) { const r = bgra[i]!; bgra[i] = bgra[i + 2]!; bgra[i + 2] = r; }
|
|
139
|
+
return { width: img.width, height: img.height, bgra };
|
|
140
|
+
} finally {
|
|
141
|
+
rmSync(dir, { recursive: true, force: true });
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function pointerPoints(): { x: number; y: number } {
|
|
146
|
+
const ev = CGEventCreate(null);
|
|
147
|
+
const p = CGEventGetLocation(ev) as { x: number; y: number };
|
|
148
|
+
CFRelease(ev);
|
|
149
|
+
return p;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function cursor(): { x: number; y: number } {
|
|
153
|
+
return pointerPoints();
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Milliseconds since the engine started, wrapping at 2^32 as Windows' tick does. */
|
|
157
|
+
export function tick(): number {
|
|
158
|
+
return (Date.now() - t0) >>> 0;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Tick of the last input from the hardware. */
|
|
162
|
+
export function lastInputTick(): number {
|
|
163
|
+
const secs = CGEventSourceSecondsSinceLastEventType(HID_STATE, ANY_INPUT) as number;
|
|
164
|
+
return (tick() - Math.round(secs * 1000)) >>> 0;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function post(ev: unknown): void {
|
|
168
|
+
CGEventPost(HID_TAP, ev);
|
|
169
|
+
CFRelease(ev);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export type Button = 'left' | 'right' | 'middle';
|
|
173
|
+
const BUTTON: Record<Button, { down: number; up: number; drag: number; n: number }> = {
|
|
174
|
+
left: { down: EV.leftDown, up: EV.leftUp, drag: EV.leftDrag, n: 0 },
|
|
175
|
+
right: { down: EV.rightDown, up: EV.rightUp, drag: EV.rightDrag, n: 1 },
|
|
176
|
+
middle: { down: EV.otherDown, up: EV.otherUp, drag: EV.otherDrag, n: 2 },
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
/** The buttons held down (moves become drags of the first), and the last press, for counting double clicks. */
|
|
180
|
+
const held = new Set<Button>();
|
|
181
|
+
let lastPress: { button: Button; at: number; x: number; y: number; count: number } | null = null;
|
|
182
|
+
|
|
183
|
+
/** Absolute move to a point of the global display space. */
|
|
184
|
+
export function moveTo(x: number, y: number): void {
|
|
185
|
+
needInput();
|
|
186
|
+
const down = held.values().next().value;
|
|
187
|
+
const b = down ? BUTTON[down] : null;
|
|
188
|
+
post(CGEventCreateMouseEvent(null, b ? b.drag : EV.move, { x, y }, b ? b.n : 0));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function mouseEvent(button: Button, down: boolean): void {
|
|
192
|
+
needInput();
|
|
193
|
+
const p = pointerPoints();
|
|
194
|
+
const spec = BUTTON[button];
|
|
195
|
+
if (down) {
|
|
196
|
+
const now = Date.now();
|
|
197
|
+
const again = lastPress && lastPress.button === button && now - lastPress.at < MULTI_CLICK_MS
|
|
198
|
+
&& Math.abs(lastPress.x - p.x) <= MULTI_CLICK_PX && Math.abs(lastPress.y - p.y) <= MULTI_CLICK_PX;
|
|
199
|
+
lastPress = { button, at: now, x: p.x, y: p.y, count: again ? lastPress!.count + 1 : 1 };
|
|
200
|
+
}
|
|
201
|
+
const ev = CGEventCreateMouseEvent(null, down ? spec.down : spec.up, p, spec.n);
|
|
202
|
+
// macOS tells a double click by this count, not by the timing of two clicks
|
|
203
|
+
CGEventSetIntegerValueField(ev, CLICK_STATE_FIELD, lastPress?.count ?? 1);
|
|
204
|
+
post(ev);
|
|
205
|
+
if (down) held.add(button);
|
|
206
|
+
else held.delete(button);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function buttonDown(b: Button): void { mouseEvent(b, true); }
|
|
210
|
+
export function buttonUp(b: Button): void { mouseEvent(b, false); }
|
|
211
|
+
|
|
212
|
+
/** One notch per unit; positive `down` scrolls toward the end of a document. */
|
|
213
|
+
export function wheel(down: number, right: number): void {
|
|
214
|
+
if (!down && !right) return;
|
|
215
|
+
needInput();
|
|
216
|
+
// macOS: a positive first wheel scrolls up, a positive second wheel scrolls left
|
|
217
|
+
const w1 = -down * LINES_PER_NOTCH, w2 = -right * LINES_PER_NOTCH;
|
|
218
|
+
post(CGEventCreateScrollWheelEvent2
|
|
219
|
+
? CGEventCreateScrollWheelEvent2(null, LINE, 2, w1, w2, 0)
|
|
220
|
+
: CGEventCreateScrollWheelEvent(null, LINE, 2, w1, 'int32_t', w2));
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function key(code: number, down: boolean, flags: number): void {
|
|
224
|
+
const ev = CGEventCreateKeyboardEvent(null, code, down);
|
|
225
|
+
CGEventSetFlags(ev, BigInt(flags));
|
|
226
|
+
post(ev);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Modifier flags of the keys down now; every key event carries them. */
|
|
230
|
+
let heldFlags = 0;
|
|
231
|
+
|
|
232
|
+
/** The Mac keys of `vks` (Windows virtual-key codes); throws before anything is posted when one is missing. */
|
|
233
|
+
function macKeys(vks: Array<{ vk: number; extended: boolean }>): Array<{ key: number; flag: number }> {
|
|
234
|
+
return vks.map((k) => {
|
|
235
|
+
const m = macKey(k.vk);
|
|
236
|
+
if (!m) throw new EngineFailure('macNoKey', [`0x${k.vk.toString(16)}`]);
|
|
237
|
+
return m;
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Presses `vks` in order and leaves them down, their modifiers held. */
|
|
242
|
+
export function keysDown(vks: Array<{ vk: number; extended: boolean }>): void {
|
|
243
|
+
needInput();
|
|
244
|
+
for (const k of macKeys(vks)) { heldFlags |= k.flag; key(k.key, true, heldFlags); }
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Releases `vks` in reverse order. */
|
|
248
|
+
export function keysUp(vks: Array<{ vk: number; extended: boolean }>): void {
|
|
249
|
+
needInput();
|
|
250
|
+
for (const k of macKeys(vks).reverse()) { heldFlags &= ~k.flag; key(k.key, false, heldFlags); }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Presses `vks` in order with their modifiers held, then releases them in reverse. */
|
|
254
|
+
export function chord(vks: Array<{ vk: number; extended: boolean }>): void {
|
|
255
|
+
keysDown(vks);
|
|
256
|
+
keysUp(vks);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Types text as Unicode key events, independent of the keyboard layout and input method. */
|
|
260
|
+
export function typeUnicode(text: string): void {
|
|
261
|
+
needInput();
|
|
262
|
+
const RETURN = macKey(0x0d)!.key;
|
|
263
|
+
for (const line of text.replace(/\r/g, '').split(/(\n)/)) {
|
|
264
|
+
if (line === '\n') { key(RETURN, true, 0); key(RETURN, false, 0); continue; }
|
|
265
|
+
// AppKit consumers expect a character at a time, not a whole text run.
|
|
266
|
+
const graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(line);
|
|
267
|
+
for (const units of [...graphemes].flatMap(({ segment }) => unicodeChunks(segment, UNICODE_CHUNK))) {
|
|
268
|
+
for (const down of [true, false]) {
|
|
269
|
+
const ev = CGEventCreateKeyboardEvent(null, 0x31, down);
|
|
270
|
+
// A preceding shortcut must not turn text into Command/Option key presses.
|
|
271
|
+
CGEventSetFlags(ev, 0n);
|
|
272
|
+
CGEventKeyboardSetUnicodeString(ev, units.length, units);
|
|
273
|
+
post(ev);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export interface WindowInfo {
|
|
280
|
+
handle: string;
|
|
281
|
+
title: string;
|
|
282
|
+
pid: number;
|
|
283
|
+
rect: Rect;
|
|
284
|
+
minimized: boolean;
|
|
285
|
+
foreground: boolean;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const cfKeys = new Map<string, unknown>();
|
|
289
|
+
const cfKey = (name: string) => {
|
|
290
|
+
let k = cfKeys.get(name);
|
|
291
|
+
if (!k) { k = CFStringCreateWithCString(null, name, UTF8); cfKeys.set(name, k); }
|
|
292
|
+
return k;
|
|
293
|
+
};
|
|
294
|
+
function cfString(dict: unknown, name: string): string {
|
|
295
|
+
return readCfString(CFDictionaryGetValue(dict, cfKey(name)));
|
|
296
|
+
}
|
|
297
|
+
function readCfString(v: unknown): string {
|
|
298
|
+
if (!v) return '';
|
|
299
|
+
const buf = Buffer.alloc(1024);
|
|
300
|
+
if (!CFStringGetCString(v, buf, buf.length, UTF8)) return '';
|
|
301
|
+
return buf.subarray(0, buf.indexOf(0) < 0 ? buf.length : buf.indexOf(0)).toString('utf8');
|
|
302
|
+
}
|
|
303
|
+
function cfNumber(dict: unknown, name: string): number {
|
|
304
|
+
const v = CFDictionaryGetValue(dict, cfKey(name));
|
|
305
|
+
if (!v) return 0;
|
|
306
|
+
const out = [0n];
|
|
307
|
+
// kCFNumberSInt64Type
|
|
308
|
+
return CFNumberGetValue(v, 4, out) ? Number(out[0]) : 0;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** The app owning each window of the last enumeration, by process id. */
|
|
312
|
+
const apps = new Map<number, string>();
|
|
313
|
+
|
|
314
|
+
/** The app name of process `pid` as the last `windows()` saw it ("Terminal"). */
|
|
315
|
+
export function processName(pid: number): string | null {
|
|
316
|
+
return apps.get(pid) ?? null;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function axAttribute(element: unknown, name: string): unknown {
|
|
320
|
+
const value = [null];
|
|
321
|
+
return AXUIElementCopyAttributeValue(element, cfKey(name), value) === 0 ? value[0] : null;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export function foregroundWindow(): ForegroundWindow | null {
|
|
325
|
+
const psn = { highLongOfPSN: 0, lowLongOfPSN: 0 }, pid = [0], name = [null];
|
|
326
|
+
if (GetFrontProcess(psn) !== 0 || GetProcessPID(psn, pid) !== 0) return null;
|
|
327
|
+
CopyProcessName(psn, name);
|
|
328
|
+
const app = readCfString(name[0]) || null;
|
|
329
|
+
if (name[0]) CFRelease(name[0]);
|
|
330
|
+
const element = AXUIElementCreateApplication(pid[0]);
|
|
331
|
+
AXUIElementSetMessagingTimeout(element, FOREGROUND_QUERY_TIMEOUT_MS / 1000);
|
|
332
|
+
const window = axAttribute(element, 'AXFocusedWindow');
|
|
333
|
+
CFRelease(element);
|
|
334
|
+
if (!window) return { title: '', app, rect: null };
|
|
335
|
+
// Accessibility timeouts apply to individual elements and are not inherited by their windows.
|
|
336
|
+
AXUIElementSetMessagingTimeout(window, FOREGROUND_QUERY_TIMEOUT_MS / 1000);
|
|
337
|
+
const title = axAttribute(window, 'AXTitle');
|
|
338
|
+
const position = axAttribute(window, 'AXPosition');
|
|
339
|
+
const size = axAttribute(window, 'AXSize');
|
|
340
|
+
try {
|
|
341
|
+
const point = { x: 0, y: 0 }, extent = { width: 0, height: 0 };
|
|
342
|
+
const rect = position && size && AXValueGetPoint(position, 1, point) && AXValueGetSize(size, 2, extent)
|
|
343
|
+
? { ...point, ...extent } : null;
|
|
344
|
+
return { title: readCfString(title), app, rect };
|
|
345
|
+
} finally {
|
|
346
|
+
for (const value of [title, position, size, window]) if (value) CFRelease(value);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Ordinary windows on screen, front to back; the frontmost one belongs to the app in front.
|
|
352
|
+
* Titles come only with the Screen Recording permission; without it a window is named by its app.
|
|
353
|
+
*/
|
|
354
|
+
export function windows(): WindowInfo[] {
|
|
355
|
+
apps.clear();
|
|
356
|
+
// kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements
|
|
357
|
+
const list = CGWindowListCopyWindowInfo(1 | 16, 0);
|
|
358
|
+
if (!list) return [];
|
|
359
|
+
const out: WindowInfo[] = [];
|
|
360
|
+
try {
|
|
361
|
+
const n = Number(CFArrayGetCount(list));
|
|
362
|
+
for (let i = 0; i < n; i++) {
|
|
363
|
+
const w = CFArrayGetValueAtIndex(list, i);
|
|
364
|
+
// layer 0 holds ordinary app windows; menus, the Dock and overlays sit above it
|
|
365
|
+
if (cfNumber(w, 'kCGWindowLayer') !== 0) continue;
|
|
366
|
+
const app = cfString(w, 'kCGWindowOwnerName');
|
|
367
|
+
const name = cfString(w, 'kCGWindowName');
|
|
368
|
+
const bounds = CFDictionaryGetValue(w, cfKey('kCGWindowBounds'));
|
|
369
|
+
const r = { x: 0, y: 0, width: 0, height: 0 };
|
|
370
|
+
if (bounds) CGRectMakeWithDictionaryRepresentation(bounds, r);
|
|
371
|
+
if (r.width < 2 || r.height < 2) continue;
|
|
372
|
+
const pid = cfNumber(w, 'kCGWindowOwnerPID');
|
|
373
|
+
apps.set(pid, app);
|
|
374
|
+
out.push({
|
|
375
|
+
handle: `${pid}:${cfNumber(w, 'kCGWindowNumber')}`,
|
|
376
|
+
title: name ? `${name} - ${app}` : app,
|
|
377
|
+
pid,
|
|
378
|
+
rect: { x: r.x, y: r.y, width: r.width, height: r.height },
|
|
379
|
+
minimized: false,
|
|
380
|
+
foreground: out.length === 0,
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
} finally {
|
|
384
|
+
CFRelease(list);
|
|
385
|
+
}
|
|
386
|
+
return out;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Brings the window's app to the front (System Events asks once for permission to be driven). */
|
|
390
|
+
export function focus(handle: string): boolean {
|
|
391
|
+
const pid = Number(handle.split(':')[0]);
|
|
392
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
393
|
+
try {
|
|
394
|
+
execFileSync('/usr/bin/osascript', ['-e', `tell application "System Events" to set frontmost of (first process whose unix id is ${pid}) to true`], { stdio: 'ignore', timeout: 10_000 });
|
|
395
|
+
return true;
|
|
396
|
+
} catch {
|
|
397
|
+
return false;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** A yes/no dialog in front of every window, answered or given up after `timeoutMs`. */
|
|
402
|
+
export function askYesNo(text: string, caption: string, { yes, no }: { yes: string; no: string }, timeoutMs: number): Promise<'yes' | 'no' | 'timeout'> {
|
|
403
|
+
const script = `display dialog ${appleString(text)} with title ${appleString(caption)} buttons {${appleString(no)}, ${appleString(yes)}} default button ${appleString(yes)} giving up after ${Math.max(1, Math.round(timeoutMs / 1000))}`;
|
|
404
|
+
return new Promise((resolve) => {
|
|
405
|
+
execFile('/usr/bin/osascript', ['-e', script], { timeout: timeoutMs + 5000 }, (err, stdout) => {
|
|
406
|
+
// "User canceled" and a closed dialog both come back as an error
|
|
407
|
+
resolve(err ? 'no' : dialogAnswer(stdout, yes));
|
|
408
|
+
});
|
|
409
|
+
});
|
|
410
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Displays in an engine's own global coordinates and the mapping to a display's physical pixels.
|
|
3
|
+
* The global unit is a physical pixel on Windows (the engine is per-monitor DPI aware) and under
|
|
4
|
+
* X11, and a point on macOS, where each display has its own number of pixels per point. Displays
|
|
5
|
+
* need not touch: Windows leaves gaps between displays of different scale factors.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export interface NativeDisplay {
|
|
9
|
+
/** Stays the same while the display stays connected. */
|
|
10
|
+
id: string;
|
|
11
|
+
primary: boolean;
|
|
12
|
+
/** Top-left corner and size in global units. */
|
|
13
|
+
x: number;
|
|
14
|
+
y: number;
|
|
15
|
+
width: number;
|
|
16
|
+
height: number;
|
|
17
|
+
/** Physical pixels per global unit. */
|
|
18
|
+
scale: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Left to right, then top to bottom: the order the bot numbers them in, from 1. */
|
|
22
|
+
export function ordered(list: readonly NativeDisplay[]): NativeDisplay[] {
|
|
23
|
+
return [...list].sort((a, b) => a.x - b.x || a.y - b.y);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Names the arrangement: any display added, removed, moved, resized or rescaled changes it. */
|
|
27
|
+
export function layoutOf(list: readonly NativeDisplay[]): string {
|
|
28
|
+
return list.map((d) => `${d.id}@${d.x},${d.y},${d.width}x${d.height}*${d.scale}`).join('|');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function physicalSize(d: NativeDisplay): { width: number; height: number } {
|
|
32
|
+
return { width: Math.round(d.width * d.scale), height: Math.round(d.height * d.scale) };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A physical pixel of `d` in global units. */
|
|
36
|
+
export function toNative(d: NativeDisplay, x: number, y: number): { x: number; y: number } {
|
|
37
|
+
return { x: d.x + x / d.scale, y: d.y + y / d.scale };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A global point in physical pixels of `d`. */
|
|
41
|
+
export function toLocal(d: NativeDisplay, x: number, y: number): { x: number; y: number } {
|
|
42
|
+
return { x: Math.round((x - d.x) * d.scale), y: Math.round((y - d.y) * d.scale) };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Index in `list` of the display holding the global point, -1 when none does. */
|
|
46
|
+
export function displayAt(list: readonly NativeDisplay[], x: number, y: number): number {
|
|
47
|
+
return list.findIndex((d) => x >= d.x && y >= d.y && x < d.x + d.width && y < d.y + d.height);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The `w`×`h` block at (`x`, `y`) of a top-down BGRA image `width` wide. */
|
|
51
|
+
export function crop(bgra: Uint8Array, width: number, x: number, y: number, w: number, h: number): Uint8Array {
|
|
52
|
+
const out = new Uint8Array(w * h * 4);
|
|
53
|
+
for (let row = 0; row < h; row++) out.set(bgra.subarray(((y + row) * width + x) * 4, ((y + row) * width + x + w) * 4), row * w * 4);
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An engine error the bot reads in a receipt. The engine child does not know the model-text language,
|
|
3
|
+
* so it sends `code` and `args`, and the World words them (`engineErrors` in model-text.ts).
|
|
4
|
+
*/
|
|
5
|
+
export type EngineErrorCode =
|
|
6
|
+
| 'macScreenPermission' | 'macInputPermission' | 'macNoKey'
|
|
7
|
+
| 'x11Display' | 'linuxNoScreenshot' | 'linuxPixelFormat' | 'linuxNoKey' | 'linuxNoXdotool'
|
|
8
|
+
| 'winBitBlt' | 'winGetDIBits' | 'winSendInput' | 'winSetCursorPos'
|
|
9
|
+
| 'layoutChanged' | 'noDisplay';
|
|
10
|
+
|
|
11
|
+
export class EngineFailure extends Error {
|
|
12
|
+
constructor(readonly code: EngineErrorCode, readonly args: Array<string | number> = []) {
|
|
13
|
+
super(`${code}${args.length ? ` ${args.join(' ')}` : ''}`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** The system's keyboard target, independent of the windows offered for listing and focus. */
|
|
2
|
+
export interface ForegroundWindow {
|
|
3
|
+
/** Empty when the window is untitled or its title cannot be read. */
|
|
4
|
+
title: string;
|
|
5
|
+
app: string | null;
|
|
6
|
+
/** Native screen coordinates; null when the focused window's bounds cannot be read. */
|
|
7
|
+
rect: { x: number; y: number; width: number; height: number } | null;
|
|
8
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Screenshot post-processing: area-average downscale from BGRA to RGBA, a cursor arrow drawn
|
|
3
|
+
* at the pointer (screen captures do not contain the cursor), and JPEG encoding. JPEG keeps a
|
|
4
|
+
* 1280×800 desktop around 100–250 KB, which matters because every screenshot stays in the
|
|
5
|
+
* model's context and is re-sent with each request.
|
|
6
|
+
*/
|
|
7
|
+
import jpeg from 'jpeg-js';
|
|
8
|
+
|
|
9
|
+
export interface Scaled { width: number; height: number; scale: number }
|
|
10
|
+
|
|
11
|
+
/** Output size that fits `maxWidth`×`maxHeight` without upscaling. */
|
|
12
|
+
export function fit(width: number, height: number, maxWidth: number, maxHeight: number): Scaled {
|
|
13
|
+
const scale = Math.min(1, maxWidth / width, maxHeight / height);
|
|
14
|
+
return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)), scale };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function downscale(bgra: Uint8Array, width: number, height: number, out: Scaled): Uint8Array {
|
|
18
|
+
const rgba = new Uint8Array(out.width * out.height * 4);
|
|
19
|
+
const fx = width / out.width, fy = height / out.height;
|
|
20
|
+
for (let oy = 0; oy < out.height; oy++) {
|
|
21
|
+
const y0 = Math.floor(oy * fy), y1 = Math.max(y0 + 1, Math.floor((oy + 1) * fy));
|
|
22
|
+
for (let ox = 0; ox < out.width; ox++) {
|
|
23
|
+
const x0 = Math.floor(ox * fx), x1 = Math.max(x0 + 1, Math.floor((ox + 1) * fx));
|
|
24
|
+
let r = 0, g = 0, b = 0, n = 0;
|
|
25
|
+
for (let y = y0; y < y1 && y < height; y++) {
|
|
26
|
+
let i = (y * width + x0) * 4;
|
|
27
|
+
for (let x = x0; x < x1 && x < width; x++, i += 4) { b += bgra[i]; g += bgra[i + 1]; r += bgra[i + 2]; n++; }
|
|
28
|
+
}
|
|
29
|
+
const o = (oy * out.width + ox) * 4;
|
|
30
|
+
rgba[o] = r / n; rgba[o + 1] = g / n; rgba[o + 2] = b / n; rgba[o + 3] = 255;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return rgba;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Standard arrow pointer, 12×19: '#' outline, '.' fill.
|
|
37
|
+
const ARROW = [
|
|
38
|
+
'#', '##', '#.#', '#..#', '#...#', '#....#', '#.....#', '#......#', '#.......#', '#........#',
|
|
39
|
+
'#.........#', '#......####', '#...#..#', '#..##..#', '#.# #..#', '## #..#', '# #..#', ' #..#', ' ##',
|
|
40
|
+
];
|
|
41
|
+
|
|
42
|
+
export function drawCursor(rgba: Uint8Array, width: number, height: number, cx: number, cy: number): void {
|
|
43
|
+
ARROW.forEach((row, dy) => {
|
|
44
|
+
for (let dx = 0; dx < row.length; dx++) {
|
|
45
|
+
const ch = row[dx];
|
|
46
|
+
if (ch !== '#' && ch !== '.') continue;
|
|
47
|
+
const x = Math.round(cx) + dx, y = Math.round(cy) + dy;
|
|
48
|
+
if (x < 0 || y < 0 || x >= width || y >= height) continue;
|
|
49
|
+
const o = (y * width + x) * 4, v = ch === '#' ? 0 : 255;
|
|
50
|
+
rgba[o] = v; rgba[o + 1] = v; rgba[o + 2] = v;
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function encodeJpeg(rgba: Uint8Array, width: number, height: number, quality: number): Uint8Array {
|
|
56
|
+
return jpeg.encode({ data: rgba, width, height }, quality).data;
|
|
57
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Key names for `speed_pet_cua_key`: a sequence of chords separated by spaces, each chord keys joined
|
|
3
|
+
* by `+` ("ctrl+s", "alt+f4", "ctrl+a delete"). Names are case-insensitive; letters, digits
|
|
4
|
+
* and the US-layout punctuation keys stand for themselves. Virtual-key codes are Windows'.
|
|
5
|
+
*/
|
|
6
|
+
import { MODEL_TEXT, type ModelLanguage } from '../model-text.ts';
|
|
7
|
+
|
|
8
|
+
export interface KeyCode { vk: number; extended: boolean }
|
|
9
|
+
|
|
10
|
+
const NAMED: Record<string, KeyCode> = {};
|
|
11
|
+
const add = (names: string[], vk: number, extended = false) => { for (const n of names) NAMED[n] = { vk, extended }; };
|
|
12
|
+
add(['ctrl', 'control'], 0x11);
|
|
13
|
+
add(['shift'], 0x10);
|
|
14
|
+
add(['alt', 'option'], 0x12);
|
|
15
|
+
add(['win', 'windows', 'meta', 'super', 'cmd', 'command'], 0x5B, true);
|
|
16
|
+
add(['enter', 'return'], 0x0D);
|
|
17
|
+
add(['esc', 'escape'], 0x1B);
|
|
18
|
+
add(['tab'], 0x09);
|
|
19
|
+
add(['space'], 0x20);
|
|
20
|
+
add(['backspace'], 0x08);
|
|
21
|
+
add(['delete', 'del'], 0x2E, true);
|
|
22
|
+
add(['insert', 'ins'], 0x2D, true);
|
|
23
|
+
add(['home'], 0x24, true);
|
|
24
|
+
add(['end'], 0x23, true);
|
|
25
|
+
add(['pageup', 'pgup'], 0x21, true);
|
|
26
|
+
add(['pagedown', 'pgdn'], 0x22, true);
|
|
27
|
+
add(['left'], 0x25, true);
|
|
28
|
+
add(['up'], 0x26, true);
|
|
29
|
+
add(['right'], 0x27, true);
|
|
30
|
+
add(['down'], 0x28, true);
|
|
31
|
+
add(['capslock'], 0x14);
|
|
32
|
+
add(['printscreen', 'prtsc'], 0x2C, true);
|
|
33
|
+
add(['menu', 'apps', 'contextmenu'], 0x5D, true);
|
|
34
|
+
add(['volumeup'], 0xAF, true);
|
|
35
|
+
add(['volumedown'], 0xAE, true);
|
|
36
|
+
add(['volumemute', 'mute'], 0xAD, true);
|
|
37
|
+
add(['playpause'], 0xB3, true);
|
|
38
|
+
for (let i = 1; i <= 24; i++) add([`f${i}`], 0x6F + i);
|
|
39
|
+
const PUNCT: Record<string, number> = { ';': 0xBA, '=': 0xBB, ',': 0xBC, '-': 0xBD, '.': 0xBE, '/': 0xBF, '`': 0xC0, '[': 0xDB, '\\': 0xDC, ']': 0xDD, "'": 0xDE };
|
|
40
|
+
for (const [ch, vk] of Object.entries(PUNCT)) add([ch], vk);
|
|
41
|
+
add(['plus'], 0xBB);
|
|
42
|
+
add(['minus'], 0xBD);
|
|
43
|
+
|
|
44
|
+
export function keyCode(name: string): KeyCode | null {
|
|
45
|
+
const n = name.trim().toLowerCase();
|
|
46
|
+
if (NAMED[n]) return NAMED[n];
|
|
47
|
+
if (/^[a-z]$/.test(n)) return { vk: n.toUpperCase().charCodeAt(0), extended: false };
|
|
48
|
+
if (/^[0-9]$/.test(n)) return { vk: n.charCodeAt(0), extended: false };
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Parses "ctrl+a delete" into chords; the error, in the model-text language, names the first unknown key. */
|
|
53
|
+
export function parseKeys(spec: string, language: ModelLanguage = 'zh'): { chords: KeyCode[][] } | { error: string } {
|
|
54
|
+
const t = MODEL_TEXT[language];
|
|
55
|
+
const chords: KeyCode[][] = [];
|
|
56
|
+
for (const part of spec.trim().split(/\s+/)) {
|
|
57
|
+
if (!part) continue;
|
|
58
|
+
// a lone "+" is the key itself; "ctrl++" is ctrl and plus
|
|
59
|
+
const names = part === '+' ? ['plus'] : part.endsWith('++') ? [...part.slice(0, -2).split('+'), 'plus'] : part.split('+');
|
|
60
|
+
const chord: KeyCode[] = [];
|
|
61
|
+
for (const name of names) {
|
|
62
|
+
const code = keyCode(name);
|
|
63
|
+
if (!code) return { error: t.keyUnknown(name) };
|
|
64
|
+
chord.push(code);
|
|
65
|
+
}
|
|
66
|
+
if (chord.length) chords.push(chord);
|
|
67
|
+
}
|
|
68
|
+
if (!chords.length) return { error: t.keyNone };
|
|
69
|
+
return { chords };
|
|
70
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Windows virtual-key codes (what `keys.ts` parses) to X11 keysyms, and the exit code of a zenity
|
|
3
|
+
* question. Pure, so it is tested on every platform.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const KEYSYMS: Record<number, number> = {
|
|
7
|
+
0x10: 0xffe1, 0x11: 0xffe3, 0x12: 0xffe9, 0x5b: 0xffeb, // Shift_L, Control_L, Alt_L, Super_L
|
|
8
|
+
0x0d: 0xff0d, 0x1b: 0xff1b, 0x09: 0xff09, 0x20: 0x0020, 0x08: 0xff08, 0x2e: 0xffff, 0x2d: 0xff63,
|
|
9
|
+
0x24: 0xff50, 0x23: 0xff57, 0x21: 0xff55, 0x22: 0xff56, 0x25: 0xff51, 0x26: 0xff52, 0x27: 0xff53, 0x28: 0xff54,
|
|
10
|
+
0x14: 0xffe5, 0x2c: 0xff61, 0x5d: 0xff67,
|
|
11
|
+
// XF86AudioRaiseVolume, LowerVolume, Mute, Play
|
|
12
|
+
0xaf: 0x1008ff13, 0xae: 0x1008ff11, 0xad: 0x1008ff12, 0xb3: 0x1008ff14,
|
|
13
|
+
// US-layout punctuation: ; = , - . / ` [ \ ] '
|
|
14
|
+
0xba: 0x3b, 0xbb: 0x3d, 0xbc: 0x2c, 0xbd: 0x2d, 0xbe: 0x2e, 0xbf: 0x2f, 0xc0: 0x60, 0xdb: 0x5b, 0xdc: 0x5c, 0xdd: 0x5d, 0xde: 0x27,
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/** The keysym for a Windows virtual-key code, or null for a key X11 has no name for. */
|
|
18
|
+
export function linuxKeysym(vk: number): number | null {
|
|
19
|
+
if (KEYSYMS[vk] !== undefined) return KEYSYMS[vk]!;
|
|
20
|
+
if (vk >= 0x41 && vk <= 0x5a) return vk + 0x20; // a–z
|
|
21
|
+
if (vk >= 0x30 && vk <= 0x39) return vk; // 0–9
|
|
22
|
+
if (vk >= 0x70 && vk <= 0x87) return 0xffbe + (vk - 0x70); // F1–F24
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** What `zenity --question --timeout` exited with: 0 for the yes button, 5 when time ran out, anything else no. */
|
|
27
|
+
export function zenityAnswer(code: number | null): 'yes' | 'no' | 'timeout' {
|
|
28
|
+
return code === 0 ? 'yes' : code === 5 ? 'timeout' : 'no';
|
|
29
|
+
}
|