@reticlehq/computer 0.0.0-stage → 3.11.0

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.
Files changed (63) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +12 -0
  3. package/README.md +217 -2
  4. package/bin/attach.mjs +330 -0
  5. package/dist/attach.d.ts +105 -0
  6. package/dist/attach.js +234 -0
  7. package/dist/channels.d.ts +42 -0
  8. package/dist/channels.js +46 -0
  9. package/dist/computer-realm.d.ts +54 -0
  10. package/dist/computer-realm.js +487 -0
  11. package/dist/doctor.d.ts +32 -0
  12. package/dist/doctor.js +42 -0
  13. package/dist/driver.d.ts +227 -0
  14. package/dist/driver.js +73 -0
  15. package/dist/effect.d.ts +60 -0
  16. package/dist/effect.js +158 -0
  17. package/dist/files.d.ts +16 -0
  18. package/dist/files.js +40 -0
  19. package/dist/hud/port.d.ts +44 -0
  20. package/dist/hud/port.js +6 -0
  21. package/dist/index.d.ts +34 -0
  22. package/dist/index.js +22 -0
  23. package/dist/lines.d.ts +34 -0
  24. package/dist/lines.js +80 -0
  25. package/dist/mac/from-ax.d.ts +27 -0
  26. package/dist/mac/from-ax.js +275 -0
  27. package/dist/mac/mac-driver.d.ts +42 -0
  28. package/dist/mac/mac-driver.js +355 -0
  29. package/dist/mac/mac-hud.d.ts +10 -0
  30. package/dist/mac/mac-hud.js +142 -0
  31. package/dist/peer/act-effect.d.ts +9 -0
  32. package/dist/peer/act-effect.js +13 -0
  33. package/dist/peer/commands.d.ts +87 -0
  34. package/dist/peer/commands.js +811 -0
  35. package/dist/peer/form.d.ts +62 -0
  36. package/dist/peer/form.js +103 -0
  37. package/dist/peer/link-switch.d.ts +12 -0
  38. package/dist/peer/link-switch.js +38 -0
  39. package/dist/peer/peer.d.ts +43 -0
  40. package/dist/peer/peer.js +216 -0
  41. package/dist/peer/pointer.d.ts +97 -0
  42. package/dist/peer/pointer.js +289 -0
  43. package/dist/peer/scroll.d.ts +12 -0
  44. package/dist/peer/scroll.js +157 -0
  45. package/dist/peer/seen.d.ts +18 -0
  46. package/dist/peer/seen.js +61 -0
  47. package/dist/peer/select.d.ts +27 -0
  48. package/dist/peer/select.js +78 -0
  49. package/dist/peer/window.d.ts +25 -0
  50. package/dist/peer/window.js +111 -0
  51. package/dist/ui-node.d.ts +93 -0
  52. package/dist/ui-node.js +192 -0
  53. package/dist/win/helper-launch.d.ts +10 -0
  54. package/dist/win/helper-launch.js +34 -0
  55. package/native/linux/Dockerfile +12 -0
  56. package/native/linux/reticle-atspi.py +933 -0
  57. package/native/linux/sandbox.mjs +127 -0
  58. package/native/mac/build/reticle-ax +0 -0
  59. package/native/mac/build/reticle-hud +0 -0
  60. package/native/mac/hud.swift +749 -0
  61. package/native/mac/reticle-ax.swift +1786 -0
  62. package/native/win/reticle-uia.ps1 +620 -0
  63. package/package.json +65 -3
@@ -0,0 +1,289 @@
1
+ /**
2
+ * The real pointer: which action of a tool is which gesture, what to say when a gesture needs
3
+ * the foreground, and where on the screen a point of a picture of the window is.
4
+ */
5
+ import { ACT_POINT_ARG, ActionType, DRAG_TO_PICTURE_POINT_ARG, DRAG_TO_POINT_ARG, PICTURE_POINT_ARG, boxFractionFromArgs, pointInBox, } from '@reticlehq/core';
6
+ import { ActKind } from '../driver.js';
7
+ import { UiRole, placeShown } from '../ui-node.js';
8
+ import { KIND_OF } from './form.js';
9
+ /** True when a window is not where it was when its picture was taken. Half a point is noise. */
10
+ function frameMoved(then, now) {
11
+ if (then === undefined || now === undefined) {
12
+ return false;
13
+ }
14
+ return then.some((value, at) => Math.abs(value - (now[at] ?? value)) > 0.5);
15
+ }
16
+ /**
17
+ * True when the window that holds the target is not at a place where a window of the application
18
+ * was when the picture was taken. Any window: an application with several windows (Finder) was
19
+ * refused for each one but its largest, which is the one the picture remembered.
20
+ */
21
+ export function windowMoved(picture, now) {
22
+ if (picture?.windows === undefined || now === undefined) {
23
+ return frameMoved(picture?.appWindow, now);
24
+ }
25
+ return !picture.windows.some((then) => !frameMoved(then, now));
26
+ }
27
+ /** The frame of each window of the application. */
28
+ export function windowFramesOf(root) {
29
+ const windows = UiRole.WINDOW === root.role ? [root] : root.children.filter((c) => UiRole.WINDOW === c.role);
30
+ return windows.flatMap((w) => (w.frame === undefined ? [] : [w.frame]));
31
+ }
32
+ /** The place of each element on the screen, by its key. */
33
+ export function placesOf(root) {
34
+ const out = new Map();
35
+ for (const p of placeShown(root).shown) {
36
+ if (p.node.frame !== undefined) {
37
+ out.set(p.key, p.node.frame);
38
+ }
39
+ }
40
+ return out;
41
+ }
42
+ /**
43
+ * True when the content of the window moved after the picture: an element that has the same
44
+ * size is at another place, as the rows of a list that scrolled. A value that changes in its
45
+ * place, as a clock, does not move the content.
46
+ */
47
+ export function contentMoved(then, now) {
48
+ for (const [key, was] of then ?? []) {
49
+ const is = now.get(key);
50
+ const sameSize = is !== undefined && is[2] === was[2] && is[3] === was[3];
51
+ if (sameSize && (is[0] !== was[0] || is[1] !== was[1])) {
52
+ return true;
53
+ }
54
+ }
55
+ return false;
56
+ }
57
+ /**
58
+ * The point on the screen for a point of the last picture, in its pixels (`args.point`).
59
+ * Only the kinds that use the real pointer take a point. Absent answer: no point was given.
60
+ */
61
+ export function pointOnScreen(picture, at, kind) {
62
+ const point = 'object' === typeof at && null !== at ? at : {};
63
+ const { x, y } = point;
64
+ if ('number' !== typeof x || 'number' !== typeof y) {
65
+ return undefined;
66
+ }
67
+ if (!POINT_KINDS.has(kind)) {
68
+ throw new Error('args.point is a point for the real pointer. Send it with args: { foreground: true } on click, dblclick, hover or drag.');
69
+ }
70
+ if (picture === undefined) {
71
+ throw new Error('args.point is a point of a picture of the window, and no picture was taken. Take one first: reticle_screenshot.');
72
+ }
73
+ const { window, scale } = picture;
74
+ return `${String(window[0] + x / scale)},${String(window[1] + y / scale)}`;
75
+ }
76
+ /** What the helper says when the terminal may not record the screen. */
77
+ export const NO_SCREEN_RECORDING = 'no-screen-recording-permission';
78
+ /** The kinds that can go to a point of a picture, and not to the middle of an element. */
79
+ export const POINT_KINDS = new Set([
80
+ ActKind.CLICK,
81
+ ActKind.DBLCLICK,
82
+ ActKind.RIGHTCLICK,
83
+ ActKind.HOVER,
84
+ ActKind.DRAG,
85
+ ActKind.WHEEL,
86
+ ]);
87
+ const asPoint = (p) => `${String(p.x)},${String(p.y)}`;
88
+ const boxOf = (f) => ({ x: f[0], y: f[1], width: f[2], height: f[3] });
89
+ /**
90
+ * Refuses `at` or `to` when it is not a fraction from 0 to 1. A page moves such a point to the edge
91
+ * of the box. Here a model that thinks in pixels of the screenshot sends `at: { x: 600, y: 400 }`,
92
+ * and the edge was a click in the wrong place that reported done.
93
+ */
94
+ function fractionOnly(more, key, pixelKey) {
95
+ const raw = more[key];
96
+ if ('object' !== typeof raw || null === raw) {
97
+ return;
98
+ }
99
+ const { x, y } = raw;
100
+ const outside = [x, y].some((n) => 'number' === typeof n && (n < 0 || n > 1));
101
+ if (outside) {
102
+ throw new Error(`args.${key} is a fraction of the element's box, from 0 to 1. For a pixel of the last picture of the screen, use args.${pixelKey}.`);
103
+ }
104
+ }
105
+ /** Whether the act names a point of a picture: the picture can be old, so it is checked. */
106
+ export function usesPicture(more) {
107
+ return more[PICTURE_POINT_ARG] !== undefined || more[DRAG_TO_PICTURE_POINT_ARG] !== undefined;
108
+ }
109
+ /**
110
+ * Where the pointer goes, as "x,y" on the screen: a point of the last picture (`point`), or a
111
+ * point of the element's box (`at`, fractions from 0 to 1, as in a page). Absent: the middle.
112
+ */
113
+ export function pointFor(picture, more, kind, frame) {
114
+ fractionOnly(more, ACT_POINT_ARG, PICTURE_POINT_ARG);
115
+ const fromPicture = pointOnScreen(picture, more[PICTURE_POINT_ARG], kind);
116
+ if (fromPicture !== undefined) {
117
+ return fromPicture;
118
+ }
119
+ const at = boxFractionFromArgs(more, ACT_POINT_ARG);
120
+ if (at === undefined || frame === undefined) {
121
+ return undefined;
122
+ }
123
+ if (!POINT_KINDS.has(kind)) {
124
+ throw new Error(`args.${ACT_POINT_ARG} is a point for the real pointer, not for this action.`);
125
+ }
126
+ return asPoint(pointInBox(boxOf(frame), at));
127
+ }
128
+ /**
129
+ * The value of a drag for the helper: "x,y" of the end, or "x,y,x,y" from a start to the end. The
130
+ * end is a point of the last picture (`toPoint`), the middle of another element (`toRef`), or a
131
+ * point of the element's own box (`to`), as a slider is dragged.
132
+ */
133
+ export function dragValue(picture, more, frame, ontoFrame) {
134
+ fractionOnly(more, DRAG_TO_POINT_ARG, DRAG_TO_PICTURE_POINT_ARG);
135
+ // A path of the picture: a stroke of a brush, a lasso, a curve. Each point is a point of the
136
+ // last picture, as `point` is, and the drag goes through all of them in order.
137
+ const path = more[PATH_ARG];
138
+ if (Array.isArray(path)) {
139
+ const points = path.map((p) => pointOnScreen(picture, p, ActKind.DRAG));
140
+ if (points.length < 2 || points.some((p) => p === undefined)) {
141
+ throw new Error(`args.${PATH_ARG} is a list of at least two points of the last picture: [{ x, y }, { x, y }, ...]. Take a picture with reticle_screenshot first.`);
142
+ }
143
+ return points.join(',');
144
+ }
145
+ const start = pointFor(picture, more, ActKind.DRAG, frame);
146
+ const to = boxFractionFromArgs(more, DRAG_TO_POINT_ARG);
147
+ let end = pointOnScreen(picture, more[DRAG_TO_PICTURE_POINT_ARG], ActKind.DRAG);
148
+ if (end === undefined && ontoFrame !== undefined) {
149
+ end = asPoint({ x: ontoFrame[0] + ontoFrame[2] / 2, y: ontoFrame[1] + ontoFrame[3] / 2 });
150
+ }
151
+ if (end === undefined && to !== undefined && frame !== undefined) {
152
+ end = asPoint(pointInBox(boxOf(frame), to));
153
+ }
154
+ if (end === undefined) {
155
+ throw new Error(`${ActionType.DRAG} needs where to drag to: args: { toRef: "<ref>" }, { toPoint: { x, y } } in the pixels of the last picture, or { to: { x, y } } as fractions of the element's box.`);
156
+ }
157
+ return start === undefined ? end : `${start},${end}`;
158
+ }
159
+ /** The mouse button a click asks for. Only the right one changes anything. */
160
+ const RIGHT_BUTTON = 'right';
161
+ /**
162
+ * The kind of action of the realm for an action of a tool. A click with the right button is the
163
+ * menu a right-click gives: asked for by name in the background, and the real button in the
164
+ * foreground. A click in the foreground is the real pointer.
165
+ */
166
+ export function kindFor(action, more, foreground) {
167
+ if (action === ActionType.CLICK && RIGHT_BUTTON === more['button']) {
168
+ return foreground ? ActKind.RIGHTCLICK : ActKind.MENU;
169
+ }
170
+ if (action === ActionType.CLICK && foreground) {
171
+ return ActKind.CLICK;
172
+ }
173
+ return KIND_OF[action];
174
+ }
175
+ /** What to say when an action needs the real pointer and the caller did not ask for it. */
176
+ export function needsForeground(action, app) {
177
+ return `${action} needs the real pointer. It brings ${app} to the front and takes the pointer of the person at the machine for a moment, then puts both back. Send it again with args: { foreground: true }.`;
178
+ }
179
+ /**
180
+ * Where the pointer of the HUD goes for an action: the place it starts, and for a drag the place
181
+ * it ends, as a hand presses at one place and lets go at another. The start is the point of the
182
+ * action when it has one, or the middle of the element. A drag gives "x,y" (the end) or "x,y,x,y"
183
+ * (the start and the end), and a wheel gives "lines,x,y".
184
+ */
185
+ export function pointerPath(kind, value, frame) {
186
+ // The points come before the hand ("|mods=..."), and a path has more than two.
187
+ const n = (value ?? '')
188
+ .split('|')[0]
189
+ ?.split(',')
190
+ .filter((x) => x !== '')
191
+ .map(Number) ?? [];
192
+ const pair = (at) => {
193
+ const [x, y] = [n[at], n[at + 1]];
194
+ return x !== undefined && y !== undefined && Number.isFinite(x) && Number.isFinite(y)
195
+ ? [x, y]
196
+ : undefined;
197
+ };
198
+ const middle = frame === undefined ? undefined : [frame[0] + frame[2] / 2, frame[1] + frame[3] / 2];
199
+ if (kind === ActKind.DRAG) {
200
+ const fromPoint = n.length >= 4;
201
+ const start = fromPoint ? pair(0) : middle;
202
+ const end = pair(n.length - 2);
203
+ return { ...(start === undefined ? {} : { start }), ...(end === undefined ? {} : { end }) };
204
+ }
205
+ let at;
206
+ if (kind === ActKind.WHEEL) {
207
+ at = 3 === n.length ? pair(1) : undefined;
208
+ }
209
+ else if (POINT_KINDS.has(kind) && 2 === n.length) {
210
+ at = pair(0);
211
+ }
212
+ const start = at ?? middle;
213
+ return start === undefined ? {} : { start };
214
+ }
215
+ /** A drag along points of the picture. */
216
+ export const PATH_ARG = 'path';
217
+ /** The keys held through a pointer action, as a key takes them: ["Shift", "Alt"]. */
218
+ const MODIFIERS_ARG = 'modifiers';
219
+ /** How long the button stays down before the pointer moves or lets go, in milliseconds. */
220
+ export const HOLD_ARG = 'holdMs';
221
+ /** How many clicks: 2 is a double-click, 3 a triple-click. */
222
+ const CLICK_COUNT_ARG = 'clickCount';
223
+ const MIDDLE_BUTTON = 'middle';
224
+ const MAX_HOLD_MS = 10_000;
225
+ /**
226
+ * How the hand holds a pointer action, after its points: "|mods=shift+alt|hold=300". The keys held
227
+ * through a click or a drag (shift-click to add to a choice, option-drag for a copy) and the time
228
+ * the button stays down. A click in the background is a press, which holds no key: it is refused,
229
+ * as nothing else would show that the keys were not held.
230
+ */
231
+ /** Roles whose effect can be only in pixels: a photo, a canvas, a frame of video, a window. */
232
+ const CANVAS_ROLES = new Set(['img', 'group', 'window', 'application']);
233
+ /**
234
+ * Whether the helper compares pictures of the window for this action. Only for a point of a
235
+ * picture or an element that can be a canvas: each picture costs a wait for the window to draw,
236
+ * and a button shows its effect in its elements.
237
+ */
238
+ export function wantsPixels(role, more) {
239
+ return (CANVAS_ROLES.has(role) ||
240
+ [PICTURE_POINT_ARG, PATH_ARG, DRAG_TO_PICTURE_POINT_ARG].some((key) => more[key] !== undefined));
241
+ }
242
+ export function handOf(kind, more, pixels = false) {
243
+ // A key press takes its modifiers in its key: only a pointer action takes a hand.
244
+ if (kind === ActKind.KEY) {
245
+ return '';
246
+ }
247
+ const keys = Array.isArray(more[MODIFIERS_ARG])
248
+ ? more[MODIFIERS_ARG].map(String)
249
+ : [];
250
+ const hold = 'number' === typeof more[HOLD_ARG] ? Math.min(MAX_HOLD_MS, Math.max(0, more[HOLD_ARG])) : 0;
251
+ const count = more[CLICK_COUNT_ARG];
252
+ if (count !== undefined && !(1 === count || 2 === count || 3 === count)) {
253
+ throw new Error(`args.${CLICK_COUNT_ARG} is 1, 2 or 3: a triple-click chooses a line or a paragraph.`);
254
+ }
255
+ const parts = [
256
+ 0 === keys.length ? '' : `|mods=${keys.map((k) => k.toLowerCase()).join('+')}`,
257
+ 0 === hold ? '' : `|hold=${String(hold)}`,
258
+ 'number' === typeof count && count > 1 ? `|count=${String(count)}` : '',
259
+ MIDDLE_BUTTON === more['button'] ? `|button=${MIDDLE_BUTTON}` : '',
260
+ ].join('');
261
+ const compare = pixels && POINT_KINDS.has(kind) ? '|pixels=1' : '';
262
+ if ('' === parts) {
263
+ return compare;
264
+ }
265
+ if (!POINT_KINDS.has(kind)) {
266
+ throw new Error(`keys held through a click, a held button, more than one click and the middle button need the real pointer: add args.foreground: true. A ${kind} in the background has none of them.`);
267
+ }
268
+ return `${parts}${compare}`;
269
+ }
270
+ /** A word the reader is less sure of than this is noise on a canvas. */
271
+ const MIN_TEXT_CONFIDENCE = 0.3;
272
+ /** The most words of one picture in an answer. */
273
+ const MAX_TEXTS = 200;
274
+ /**
275
+ * The words of a picture for the answer: a canvas has no elements, and the box of a word is a
276
+ * point an agent can click. Declared: `textsCut` counts the words left out, unsure or past the
277
+ * most.
278
+ */
279
+ export function wordsOfPicture(read) {
280
+ if (read === undefined) {
281
+ return {};
282
+ }
283
+ const kept = read
284
+ .filter((word) => word.confidence >= MIN_TEXT_CONFIDENCE)
285
+ .slice(0, MAX_TEXTS)
286
+ .map(({ text, box }) => ({ text, box }));
287
+ const cut = read.length - kept.length;
288
+ return { texts: kept, ...(cut > 0 ? { textsCut: cut } : {}) };
289
+ }
@@ -0,0 +1,12 @@
1
+ import type { SelectContext } from './select.js';
2
+ /**
3
+ * Scrolls the scroll area that holds an element, by moving its scroll bar. No wheel event is
4
+ * sent: a wheel event does not reach an application that is not in front, and it would use the
5
+ * pointer of the person at the machine.
6
+ *
7
+ * `fraction` is the place of the bar, 0 to 1. `dy` moves the bar one step in its direction; the
8
+ * realm does not know the height of the content, so it cannot scroll by pixels, and it says so.
9
+ */
10
+ /** The point on the screen, "x,y", where the wheel turns. Set by the realm, from `args.point`. */
11
+ export declare const WHEEL_AT = "wheelAt";
12
+ export declare function scrollBy(ctx: Pick<SelectContext, 'driver' | 'refs' | 'drive'>, args: Record<string, unknown>): Promise<Record<string, unknown>>;
@@ -0,0 +1,157 @@
1
+ /**
2
+ * `scroll`: the content of a scroll area is moved, by its scroll bar or by a key.
3
+ */
4
+ import { ActKind, Delivery } from '../driver.js';
5
+ import { UiRole } from '../ui-node.js';
6
+ import { see } from './seen.js';
7
+ /** Room for an effect that comes up to a second late, and then the quiet time after it. */
8
+ const SETTLE_MS = 1500;
9
+ /** How far one `dy` scroll moves the bar: a tenth of its range. */
10
+ const SCROLL_STEP = 0.1;
11
+ /** Said in the answer of a scroll that was done with a key, because there was no scroll bar. */
12
+ const SCROLL_BY_KEY = 'key';
13
+ /** Said in the answer of a scroll that was done with the real wheel. */
14
+ const SCROLL_BY_WHEEL = 'wheel';
15
+ /** Lines of the wheel for a place (the end or the start), and for one move. */
16
+ const WHEEL_TO_END = 40;
17
+ const WHEEL_STEP = 5;
18
+ /** About how far one line of the wheel moves a view, to turn a distance into lines. */
19
+ const PIXELS_PER_LINE = 40;
20
+ /** The most turns of the wheel to an end: 10 turns of 40 lines. */
21
+ const WHEEL_TURNS_TO_END = 10;
22
+ /** The key that does what a scroll asks: the end or the start for a place, a page for a move. */
23
+ function scrollKeyFor(fraction, dy) {
24
+ if ('number' === typeof fraction) {
25
+ return fraction >= 0.5 ? 'End' : 'Home';
26
+ }
27
+ if ('number' === typeof dy && dy !== 0) {
28
+ return dy > 0 ? 'PageDown' : 'PageUp';
29
+ }
30
+ return undefined;
31
+ }
32
+ /**
33
+ * Scrolls the scroll area that holds an element, by moving its scroll bar. No wheel event is
34
+ * sent: a wheel event does not reach an application that is not in front, and it would use the
35
+ * pointer of the person at the machine.
36
+ *
37
+ * `fraction` is the place of the bar, 0 to 1. `dy` moves the bar one step in its direction; the
38
+ * realm does not know the height of the content, so it cannot scroll by pixels, and it says so.
39
+ */
40
+ /** The point on the screen, "x,y", where the wheel turns. Set by the realm, from `args.point`. */
41
+ export const WHEEL_AT = 'wheelAt';
42
+ export async function scrollBy(ctx, args) {
43
+ const given = args['ref'];
44
+ const ref = 'string' === typeof given ? given : undefined;
45
+ // Neither how far nor where to: the wheel turned 0 lines, or the bar was set to its own place,
46
+ // and the answer said that it scrolled.
47
+ const dx = 'number' === typeof args['dx'] ? args['dx'] : 0;
48
+ if ('number' !== typeof args['fraction'] &&
49
+ !('number' === typeof args['dy'] && 0 !== args['dy']) &&
50
+ 0 === dx) {
51
+ throw new Error('a scroll needs args.dy (a number of pixels: more than 0 goes down, less than 0 goes up), args.dx (more than 0 goes right) or args.fraction (a place from 0, the top, to 1, the end).');
52
+ }
53
+ // Sideways only with the real wheel: a scroll bar of the side is not looked for.
54
+ if (0 !== dx && true !== args['foreground']) {
55
+ throw new Error('a scroll sideways (args.dx) turns the real wheel: add args.foreground: true, and a ref or a point.');
56
+ }
57
+ const read = await ctx.driver.read();
58
+ const seen = see(read.root);
59
+ const key = ref === undefined ? undefined : ctx.refs.keyOf(ref);
60
+ if (ref !== undefined && !seen.some((s) => s.key === key)) {
61
+ throw new Error(`ref '${ref}' no longer resolves to an element`);
62
+ }
63
+ // The first vertical bar that is in the element's own line of parents, or the first of all.
64
+ const bars = seen.filter((s) => s.node.role === UiRole.SCROLLBAR &&
65
+ s.node.frame !== undefined &&
66
+ s.node.frame[3] > s.node.frame[2]);
67
+ const bar = key === undefined
68
+ ? bars[0]
69
+ : bars
70
+ .filter((b) => b.parentKey !== undefined && `${key}/`.startsWith(`${b.parentKey}/`))
71
+ .at(-1);
72
+ const fraction = args['fraction'];
73
+ const dy = args['dy'];
74
+ // With the foreground, the real wheel over the element, as a person scrolls. A list of a web
75
+ // view (Discord's servers) has no bar and takes no key: "Add a Server" stayed under the edge.
76
+ const over = seen.find((s) => s.key === key);
77
+ if (true === args['foreground'] && over !== undefined && ref !== undefined) {
78
+ let lines = 0;
79
+ if ('number' === typeof fraction) {
80
+ lines = fraction >= 0.5 ? WHEEL_TO_END : -WHEEL_TO_END;
81
+ }
82
+ else if ('number' === typeof dy && dy !== 0) {
83
+ lines = Math.sign(dy) * WHEEL_STEP;
84
+ }
85
+ // At a point of the picture when one is given: "lines,x,y". Else over the element. Lines to
86
+ // the side go in the hand: "|across=5" is to the right.
87
+ // A longer way to the side is more of the wheel, as a hand turns it further.
88
+ const acrossLines = Math.sign(dx) *
89
+ Math.min(WHEEL_TO_END, Math.max(WHEEL_STEP, Math.round(Math.abs(dx) / PIXELS_PER_LINE)));
90
+ const across = 0 === dx ? '' : `|across=${String(acrossLines)}`;
91
+ const at = `${'string' === typeof args[WHEEL_AT] ? `,${args[WHEEL_AT]}` : ''}${across}`;
92
+ const turn = async () => (await ctx.drive(over, ref, ActKind.WHEEL, `${String(lines)}${at}`, {
93
+ delivery: Delivery.FOREGROUND,
94
+ budgetMs: SETTLE_MS,
95
+ })).changes.length > 0;
96
+ // To an end, the wheel turns until nothing moves, as a hand does: one turn did not reach the
97
+ // end of the 300 channels of Discord. A turn that moves nothing says the end is reached.
98
+ const toEnd = 'number' === typeof fraction;
99
+ let turns = 1;
100
+ const moved = await turn();
101
+ let atEnd = !moved;
102
+ for (let last = moved; toEnd && last && turns < WHEEL_TURNS_TO_END; turns += 1) {
103
+ last = await turn();
104
+ atEnd = !last;
105
+ }
106
+ // Declared: the caller asked for a place or for pixels, and got lines of the wheel.
107
+ return {
108
+ scrolled: moved,
109
+ by: SCROLL_BY_WHEEL,
110
+ lines: lines * turns,
111
+ ...(0 === dx ? {} : { across: acrossLines * turns }),
112
+ ...(toEnd ? { atEnd } : {}),
113
+ };
114
+ }
115
+ if (bar === undefined) {
116
+ // A page in a Chromium browser has no scroll bar in its tree. A key scrolls it, also when
117
+ // the browser is not in front. The key goes to the element, or to the page, or to the window.
118
+ const target = seen.find((s) => s.key === key) ??
119
+ seen.find((s) => s.node.role === UiRole.DOCUMENT) ??
120
+ seen[0];
121
+ const scrollKey = scrollKeyFor(fraction, dy);
122
+ if (target === undefined || scrollKey === undefined) {
123
+ throw new Error('there is no scroll bar to move for this element');
124
+ }
125
+ const keyed = await ctx.drive(target, ctx.refs.refFor(target.key), ActKind.KEY, scrollKey, {
126
+ delivery: Delivery.DIRECT,
127
+ budgetMs: SETTLE_MS,
128
+ });
129
+ // Declared: the caller asked for a place or for pixels, and got one key. The place of the
130
+ // content after the key is not known, so no `fraction` and no `atEnd` are given.
131
+ return { scrolled: keyed.changes.length > 0, by: SCROLL_BY_KEY, key: scrollKey };
132
+ }
133
+ const now = Number(bar.node.value ?? '0');
134
+ let to = now;
135
+ if ('number' === typeof fraction) {
136
+ to = fraction;
137
+ }
138
+ else if ('number' === typeof dy && dy !== 0) {
139
+ to = now + Math.sign(dy) * SCROLL_STEP;
140
+ }
141
+ to = Math.min(1, Math.max(0, to));
142
+ const { changes } = await ctx.drive(bar, ctx.refs.refFor(bar.key), ActKind.SET, String(to), {
143
+ // A person scrolls with a wheel over the content, not by a click on the bar, and the bar
144
+ // of a modern scroll area is not drawn until then. So no reach check is made on the bar.
145
+ delivery: Delivery.DIRECT,
146
+ budgetMs: SETTLE_MS,
147
+ });
148
+ return {
149
+ scrolled: changes.length > 0,
150
+ atEnd: 0 === to || 1 === to,
151
+ fraction: to,
152
+ // Declared, because the caller asked for pixels and got a step.
153
+ ...('number' === typeof dy && 'number' !== typeof fraction
154
+ ? { stepInsteadOfPixels: SCROLL_STEP }
155
+ : {}),
156
+ };
157
+ }
@@ -0,0 +1,18 @@
1
+ import type { Placed, UiNode } from '../ui-node.js';
2
+ export interface Seen extends Placed {
3
+ /** The element has a size and is inside its window. It says nothing about a window on top. */
4
+ visible: boolean;
5
+ /** The name of the dialog the element is in, or an empty string. */
6
+ dialog: string;
7
+ /** The frame of the window the element is in. Absent: it is in no window. */
8
+ windowFrame?: readonly [number, number, number, number];
9
+ }
10
+ /** What is on the screen. An element with no place on it, as in a closed menu, is not here. */
11
+ export declare function see(root: UiNode): Seen[];
12
+ export declare const READ_STATE: Readonly<Partial<Record<string, (seen: Seen) => boolean>>>;
13
+ /**
14
+ * Where a key with no element goes: what has the keyboard, else the first window, else the
15
+ * application. A person types into the application in front; the server sends a document key
16
+ * (Escape, a shortcut) with no ref.
17
+ */
18
+ export declare function keyTarget(all: readonly Seen[]): Seen | undefined;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * What the peer takes for "on the screen": each element that has a place, whether it is inside its
3
+ * window, and the dialog it is in. And the states of an element that the peer can read.
4
+ */
5
+ import { ElementState } from '@reticlehq/core';
6
+ import { placeShown, UiRole } from '../ui-node.js';
7
+ function intersects(a, b) {
8
+ if (a === undefined || b === undefined) {
9
+ return false;
10
+ }
11
+ return a[0] < b[0] + b[2] && b[0] < a[0] + a[2] && a[1] < b[1] + b[3] && b[1] < a[1] + a[3];
12
+ }
13
+ /** What is on the screen. An element with no place on it, as in a closed menu, is not here. */
14
+ export function see(root) {
15
+ const placed = placeShown(root).shown;
16
+ const byKey = new Map(placed.map((p) => [p.key, p]));
17
+ return placed.map((p) => {
18
+ let window = p;
19
+ while (window !== undefined &&
20
+ window.node.role !== 'window' &&
21
+ window.parentKey !== undefined) {
22
+ window = byKey.get(window.parentKey);
23
+ }
24
+ let dialog = p;
25
+ while (dialog !== undefined &&
26
+ dialog.node.role !== 'dialog' &&
27
+ dialog.parentKey !== undefined) {
28
+ dialog = byKey.get(dialog.parentKey);
29
+ }
30
+ const frame = p.node.frame;
31
+ const sized = frame !== undefined && frame[2] > 0 && frame[3] > 0;
32
+ const inside = 'window' === window?.node.role ? intersects(frame, window.node.frame) : sized;
33
+ return {
34
+ ...p,
35
+ visible: sized && inside,
36
+ dialog: 'dialog' === dialog?.node.role ? dialog.node.name : '',
37
+ ...('window' === window?.node.role && window.node.frame !== undefined
38
+ ? { windowFrame: window.node.frame }
39
+ : {}),
40
+ };
41
+ });
42
+ }
43
+ export const READ_STATE = {
44
+ [ElementState.PRESENT]: () => true,
45
+ [ElementState.VISIBLE]: (s) => s.visible,
46
+ [ElementState.HIDDEN]: (s) => !s.visible,
47
+ [ElementState.ENABLED]: (s) => !s.node.states.includes(ElementState.DISABLED),
48
+ [ElementState.DISABLED]: (s) => s.node.states.includes(ElementState.DISABLED),
49
+ [ElementState.CHECKED]: (s) => s.node.states.includes(ElementState.CHECKED),
50
+ [ElementState.FOCUSED]: (s) => s.node.states.includes(ElementState.FOCUSED),
51
+ };
52
+ /**
53
+ * Where a key with no element goes: what has the keyboard, else the first window, else the
54
+ * application. A person types into the application in front; the server sends a document key
55
+ * (Escape, a shortcut) with no ref.
56
+ */
57
+ export function keyTarget(all) {
58
+ return (all.find((s) => s.node.states.includes(ElementState.FOCUSED)) ??
59
+ all.find((s) => s.node.role === UiRole.WINDOW) ??
60
+ all[0]);
61
+ }
@@ -0,0 +1,27 @@
1
+ import { ActKind, Delivery } from '../driver.js';
2
+ import type { ActOutcome, UiDriver } from '../driver.js';
3
+ import type { Change } from '../effect.js';
4
+ import type { RefTable } from '../lines.js';
5
+ import type { ActResult } from './form.js';
6
+ import type { Seen } from './seen.js';
7
+ interface How {
8
+ delivery: Delivery;
9
+ budgetMs: number;
10
+ }
11
+ /** What `select` needs of the peer: its reads, its refs, and its one way to act. */
12
+ export interface SelectContext {
13
+ driver: UiDriver;
14
+ refs: RefTable;
15
+ drive: (target: Seen, ref: string, kind: ActKind, value: string | undefined, how: How) => Promise<{
16
+ outcome: ActOutcome;
17
+ changes: Change[];
18
+ }>;
19
+ act: (args: Record<string, unknown>, allowed?: readonly string[]) => Promise<ActResult>;
20
+ }
21
+ /**
22
+ * Chooses one item of a pop-up as a person does: press the pop-up, read its choices, press the
23
+ * one asked for. When that choice is not there, the pop-up is closed again and the answer
24
+ * names the choices that are.
25
+ */
26
+ export declare function selectChoice(ctx: SelectContext, ref: string, more: Record<string, unknown>, allowed?: readonly string[]): Promise<ActResult>;
27
+ export {};
@@ -0,0 +1,78 @@
1
+ /**
2
+ * `select`: one choice of a pop-up or a list, taken the way a person takes it.
3
+ */
4
+ import { ActionType } from '@reticlehq/core';
5
+ import { ActKind, Delivery } from '../driver.js';
6
+ import { UiRole, place, quoted } from '../ui-node.js';
7
+ import { CHOICES_NAMED, ESCAPE, SettleReason, heldBy } from './form.js';
8
+ import { see } from './seen.js';
9
+ /** Room for an effect that comes up to a second late, and then the quiet time after it. */
10
+ const SETTLE_MS = 1500;
11
+ /**
12
+ * Chooses one item of a pop-up as a person does: press the pop-up, read its choices, press the
13
+ * one asked for. When that choice is not there, the pop-up is closed again and the answer
14
+ * names the choices that are.
15
+ */
16
+ export async function selectChoice(ctx, ref, more, allowed) {
17
+ const wanted = more['value'];
18
+ if ('string' !== typeof wanted) {
19
+ throw new Error(`${ActionType.SELECT} needs the name of the choice: args: { value: "…" }.`);
20
+ }
21
+ const read = await ctx.driver.read();
22
+ const key = ctx.refs.keyOf(ref);
23
+ const popup = see(read.root).find((s) => s.key === key);
24
+ if (popup === undefined) {
25
+ throw new Error(`ref '${ref}' no longer resolves to an element`);
26
+ }
27
+ const how = { delivery: Delivery.USER_PATH, budgetMs: SETTLE_MS };
28
+ // A list in a web view has no choice with a name below it, open or closed. A person types
29
+ // the name into the list, and the list goes to that choice. The pop-up is not opened: it is
30
+ // a window of its own there, and a key that is sent to the application does not close it.
31
+ const named = place(read.root).some((p) => p.key.startsWith(`${popup.key}/`) && p.node.role === UiRole.MENUITEM && '' !== p.node.name);
32
+ if (popup.node.role === UiRole.COMBOBOX && !named) {
33
+ return selectByTyping(ctx, popup, ref, wanted, how);
34
+ }
35
+ await ctx.drive(popup, ref, ActKind.PRESS, undefined, how);
36
+ const choices = see((await ctx.driver.read()).root).filter((s) => s.visible && s.node.role === UiRole.MENUITEM && s.key.startsWith(popup.key));
37
+ const choice = choices.find((s) => s.node.name === wanted);
38
+ if (choice === undefined) {
39
+ // The pop-up that this action opened lies over its own control, so the control is "not
40
+ // reachable" now. The key that closes the pop-up goes to the application without that check.
41
+ await ctx.drive(popup, ref, ActKind.KEY, ESCAPE, { ...how, delivery: Delivery.DIRECT });
42
+ throw new Error(`${popup.node.role} "${popup.node.name}" has no choice ${quoted(wanted)}. It has: ${choices
43
+ .slice(0, CHOICES_NAMED)
44
+ .map((s) => quoted(s.node.name))
45
+ .join(', ')}.`);
46
+ }
47
+ const pressed = await ctx.act({ ref: ctx.refs.refFor(choice.key), action: ActionType.CLICK, args: more }, allowed);
48
+ return { ...pressed, ref, action: ActionType.SELECT };
49
+ }
50
+ async function selectByTyping(ctx, popup, ref, wanted, how) {
51
+ const typed = await ctx.drive(popup, ref, ActKind.TYPE, wanted, how);
52
+ const held = heldBy(typed.outcome, popup.key);
53
+ const was = popup.node.value ?? '';
54
+ if (held !== wanted) {
55
+ if (held !== was) {
56
+ // The keys went to another choice that starts the same way. Put the old one back.
57
+ await ctx.drive(popup, ref, ActKind.TYPE, was, how);
58
+ }
59
+ throw new Error(`${popup.node.role} "${popup.node.name}" did not go to the choice ${quoted(wanted)}: it holds ${quoted(was)}. The list does not name its choices, so the realm typed the name.`);
60
+ }
61
+ const settled = typed.outcome.settled;
62
+ return {
63
+ ok: true,
64
+ ref,
65
+ action: ActionType.SELECT,
66
+ dispatched: true,
67
+ settled,
68
+ settleReason: settled ? null : SettleReason.TIMEOUT,
69
+ effect: {
70
+ dispatched: true,
71
+ targetMatched: true,
72
+ valueChanged: typed.changes.some((c) => c.value !== undefined),
73
+ domMutatedWithin: typed.changes.length,
74
+ },
75
+ role: popup.node.role,
76
+ name: popup.node.name,
77
+ };
78
+ }