@dotrino/remote-desktop-agent 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/atspi.js +331 -0
- package/bin/cli.js +116 -0
- package/desktop.js +178 -0
- package/index.js +223 -0
- package/link.js +23 -0
- package/package.json +48 -4
- package/scene.js +125 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 seyacat
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/atspi.js
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* atspi.js — lee el escritorio por su ÁRBOL DE ACCESIBILIDAD (AT-SPI), no por sus píxeles.
|
|
3
|
+
*
|
|
4
|
+
* AT-SPI es lo que usan los lectores de pantalla en Linux: cada app publica sus ventanas,
|
|
5
|
+
* botones, menús, celdas y textos, con su posición en pantalla. Va por D-Bus, en un bus
|
|
6
|
+
* propio (el de accesibilidad), y funciona igual en X11 y en Wayland. El cliente D-Bus es
|
|
7
|
+
* el del pilar (`@dotrino/proxy-client/dbus`): no se escribe otro.
|
|
8
|
+
*
|
|
9
|
+
* Lo que sale de aquí es una lista de NODOS planos, en orden de pintado (padres antes que
|
|
10
|
+
* hijos, ventanas de abajo antes que la activa), con un id corto y estable mientras el
|
|
11
|
+
* objeto viva. Quien lo manda (scene.js) solo compara listas.
|
|
12
|
+
*
|
|
13
|
+
* Dos trampas que se pagaron al probarlo (2026-11-16):
|
|
14
|
+
* - El nodo raíz de cada app NO está «visible» (no tiene SHOWING): si se corta ahí por no
|
|
15
|
+
* visible, no sale nada de ninguna app.
|
|
16
|
+
* - Chrome, VS Code, Slack y demás Electron solo publican su árbol si la accesibilidad está
|
|
17
|
+
* encendida AL ARRANCAR. Encenderla en caliente no les llega: hay que reiniciarlas una vez.
|
|
18
|
+
* Las apps GTK la publican siempre.
|
|
19
|
+
*/
|
|
20
|
+
import { openSessionBus, openBus, DBusError } from '@dotrino/proxy-client/dbus'
|
|
21
|
+
|
|
22
|
+
const ROOT_DEST = 'org.a11y.atspi.Registry'
|
|
23
|
+
const ROOT_PATH = '/org/a11y/atspi/accessible/root'
|
|
24
|
+
const DEC_PATH = '/org/a11y/atspi/registry/deviceeventcontroller'
|
|
25
|
+
const I_ACC = 'org.a11y.atspi.Accessible'
|
|
26
|
+
const I_COMP = 'org.a11y.atspi.Component'
|
|
27
|
+
const I_TEXT = 'org.a11y.atspi.Text'
|
|
28
|
+
const I_ACTION = 'org.a11y.atspi.Action'
|
|
29
|
+
const I_PROPS = 'org.freedesktop.DBus.Properties'
|
|
30
|
+
|
|
31
|
+
/** Bits de estado de AT-SPI (AtspiStateType) que importan para dibujar y actuar. */
|
|
32
|
+
export const STATE = {
|
|
33
|
+
ACTIVE: 1, CHECKED: 4, DEFUNCT: 6, EDITABLE: 7, ENABLED: 8, EXPANDABLE: 9, EXPANDED: 10,
|
|
34
|
+
FOCUSABLE: 11, FOCUSED: 12, ICONIFIED: 15, MODAL: 16, MULTI_LINE: 17, PRESSED: 20,
|
|
35
|
+
SELECTED: 23, SENSITIVE: 24, SHOWING: 25, VISIBLE: 30, INDETERMINATE: 32
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Los estados que viajan al cliente, como letras: corto y legible en una traza. */
|
|
39
|
+
const WIRE_STATES = /** @type {const} */ ([
|
|
40
|
+
['a', STATE.ACTIVE], ['c', STATE.CHECKED], ['e', STATE.EDITABLE], ['x', STATE.EXPANDED],
|
|
41
|
+
['f', STATE.FOCUSED], ['s', STATE.SELECTED], ['p', STATE.PRESSED], ['d', STATE.SENSITIVE],
|
|
42
|
+
['m', STATE.MULTI_LINE], ['i', STATE.INDETERMINATE]
|
|
43
|
+
])
|
|
44
|
+
|
|
45
|
+
/** Tope de nodos por ventana: una tabla de 50.000 filas no puede colgar al agente. */
|
|
46
|
+
export const MAX_NODES_PER_WINDOW = 4000
|
|
47
|
+
/** Tope de profundidad: hay árboles que se muerden la cola. */
|
|
48
|
+
const MAX_DEPTH = 60
|
|
49
|
+
/** Tope de hijos que se miran de un nodo (una lista enorme: lo que se ve cabe de sobra). */
|
|
50
|
+
const MAX_CHILDREN = 1500
|
|
51
|
+
/** Lo que se lee de un texto: lo que cabe en pantalla, no un documento entero. */
|
|
52
|
+
export const MAX_TEXT = 2000
|
|
53
|
+
|
|
54
|
+
/** Roles cuyo contenido es el TEXTO que tienen dentro (no solo su nombre). */
|
|
55
|
+
const TEXT_ROLES = new Set(['text', 'entry', 'password text', 'paragraph', 'label', 'static',
|
|
56
|
+
'heading', 'table cell', 'link', 'terminal', 'document text', 'caption', 'list item', 'spin button'])
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Roles que no se pueden dibujar desde la accesibilidad: lo de dentro son píxeles (un lienzo,
|
|
60
|
+
* un vídeo, una imagen). Salen como HUECO con su tamaño; en la fase 2 se rellenan con vídeo.
|
|
61
|
+
*/
|
|
62
|
+
const HOLE_ROLES = new Set(['canvas', 'drawing area', 'image', 'video', 'animation', 'embedded'])
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Un nodo tal como viaja.
|
|
66
|
+
* @typedef {{
|
|
67
|
+
* id: number, p: number, r: string, n?: string, t?: string,
|
|
68
|
+
* x: number, y: number, w: number, h: number, s?: string, a?: string[], hole?: 1
|
|
69
|
+
* }} Node
|
|
70
|
+
*/
|
|
71
|
+
|
|
72
|
+
/** Un objeto de AT-SPI: el nombre de su app en el bus y su ruta. */
|
|
73
|
+
/** @typedef {[string, string]} Ref */
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Abre el bus de accesibilidad de esta sesión gráfica.
|
|
77
|
+
* Lanza `no-session-bus` (no hay escritorio: un servidor) o `no-a11y-bus` (el escritorio no
|
|
78
|
+
* trae AT-SPI). Son errores con código, para decirle a la persona cuál de las dos cosas pasa.
|
|
79
|
+
*/
|
|
80
|
+
export async function openA11yBus () {
|
|
81
|
+
const session = await openSessionBus()
|
|
82
|
+
if (!session) throw Object.assign(new Error('no session bus: this machine has no desktop session'), { code: 'no-session-bus' })
|
|
83
|
+
try {
|
|
84
|
+
const [addr] = await session.call({ destination: 'org.a11y.Bus', path: '/org/a11y/bus', iface: 'org.a11y.Bus', member: 'GetAddress' })
|
|
85
|
+
const bus = await openBus(addr)
|
|
86
|
+
if (!bus) throw Object.assign(new Error(`the accessibility bus is not reachable at ${addr}`), { code: 'no-a11y-bus' })
|
|
87
|
+
return { session, bus }
|
|
88
|
+
} catch (e) {
|
|
89
|
+
session.close()
|
|
90
|
+
if (e instanceof DBusError) throw Object.assign(new Error('the desktop has no accessibility service (at-spi2-core)'), { code: 'no-a11y-bus' })
|
|
91
|
+
throw e
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Enciende la accesibilidad del escritorio (las apps GTK publican más, y las que se abran desde
|
|
97
|
+
* ahora también las de Chromium). Devuelve cómo estaba, para dejarla igual al irse.
|
|
98
|
+
*
|
|
99
|
+
* @param {import('@dotrino/proxy-client/dbus').DBusConnection} session
|
|
100
|
+
* @param {boolean} on
|
|
101
|
+
* @returns {Promise<{ IsEnabled: boolean, ScreenReaderEnabled: boolean }>}
|
|
102
|
+
*/
|
|
103
|
+
export async function setA11y (session, on) {
|
|
104
|
+
const { variant } = await import('@dotrino/proxy-client/dbus')
|
|
105
|
+
/** @type {{ IsEnabled: boolean, ScreenReaderEnabled: boolean }} */
|
|
106
|
+
const before = { IsEnabled: false, ScreenReaderEnabled: false }
|
|
107
|
+
for (const prop of /** @type {const} */ (['IsEnabled', 'ScreenReaderEnabled'])) {
|
|
108
|
+
const [v] = await session.call({ destination: 'org.a11y.Bus', path: '/org/a11y/bus', iface: I_PROPS, member: 'Get', signature: 'ss', body: ['org.a11y.Status', prop] })
|
|
109
|
+
before[prop] = !!v.value
|
|
110
|
+
await session.call({ destination: 'org.a11y.Bus', path: '/org/a11y/bus', iface: I_PROPS, member: 'Set', signature: 'ssv', body: ['org.a11y.Status', prop, variant('b', on)] })
|
|
111
|
+
}
|
|
112
|
+
return before
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Deja la accesibilidad como estaba antes de `setA11y`.
|
|
117
|
+
* @param {import('@dotrino/proxy-client/dbus').DBusConnection} session
|
|
118
|
+
* @param {{ IsEnabled: boolean, ScreenReaderEnabled: boolean }} before
|
|
119
|
+
*/
|
|
120
|
+
export async function restoreA11y (session, before) {
|
|
121
|
+
const { variant } = await import('@dotrino/proxy-client/dbus')
|
|
122
|
+
for (const prop of /** @type {const} */ (['IsEnabled', 'ScreenReaderEnabled'])) {
|
|
123
|
+
await session.call({ destination: 'org.a11y.Bus', path: '/org/a11y/bus', iface: I_PROPS, member: 'Set', signature: 'ssv', body: ['org.a11y.Status', prop, variant('b', before[prop])] })
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** ¿Tiene ese bit el conjunto de estados (`au`, dos palabras de 32 bits)? */
|
|
128
|
+
/** @param {number[]} words @param {number} bit */
|
|
129
|
+
export const hasState = (words, bit) => !!((words[bit >> 5] >>> (bit & 31)) & 1)
|
|
130
|
+
|
|
131
|
+
/** Los estados que viajan, en letras. @param {number[]} words */
|
|
132
|
+
export function wireStates (words) {
|
|
133
|
+
let s = ''
|
|
134
|
+
for (const [ch, bit] of WIRE_STATES) if (hasState(words, bit)) s += ch
|
|
135
|
+
return s
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* El lector: sabe recorrer el árbol, actuar sobre un nodo y generar ratón y teclado.
|
|
140
|
+
* @param {import('@dotrino/proxy-client/dbus').DBusConnection} bus el de accesibilidad
|
|
141
|
+
*/
|
|
142
|
+
export function makeReader (bus) {
|
|
143
|
+
/** @type {Map<string, number>} "bus path" → id corto */
|
|
144
|
+
const ids = new Map()
|
|
145
|
+
/** @type {Map<number, Ref>} id corto → objeto */
|
|
146
|
+
const refs = new Map()
|
|
147
|
+
let nextId = 1
|
|
148
|
+
|
|
149
|
+
/** @param {Ref} ref */
|
|
150
|
+
const idOf = (ref) => {
|
|
151
|
+
const k = ref[0] + ' ' + ref[1]
|
|
152
|
+
let id = ids.get(k)
|
|
153
|
+
if (!id) { id = nextId++; ids.set(k, id); refs.set(id, ref) }
|
|
154
|
+
return id
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* @param {Ref} ref @param {string} iface @param {string} member
|
|
159
|
+
* @param {string} [signature] @param {import('@dotrino/proxy-client/dbus').DBusValue[]} [body] valores de D-Bus: su forma la dice `signature`
|
|
160
|
+
*/
|
|
161
|
+
const call = (ref, iface, member, signature = '', body = []) =>
|
|
162
|
+
bus.call({ destination: ref[0], path: ref[1], iface, member, signature, body })
|
|
163
|
+
|
|
164
|
+
/** @param {Ref} ref @param {string} iface @param {string} prop */
|
|
165
|
+
const prop = async (ref, iface, prop) => (await call(ref, I_PROPS, 'Get', 'ss', [iface, prop]))[0].value
|
|
166
|
+
|
|
167
|
+
/** Las apps que publican algo. @returns {Promise<Ref[]>} */
|
|
168
|
+
async function apps () {
|
|
169
|
+
const [kids] = await call([ROOT_DEST, ROOT_PATH], I_ACC, 'GetChildren')
|
|
170
|
+
return kids
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Lo que se sabe de un objeto sin mirar a sus hijos. `null` si ya no existe o no se ve.
|
|
175
|
+
* @param {Ref} ref
|
|
176
|
+
* @param {boolean} isApp el nodo raíz de una app nunca tiene SHOWING (ver arriba)
|
|
177
|
+
*/
|
|
178
|
+
async function describe (ref, isApp) {
|
|
179
|
+
try {
|
|
180
|
+
const [[role], [states], [ifaces]] = await Promise.all([
|
|
181
|
+
call(ref, I_ACC, 'GetRoleName'), call(ref, I_ACC, 'GetState'), call(ref, I_ACC, 'GetInterfaces')
|
|
182
|
+
])
|
|
183
|
+
if (!isApp && (!hasState(states, STATE.SHOWING) || hasState(states, STATE.DEFUNCT))) return null
|
|
184
|
+
const has = new Set(ifaces)
|
|
185
|
+
const [name, ext, count, actions] = await Promise.all([
|
|
186
|
+
prop(ref, I_ACC, 'Name'),
|
|
187
|
+
has.has(I_COMP) ? call(ref, I_COMP, 'GetExtents', 'u', [0]).then((r) => r[0]) : null,
|
|
188
|
+
prop(ref, I_ACC, 'ChildCount'),
|
|
189
|
+
has.has(I_ACTION) ? call(ref, I_ACTION, 'GetActions').then((r) => r[0].map((/** @type {[string, string, string]} */ a) => a[0])).catch(() => []) : []
|
|
190
|
+
])
|
|
191
|
+
let text = ''
|
|
192
|
+
if (has.has(I_TEXT) && TEXT_ROLES.has(role)) {
|
|
193
|
+
try {
|
|
194
|
+
const n = Math.min(await prop(ref, I_TEXT, 'CharacterCount'), MAX_TEXT)
|
|
195
|
+
if (n > 0) text = (await call(ref, I_TEXT, 'GetText', 'ii', [0, n]))[0]
|
|
196
|
+
} catch (_) { /* un texto que no se deja leer se dibuja con su nombre */ }
|
|
197
|
+
}
|
|
198
|
+
return { role, states, name: String(name || ''), ext, count: Number(count) || 0, actions, text }
|
|
199
|
+
} catch (e) {
|
|
200
|
+
// El objeto se fue entre que se listó y se le preguntó: es lo normal en un escritorio vivo.
|
|
201
|
+
if (e instanceof DBusError) return null
|
|
202
|
+
throw e
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Recorre UNA ventana entera y devuelve sus nodos visibles en orden de pintado.
|
|
208
|
+
* Los hijos de un nivel se piden a la vez: el bus está en esta máquina, y en serie una
|
|
209
|
+
* ventana de mil nodos tardaba lo que tardan miles de idas y vueltas.
|
|
210
|
+
*
|
|
211
|
+
* @param {Ref} win
|
|
212
|
+
* @returns {Promise<Node[]>}
|
|
213
|
+
*/
|
|
214
|
+
async function walkWindow (win) {
|
|
215
|
+
let budget = MAX_NODES_PER_WINDOW
|
|
216
|
+
/**
|
|
217
|
+
* Un nodo y lo que cuelga de él, en orden de pintado. Cada rama devuelve SU lista y el
|
|
218
|
+
* padre las junta en el orden de sus hijos: así ir en paralelo no cambia el orden.
|
|
219
|
+
* @param {Ref} ref @param {number} parent @param {number} depth
|
|
220
|
+
* @returns {Promise<Node[]>}
|
|
221
|
+
*/
|
|
222
|
+
async function visit (ref, parent, depth) {
|
|
223
|
+
if (budget <= 0 || depth > MAX_DEPTH) return []
|
|
224
|
+
const d = await describe(ref, false)
|
|
225
|
+
if (!d || !d.ext) return []
|
|
226
|
+
const [x, y, w, h] = d.ext
|
|
227
|
+
if (w <= 0 || h <= 0) return []
|
|
228
|
+
budget--
|
|
229
|
+
const id = idOf(ref)
|
|
230
|
+
/** @type {Node} */
|
|
231
|
+
const node = { id, p: parent, r: d.role, x, y, w, h }
|
|
232
|
+
if (d.name) node.n = d.name
|
|
233
|
+
if (d.text && d.text !== d.name) node.t = d.text
|
|
234
|
+
const s = wireStates(d.states)
|
|
235
|
+
if (s) node.s = s
|
|
236
|
+
if (d.actions.length) node.a = d.actions
|
|
237
|
+
if (HOLE_ROLES.has(d.role)) node.hole = 1
|
|
238
|
+
if (!d.count || node.hole) return [node]
|
|
239
|
+
/** @type {Ref[]} */
|
|
240
|
+
let kids = []
|
|
241
|
+
try { kids = (await call(ref, I_ACC, 'GetChildren'))[0] } catch (e) { if (!(e instanceof DBusError)) throw e }
|
|
242
|
+
const parts = await Promise.all(kids.slice(0, MAX_CHILDREN).map((k) => visit(k, id, depth + 1)))
|
|
243
|
+
return [node, ...parts.flat()]
|
|
244
|
+
}
|
|
245
|
+
return visit(win, 0, 0)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Las ventanas que se ven ahora, de abajo arriba: la ACTIVA, la última (es la que está
|
|
250
|
+
* encima). AT-SPI no da el orden real de apilado en X11; esto es lo honesto que se sabe.
|
|
251
|
+
*
|
|
252
|
+
* @returns {Promise<Array<{ ref: Ref, id: number, app: string, name: string, active: boolean, ext: number[] }>>}
|
|
253
|
+
*/
|
|
254
|
+
async function windows () {
|
|
255
|
+
/** @type {Array<{ ref: Ref, id: number, app: string, name: string, active: boolean, ext: number[] }>} */
|
|
256
|
+
const list = []
|
|
257
|
+
const appRefs = await apps()
|
|
258
|
+
await Promise.all(appRefs.map(async (appRef) => {
|
|
259
|
+
let appName = ''
|
|
260
|
+
/** @type {Ref[]} */
|
|
261
|
+
let kids = []
|
|
262
|
+
try {
|
|
263
|
+
appName = String(await prop(appRef, I_ACC, 'Name') || '')
|
|
264
|
+
kids = (await call(appRef, I_ACC, 'GetChildren'))[0]
|
|
265
|
+
} catch (e) { if (e instanceof DBusError) return; throw e }
|
|
266
|
+
await Promise.all(kids.map(async (w) => {
|
|
267
|
+
const d = await describe(w, false)
|
|
268
|
+
if (!d || !d.ext || d.ext[2] <= 0 || d.ext[3] <= 0) return
|
|
269
|
+
if (hasState(d.states, STATE.ICONIFIED)) return
|
|
270
|
+
list.push({ ref: w, id: idOf(w), app: appName, name: d.name, active: hasState(d.states, STATE.ACTIVE), ext: d.ext })
|
|
271
|
+
}))
|
|
272
|
+
}))
|
|
273
|
+
// Primero las grandes que no están activas (el fondo de escritorio, el panel suele ser
|
|
274
|
+
// pequeño y va arriba del fondo), al final la activa.
|
|
275
|
+
// Desempate por id: se leen en paralelo y llegan en cualquier orden; sin él, dos ventanas del
|
|
276
|
+
// mismo tamaño cambiaban de sitio en cada lectura y salía un parche sin cambios.
|
|
277
|
+
list.sort((a, b) => (Number(a.active) - Number(b.active)) || (b.ext[2] * b.ext[3] - a.ext[2] * a.ext[3]) || (a.id - b.id))
|
|
278
|
+
return list
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Ejecuta la acción `index` de un nodo (la «pulsación» de un botón, abrir un menú…).
|
|
283
|
+
* @param {number} id @param {number} [index]
|
|
284
|
+
*/
|
|
285
|
+
async function doAction (id, index = 0) {
|
|
286
|
+
const ref = refs.get(id)
|
|
287
|
+
if (!ref) throw Object.assign(new Error(`unknown node ${id}`), { code: 'no-node' })
|
|
288
|
+
const [ok] = await call(ref, I_ACTION, 'DoAction', 'i', [index])
|
|
289
|
+
return !!ok
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Pone el foco en un nodo (un campo antes de escribir en él). @param {number} id */
|
|
293
|
+
async function focus (id) {
|
|
294
|
+
const ref = refs.get(id)
|
|
295
|
+
if (!ref) throw Object.assign(new Error(`unknown node ${id}`), { code: 'no-node' })
|
|
296
|
+
const [ok] = await call(ref, I_COMP, 'GrabFocus')
|
|
297
|
+
return !!ok
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Ratón de verdad, en coordenadas de pantalla. `event` es el de AT-SPI: `b<n>c` (clic con el
|
|
302
|
+
* botón n), `b<n>p`/`b<n>r` (bajar/soltar), `b<n>d` (doble clic), `abs` (solo mover); la
|
|
303
|
+
* rueda son los botones 4 (arriba) y 5 (abajo).
|
|
304
|
+
* @param {number} x @param {number} y @param {string} event
|
|
305
|
+
*/
|
|
306
|
+
async function mouse (x, y, event) {
|
|
307
|
+
await bus.call({ destination: ROOT_DEST, path: DEC_PATH, iface: 'org.a11y.atspi.DeviceEventController', member: 'GenerateMouseEvent', signature: 'iis', body: [Math.round(x), Math.round(y), event] })
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Teclado de verdad. Un texto se escribe tal cual (`KEY_STRING`); una tecla especial va por
|
|
312
|
+
* su keysym de X (`KEY_SYM`), con su pulsar y soltar si se mantiene un modificador.
|
|
313
|
+
* @param {{ text?: string, keysym?: number, press?: 'down'|'up' }} k
|
|
314
|
+
*/
|
|
315
|
+
async function key (k) {
|
|
316
|
+
/** @param {number} code @param {string} str @param {number} type */
|
|
317
|
+
const gen = (code, str, type) => bus.call({ destination: ROOT_DEST, path: DEC_PATH, iface: 'org.a11y.atspi.DeviceEventController', member: 'GenerateKeyboardEvent', signature: 'isu', body: [code, str, type] })
|
|
318
|
+
if (typeof k.text === 'string' && k.text) return gen(0, k.text, 4)
|
|
319
|
+
if (typeof k.keysym === 'number') {
|
|
320
|
+
// KEY_SYM pulsa y suelta. Para mantener (Ctrl mientras se pulsa otra) hace falta el
|
|
321
|
+
// keycode, que AT-SPI no da desde un keysym: los modificadores van en `combo` (scene.js).
|
|
322
|
+
return gen(k.keysym, '', 3)
|
|
323
|
+
}
|
|
324
|
+
throw Object.assign(new Error('nothing to type'), { code: 'bad-key' })
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** El objeto de un id, para quien lo necesite (las pruebas). @param {number} id */
|
|
328
|
+
const refOf = (id) => refs.get(id) || null
|
|
329
|
+
|
|
330
|
+
return { apps, windows, walkWindow, doAction, focus, mouse, key, refOf, idOf }
|
|
331
|
+
}
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* dotrino-remote-desktop-agent — el agente de Dotrino Remote Desktop.
|
|
4
|
+
*
|
|
5
|
+
* dotrino-remote-desktop-agent [--name <n>] enlaza (si falta) y CORRE el agente
|
|
6
|
+
* dotrino-remote-desktop-agent enroll [--name <n>] re-enlaza (sobrescribe) y lo corre
|
|
7
|
+
* dotrino-remote-desktop-agent list los agentes enlazados en esta máquina
|
|
8
|
+
* dotrino-remote-desktop-agent info [--name <n>] qué aparato es: su ID, su bóveda, sus permisos
|
|
9
|
+
* dotrino-remote-desktop-agent update [--name <n>] [--approval on|off] [--notify on|off]
|
|
10
|
+
* cómo se actualiza (CONVENCIONES §15)
|
|
11
|
+
*
|
|
12
|
+
* Tiene que correr DENTRO de la sesión gráfica del usuario (necesita su bus de sesión y el de
|
|
13
|
+
* accesibilidad): un servicio de usuario de systemd o el arranque automático del escritorio,
|
|
14
|
+
* no un servicio del sistema.
|
|
15
|
+
*/
|
|
16
|
+
import { createRequire } from 'node:module'
|
|
17
|
+
import { startAgent } from '../index.js'
|
|
18
|
+
import { loadLink, dataDir, LABEL } from '../link.js'
|
|
19
|
+
import { enrollInteractive } from '@dotrino/remote-agent/link'
|
|
20
|
+
import { listInstances, lockInstance, instancesRoot } from '@dotrino/remote-agent/instances'
|
|
21
|
+
import { deviceInfo, formatDeviceInfo } from '@dotrino/vault/device-info'
|
|
22
|
+
import { updatePrefsCommand, updateStatusText } from '@dotrino/update/npm'
|
|
23
|
+
import { startSelfUpdate } from '@dotrino/remote-agent/update'
|
|
24
|
+
|
|
25
|
+
/** @type {{ version: string }} */
|
|
26
|
+
const { version: VERSION } = createRequire(import.meta.url)('../package.json')
|
|
27
|
+
const args = process.argv.slice(2)
|
|
28
|
+
const cmd = args[0] && !args[0].startsWith('-') ? args[0] : 'run'
|
|
29
|
+
/** @param {string} name */
|
|
30
|
+
const opt = (name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined }
|
|
31
|
+
|
|
32
|
+
if (args.includes('-h') || args.includes('--help')) {
|
|
33
|
+
console.log(`uso:
|
|
34
|
+
dotrino-remote-desktop-agent [--name <n>] enlaza este agente (si falta) y lo corre
|
|
35
|
+
dotrino-remote-desktop-agent enroll [--name <n>] re-enlaza (sobrescribe el enlace) y lo corre
|
|
36
|
+
dotrino-remote-desktop-agent list los agentes enlazados en esta máquina
|
|
37
|
+
dotrino-remote-desktop-agent info [--name <n>] qué aparato es: su ID (el de «dotrino-vault members»),
|
|
38
|
+
su bóveda y sus permisos. Sin red. [--json]
|
|
39
|
+
dotrino-remote-desktop-agent update [--name <n>] cómo se actualiza. Por defecto lo hace solo y avisa:
|
|
40
|
+
--approval on|off pedir antes aprobación a tu bóveda
|
|
41
|
+
--notify on|off avisar cuando se actualiza
|
|
42
|
+
opciones: [--name <n>] [--proxy <wss://…>] [--dir <ruta>]
|
|
43
|
+
[--no-a11y] no encender la accesibilidad del escritorio al mirar
|
|
44
|
+
|
|
45
|
+
Corre dentro de tu sesión gráfica (Linux, X11 o Wayland).
|
|
46
|
+
enlaces en ${instancesRoot(LABEL)}/<nombre> (--dir o DOTRINO_REMOTE_DESKTOP_DIR fuerzan una carpeta)`)
|
|
47
|
+
process.exit(0)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** @param {unknown} e @returns {never} */
|
|
51
|
+
function die (e) { console.error('error:', /** @type {Error} */ (e).message); process.exit(1) }
|
|
52
|
+
|
|
53
|
+
if (cmd === 'list') {
|
|
54
|
+
const names = listInstances(LABEL)
|
|
55
|
+
if (!names.length) console.log('No hay ningún agente de escritorio remoto enlazado en esta máquina.')
|
|
56
|
+
for (const n of names) console.log(` ${n} ${instancesRoot(LABEL)}/${n}`)
|
|
57
|
+
process.exit(0)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// `update`: los dos ajustes de ESTE agente (`@dotrino/update/npm`). Sin banderas, los enseña.
|
|
61
|
+
if (cmd === 'update') {
|
|
62
|
+
let r
|
|
63
|
+
try {
|
|
64
|
+
const dir = opt('--dir') || dataDir(opt('--name'))
|
|
65
|
+
const own = args.slice(1).filter((a, i, all) => !['--name', '--dir'].includes(a) && !['--name', '--dir'].includes(all[i - 1]))
|
|
66
|
+
r = updatePrefsCommand(own, { dir, lang: 'es' })
|
|
67
|
+
} catch (e) { die(e) }
|
|
68
|
+
if (!r.handled) { console.error('uso: dotrino-remote-desktop-agent update [--name <n>] [--approval on|off] [--notify on|off]'); process.exit(2) }
|
|
69
|
+
;(r.ok ? console.log : console.error)(r.text)
|
|
70
|
+
process.exit(r.ok ? 0 : 2)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (cmd === 'info') {
|
|
74
|
+
try {
|
|
75
|
+
const dir = opt('--dir') || dataDir(opt('--name'))
|
|
76
|
+
const link = loadLink(dir)
|
|
77
|
+
if (!link) { console.error(`Este agente no está enlazado (${dir}). Enlázalo con: dotrino-remote-desktop-agent`); process.exit(1) }
|
|
78
|
+
const info = await deviceInfo(link, { kind: LABEL, name: opt('--dir') ? null : dir.split(/[\\/]/).pop(), version: VERSION, dir })
|
|
79
|
+
const pending = updateStatusText({ dir, current: VERSION, lang: 'es' })
|
|
80
|
+
if (args.includes('--json')) console.log(JSON.stringify(pending ? { ...info, update: pending } : info, null, 2))
|
|
81
|
+
else console.log(formatDeviceInfo(info) + (pending ? '\n' + pending : ''))
|
|
82
|
+
} catch (e) { die(e) }
|
|
83
|
+
process.exit(0)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (cmd !== 'run' && cmd !== 'enroll') { console.error(`comando desconocido: ${cmd} (mira --help)`); process.exit(2) }
|
|
87
|
+
|
|
88
|
+
try {
|
|
89
|
+
const dir = opt('--dir') || dataDir(opt('--name'))
|
|
90
|
+
// Antes de nada, también de enlazar: dos procesos con el mismo enlace son la misma llave.
|
|
91
|
+
process.on('exit', lockInstance(dir))
|
|
92
|
+
if (cmd === 'enroll' || !loadLink(dir)) {
|
|
93
|
+
if (cmd === 'enroll' && loadLink(dir)) console.log('Re-enlazando esta máquina (sobrescribe el enlace actual).\n')
|
|
94
|
+
await enrollInteractive({ dir, label: LABEL })
|
|
95
|
+
console.log(' Levantando el agente…\n')
|
|
96
|
+
}
|
|
97
|
+
const agent = await startAgent({
|
|
98
|
+
dir,
|
|
99
|
+
proxyUrl: opt('--proxy'),
|
|
100
|
+
...(args.includes('--no-a11y') ? { a11y: false } : {}),
|
|
101
|
+
onRevoked: () => { console.log(' Esta máquina se quitó de tu bóveda. Para volver a usarla, enlázala otra vez.\n'); process.exit(0) },
|
|
102
|
+
onRemote: (r) => console.log(` máquina ${r.machineId}: tus otros aparatos ya pueden usar este escritorio.\n`)
|
|
103
|
+
})
|
|
104
|
+
console.log('\n Dotrino Remote Desktop — agente activo')
|
|
105
|
+
console.log(' versión:', VERSION)
|
|
106
|
+
// §15: se actualiza solo (mira al arrancar y una vez al día). Solo se reinicia cuando nadie
|
|
107
|
+
// está mirando el escritorio.
|
|
108
|
+
const stopUpdates = startSelfUpdate({
|
|
109
|
+
pkg: '@dotrino/remote-desktop-agent', repo: 'imdotrino/dotrino-remote-desktop', tag: (v) => `agent-v${v}`,
|
|
110
|
+
label: LABEL, dir, version: VERSION, busy: () => agent.desktop.watching, close: () => agent.close()
|
|
111
|
+
})
|
|
112
|
+
// El socket del proxio va `unref`'d: sin esto el proceso saldría al arrancar como servicio.
|
|
113
|
+
const keepAlive = setInterval(() => {}, 1 << 30)
|
|
114
|
+
const bye = () => { clearInterval(keepAlive); stopUpdates(); agent.close().finally(() => process.exit(0)) }
|
|
115
|
+
process.on('SIGINT', bye); process.on('SIGTERM', bye)
|
|
116
|
+
} catch (e) { die(e) }
|
package/desktop.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* desktop.js — el escritorio VIVO: lee la escena, se entera de lo que cambia y avisa.
|
|
3
|
+
*
|
|
4
|
+
* Solo trabaja mientras alguien mira (`watch`): sin nadie no lee nada ni escucha eventos.
|
|
5
|
+
*
|
|
6
|
+
* Cómo se entera de los cambios, sin leer la pantalla entera a cada rato:
|
|
7
|
+
* - Los EVENTOS de accesibilidad (`object:*`: cambió un texto, un estado, los hijos…) marcan
|
|
8
|
+
* como sucias las ventanas de la app que los manda, y solo esas se vuelven a leer, juntando
|
|
9
|
+
* los eventos de `SETTLE_MS` (escribir una palabra no son diez lecturas).
|
|
10
|
+
* - MOVER una ventana no manda ningún evento, y mueve todo lo de dentro. Por eso la LISTA de
|
|
11
|
+
* ventanas (barata: 9 ms con 26) se mira cada `WINDOWS_MS`, y la que cambió de sitio o de
|
|
12
|
+
* tamaño se vuelve a leer entera.
|
|
13
|
+
* - Y por si una app no avisa de algo, cada `FULL_MS` se relee todo. Es la red de seguridad,
|
|
14
|
+
* no el mecanismo: si sin ella algo no se viera, el fallo está arriba.
|
|
15
|
+
*/
|
|
16
|
+
import { makeReader, openA11yBus, setA11y, restoreA11y } from './atspi.js'
|
|
17
|
+
import { diff, screenOf } from './scene.js'
|
|
18
|
+
|
|
19
|
+
export const SETTLE_MS = 120
|
|
20
|
+
export const WINDOWS_MS = 1000
|
|
21
|
+
export const FULL_MS = 5000
|
|
22
|
+
|
|
23
|
+
/** @typedef {import('./scene.js').Scene} Scene */
|
|
24
|
+
/** @typedef {import('./scene.js').Patch} Patch */
|
|
25
|
+
/** @typedef {import('./atspi.js').Node} Node */
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {{ log?: (msg: string) => void, a11y?: boolean }} [opts]
|
|
29
|
+
* `a11y`: encender la accesibilidad del escritorio mientras haya alguien mirando (por
|
|
30
|
+
* defecto sí). Se deja como estaba al irse el último.
|
|
31
|
+
*/
|
|
32
|
+
export function makeDesktop (opts = {}) {
|
|
33
|
+
const log = opts.log || (() => {})
|
|
34
|
+
/** @type {Awaited<ReturnType<typeof openA11yBus>> | null} */
|
|
35
|
+
let conn = null
|
|
36
|
+
/** @type {ReturnType<typeof makeReader> | null} */
|
|
37
|
+
let reader = null
|
|
38
|
+
/** @type {{ IsEnabled: boolean, ScreenReaderEnabled: boolean } | null} */
|
|
39
|
+
let a11yBefore = null
|
|
40
|
+
/** @type {Scene} */
|
|
41
|
+
let scene = { seq: 0, screen: { w: 0, h: 0 }, wins: [], nodes: [] }
|
|
42
|
+
/** @type {Map<number, { key: string, app: string, nodes: Node[] }>} lo leído de cada ventana */
|
|
43
|
+
const perWin = new Map()
|
|
44
|
+
/** @type {Set<(p: Patch) => void>} */
|
|
45
|
+
const watchers = new Set()
|
|
46
|
+
/** @type {Set<string>} apps (su nombre en el bus) con algo nuevo */
|
|
47
|
+
const dirtyApps = new Set()
|
|
48
|
+
let fullDue = true
|
|
49
|
+
/** @type {ReturnType<typeof setTimeout> | null} */
|
|
50
|
+
let settle = null
|
|
51
|
+
/** @type {ReturnType<typeof setInterval>[]} */
|
|
52
|
+
let timers = []
|
|
53
|
+
/** @type {Promise<void>} las lecturas van de una en una */
|
|
54
|
+
let running = Promise.resolve()
|
|
55
|
+
/** @type {Promise<void> | null} */
|
|
56
|
+
let starting = null
|
|
57
|
+
|
|
58
|
+
async function start () {
|
|
59
|
+
conn = await openA11yBus()
|
|
60
|
+
reader = makeReader(conn.bus)
|
|
61
|
+
if (opts.a11y !== false) {
|
|
62
|
+
try { a11yBefore = await setA11y(conn.session, true) } catch (e) { log(`could not turn accessibility on: ${/** @type {Error} */ (e).message}`) }
|
|
63
|
+
}
|
|
64
|
+
await listen(conn.bus)
|
|
65
|
+
timers = [
|
|
66
|
+
setInterval(() => schedule(false), WINDOWS_MS),
|
|
67
|
+
setInterval(() => { fullDue = true; schedule(false) }, FULL_MS)
|
|
68
|
+
]
|
|
69
|
+
for (const t of timers) t.unref?.()
|
|
70
|
+
fullDue = true
|
|
71
|
+
await refresh()
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Pide los eventos a las apps. AT-SPI solo los emite si alguien los pidió al registro; la
|
|
76
|
+
* firma de `RegisterEvent` cambió (antes un argumento, desde at-spi2-core 2.34 tres): se
|
|
77
|
+
* prueba la nueva y, si el registro no la conoce, la vieja. No es un repliegue que tape
|
|
78
|
+
* nada: si ninguna entra, se dice, y la red de seguridad (`FULL_MS`) sigue leyendo.
|
|
79
|
+
* @param {import('@dotrino/proxy-client/dbus').DBusConnection} bus
|
|
80
|
+
*/
|
|
81
|
+
async function listen (bus) {
|
|
82
|
+
const reg = { destination: 'org.a11y.atspi.Registry', path: '/org/a11y/atspi/registry', iface: 'org.a11y.atspi.Registry', member: 'RegisterEvent' }
|
|
83
|
+
for (const ev of ['object:', 'window:']) {
|
|
84
|
+
try { await bus.call({ ...reg, signature: 'sass', body: [ev, [], ''] }) } catch (_) {
|
|
85
|
+
try { await bus.call({ ...reg, signature: 's', body: [ev] }) } catch (e) { log(`no accessibility events (${ev}): ${/** @type {Error} */ (e).message}; reading every ${FULL_MS / 1000} s`) }
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
await bus.addMatch("type='signal',interface='org.a11y.atspi.Event.Object'")
|
|
89
|
+
await bus.addMatch("type='signal',interface='org.a11y.atspi.Event.Window'")
|
|
90
|
+
bus.onSignal((m) => {
|
|
91
|
+
if (!m.sender || !m.iface?.startsWith('org.a11y.atspi.Event.')) return
|
|
92
|
+
// Un cambio de ventana (crear, cerrar, activar) cambia la lista: lectura entera.
|
|
93
|
+
if (m.iface === 'org.a11y.atspi.Event.Window') fullDue = true
|
|
94
|
+
else dirtyApps.add(m.sender)
|
|
95
|
+
if (!settle) settle = setTimeout(() => { settle = null; schedule(true) }, SETTLE_MS)
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** @param {boolean} _fromEvent */
|
|
100
|
+
function schedule (_fromEvent) {
|
|
101
|
+
if (!watchers.size) return
|
|
102
|
+
running = running.then(refresh).catch((e) => log(`could not read the desktop: ${e.message}`))
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Lee lo que haga falta y avisa con el parche, si cambió algo. */
|
|
106
|
+
async function refresh () {
|
|
107
|
+
if (!reader) return
|
|
108
|
+
const wins = await reader.windows()
|
|
109
|
+
const full = fullDue
|
|
110
|
+
fullDue = false
|
|
111
|
+
const dirty = new Set(dirtyApps)
|
|
112
|
+
dirtyApps.clear()
|
|
113
|
+
const alive = new Set(wins.map((w) => w.id))
|
|
114
|
+
for (const id of perWin.keys()) if (!alive.has(id)) perWin.delete(id)
|
|
115
|
+
await Promise.all(wins.map(async (w) => {
|
|
116
|
+
const key = w.ext.join(',') + (w.active ? 'a' : '') + w.name
|
|
117
|
+
const had = perWin.get(w.id)
|
|
118
|
+
if (!full && had && had.key === key && !dirty.has(w.app) && !dirty.has(w.ref[0])) return
|
|
119
|
+
const nodes = /** @type {ReturnType<typeof makeReader>} */ (reader).walkWindow(w.ref)
|
|
120
|
+
const got = await nodes
|
|
121
|
+
// Una ventana que no publica nada por dentro (Chrome arrancado sin accesibilidad, un
|
|
122
|
+
// juego) es un HUECO entero: se ve que está, con su nombre, y en la fase 2 lleva vídeo.
|
|
123
|
+
if (got.length === 1) got[0].hole = 1
|
|
124
|
+
perWin.set(w.id, { key, app: w.ref[0], nodes: got })
|
|
125
|
+
}))
|
|
126
|
+
/** @type {Node[]} */
|
|
127
|
+
const nodes = []
|
|
128
|
+
for (const w of wins) { const p = perWin.get(w.id); if (p) nodes.push(...p.nodes) }
|
|
129
|
+
/** @type {Scene} */
|
|
130
|
+
const next = {
|
|
131
|
+
seq: scene.seq + 1,
|
|
132
|
+
screen: screenOf(wins),
|
|
133
|
+
wins: wins.map((w) => ({ id: w.id, app: w.app, name: w.name, active: w.active })),
|
|
134
|
+
nodes
|
|
135
|
+
}
|
|
136
|
+
const patch = diff(scene, next)
|
|
137
|
+
if (!patch) return
|
|
138
|
+
scene = next
|
|
139
|
+
for (const fn of watchers) { try { fn(patch) } catch (_) {} }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function stop () {
|
|
143
|
+
for (const t of timers) clearInterval(t)
|
|
144
|
+
timers = []
|
|
145
|
+
if (settle) { clearTimeout(settle); settle = null }
|
|
146
|
+
if (conn && a11yBefore) { try { await restoreA11y(conn.session, a11yBefore) } catch (_) {} }
|
|
147
|
+
a11yBefore = null
|
|
148
|
+
conn?.bus.close(); conn?.session.close()
|
|
149
|
+
conn = null; reader = null; perWin.clear()
|
|
150
|
+
scene = { seq: scene.seq, screen: { w: 0, h: 0 }, wins: [], nodes: [] }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return {
|
|
154
|
+
/**
|
|
155
|
+
* Empieza a mirar. Devuelve la escena de ahora y, después, cada parche llega a `onPatch`.
|
|
156
|
+
* El primero que mira enciende la lectura; al irse el último se apaga (`unwatch`).
|
|
157
|
+
* @param {(p: Patch) => void} onPatch
|
|
158
|
+
* @returns {Promise<{ scene: Scene, unwatch: () => void }>}
|
|
159
|
+
*/
|
|
160
|
+
async watch (onPatch) {
|
|
161
|
+
if (!conn) { starting ||= start().finally(() => { starting = null }); await starting }
|
|
162
|
+
await running
|
|
163
|
+
watchers.add(onPatch)
|
|
164
|
+
const unwatch = () => {
|
|
165
|
+
watchers.delete(onPatch)
|
|
166
|
+
if (!watchers.size) running = running.then(stop)
|
|
167
|
+
}
|
|
168
|
+
return { scene, unwatch }
|
|
169
|
+
},
|
|
170
|
+
/** Cuántos miran ahora: el agente no se reinicia para actualizarse mientras haya alguien. */
|
|
171
|
+
get watching () { return watchers.size },
|
|
172
|
+
/** La escena de ahora (la última leída). */
|
|
173
|
+
get scene () { return scene },
|
|
174
|
+
/** El lector, para actuar (clic, teclas). `null` si nadie mira. */
|
|
175
|
+
get reader () { return reader },
|
|
176
|
+
stop
|
|
177
|
+
}
|
|
178
|
+
}
|
package/index.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @dotrino/remote-desktop-agent — el escritorio de esta máquina, para los aparatos de tu cuenta.
|
|
3
|
+
*
|
|
4
|
+
* No manda píxeles: manda el ÁRBOL DE ACCESIBILIDAD del escritorio (ventanas, botones, menús,
|
|
5
|
+
* textos, con su posición) y después solo lo que cambia. El cliente lo dibuja en SVG. Es ligero
|
|
6
|
+
* (una ventana de explorador de archivos entera son ~4 KB comprimidos) y el texto llega exacto.
|
|
7
|
+
* Lo que no se puede dibujar así (un lienzo, un vídeo, una app que no publica nada) va como
|
|
8
|
+
* HUECO con su tamaño; la fase 2 lo rellena con vídeo de ese rectángulo.
|
|
9
|
+
*
|
|
10
|
+
* Lo común (enrolarse con la bóveda, el saludo contra el ACTA, el canal cifrado por sesión, la
|
|
11
|
+
* revocación, la renovación del papel, la bitácora y trocear lo grande) lo hace
|
|
12
|
+
* `@dotrino/remote-agent`. Aquí solo hay escritorio.
|
|
13
|
+
*
|
|
14
|
+
* Payloads de dominio (cifrados dentro de la sesión; el proxio no los ve):
|
|
15
|
+
* cliente → agente:
|
|
16
|
+
* { type:'scene' } la escena entera, y a partir de ahí cada parche
|
|
17
|
+
* { type:'leave' } dejar de recibir parches
|
|
18
|
+
* { type:'click', x, y, button?, double? } clic de verdad en la pantalla (button 1–3)
|
|
19
|
+
* { type:'press', x, y, button? } · { type:'release', x, y, button? } arrastrar
|
|
20
|
+
* { type:'move', x, y } mover el ratón
|
|
21
|
+
* { type:'wheel', x, y, dy } rueda (dy < 0 arriba)
|
|
22
|
+
* { type:'action', id, index? } la acción de un nodo (pulsar un botón sin apuntar)
|
|
23
|
+
* { type:'focus', id } poner el foco en un nodo
|
|
24
|
+
* { type:'text', text } escribir un texto
|
|
25
|
+
* { type:'key', keysym } una tecla especial, por su keysym de X (Intro, flechas…)
|
|
26
|
+
* agente → cliente:
|
|
27
|
+
* { type:'scene', seq, screen, wins, nodes } · { type:'patch', seq, base, … } (scene.js)
|
|
28
|
+
* { type:'fail', code, message }
|
|
29
|
+
*
|
|
30
|
+
* Quién puede: cualquier aparato de tu cuenta con `sign` en el acta, igual que la terminal
|
|
31
|
+
* (lo juzga `remote-agent` en el saludo). Instalar este agente en una máquina es decir que su
|
|
32
|
+
* escritorio se puede usar desde tus otros aparatos.
|
|
33
|
+
*/
|
|
34
|
+
import { createRequire } from 'node:module'
|
|
35
|
+
import { startRemoteAgent } from '@dotrino/remote-agent/agent'
|
|
36
|
+
import { dataDir, loadLink, LABEL } from './link.js'
|
|
37
|
+
import { makeDesktop } from './desktop.js'
|
|
38
|
+
|
|
39
|
+
/** @typedef {Awaited<ReturnType<typeof startRemoteAgent>>} RemoteAgent */
|
|
40
|
+
|
|
41
|
+
const require = createRequire(import.meta.url)
|
|
42
|
+
/** @type {{ version: string }} */
|
|
43
|
+
const { version: VERSION } = require('./package.json')
|
|
44
|
+
|
|
45
|
+
export { LABEL, VERSION }
|
|
46
|
+
|
|
47
|
+
/** Cuánto dura sin mensajes una sesión: una pantalla quieta no manda nada. */
|
|
48
|
+
export const SESSION_IDLE_MS = 60 * 60_000
|
|
49
|
+
/** Cada cuánto se reintenta la parte remota cuando no pudo arrancar (sin red, proxio caído). */
|
|
50
|
+
const REMOTE_RETRY_MS = 15_000
|
|
51
|
+
|
|
52
|
+
/** Los botones que se aceptan, y lo que se manda para cada uno (AT-SPI: `b<n><p|r|c|d>`). */
|
|
53
|
+
const BUTTONS = new Set([1, 2, 3])
|
|
54
|
+
/** Lo más largo que se escribe de una vez: pegar un libro no puede colgar el escritorio. */
|
|
55
|
+
const MAX_TYPED = 10_000
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @typedef {{ device?: string|null, send: (p: object) => unknown, on: (ev: 'message'|'close', cb: (msg?: unknown) => void) => unknown }} SessionLike
|
|
59
|
+
*/
|
|
60
|
+
|
|
61
|
+
/** @param {unknown} v @returns {v is number} */
|
|
62
|
+
const num = (v) => typeof v === 'number' && Number.isFinite(v)
|
|
63
|
+
/** @param {unknown} v @returns {v is number} */
|
|
64
|
+
const int = (v) => Number.isInteger(v)
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Atiende una sesión de otro aparato. Exportada para las pruebas.
|
|
68
|
+
* @param {SessionLike} session
|
|
69
|
+
* @param {ReturnType<typeof makeDesktop>} desktop
|
|
70
|
+
* @param {{ log?: (m: string) => void }} [opts]
|
|
71
|
+
*/
|
|
72
|
+
export function serveSession (session, desktop, { log = () => {} } = {}) {
|
|
73
|
+
/** @type {(() => void) | null} */
|
|
74
|
+
let unwatch = null
|
|
75
|
+
/** @type {(code: string, message: string) => void} */
|
|
76
|
+
const fail = (code, message) => { session.send({ type: 'fail', code, message }) }
|
|
77
|
+
/** @param {unknown} err */
|
|
78
|
+
const failWith = (err) => {
|
|
79
|
+
const e = /** @type {{ code?: string, message?: string } | null | undefined} */ (err)
|
|
80
|
+
fail(e?.code || 'desktop-error', e?.message || String(err))
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** El lector, o un fallo dicho: sin nadie mirando no hay a quién mandarle el clic. */
|
|
84
|
+
const reader = () => {
|
|
85
|
+
const r = desktop.reader
|
|
86
|
+
if (!r) throw Object.assign(new Error('ask for the scene first'), { code: 'not-watching' })
|
|
87
|
+
return r
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
session.on('message', async (raw) => {
|
|
91
|
+
if (!raw || typeof raw !== 'object') return
|
|
92
|
+
// Lo que llega es JSON de otro aparato: cada campo se comprueba antes de usarlo.
|
|
93
|
+
const msg = /** @type {Record<string, unknown>} */ (raw)
|
|
94
|
+
const { x, y, dy, id, index, text, keysym, double } = msg
|
|
95
|
+
const button = msg.button ?? 1
|
|
96
|
+
try {
|
|
97
|
+
switch (msg.type) {
|
|
98
|
+
case 'scene': {
|
|
99
|
+
unwatch?.()
|
|
100
|
+
const w = await desktop.watch((patch) => { session.send({ type: 'patch', ...patch }) })
|
|
101
|
+
unwatch = w.unwatch
|
|
102
|
+
session.send({ type: 'scene', ...w.scene })
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
case 'leave': unwatch?.(); unwatch = null; return
|
|
106
|
+
case 'click': {
|
|
107
|
+
if (!num(x) || !num(y)) return fail('bad-input', 'click needs x and y')
|
|
108
|
+
if (!int(button) || !BUTTONS.has(button)) return fail('bad-input', 'button must be 1, 2 or 3')
|
|
109
|
+
await reader().mouse(x, y, 'abs')
|
|
110
|
+
await reader().mouse(x, y, `b${button}${double ? 'd' : 'c'}`)
|
|
111
|
+
return
|
|
112
|
+
}
|
|
113
|
+
case 'press': case 'release': {
|
|
114
|
+
if (!num(x) || !num(y)) return fail('bad-input', `${msg.type} needs x and y`)
|
|
115
|
+
if (!int(button) || !BUTTONS.has(button)) return fail('bad-input', 'button must be 1, 2 or 3')
|
|
116
|
+
await reader().mouse(x, y, 'abs')
|
|
117
|
+
await reader().mouse(x, y, `b${button}${msg.type === 'press' ? 'p' : 'r'}`)
|
|
118
|
+
return
|
|
119
|
+
}
|
|
120
|
+
case 'move':
|
|
121
|
+
if (!num(x) || !num(y)) return fail('bad-input', 'move needs x and y')
|
|
122
|
+
await reader().mouse(x, y, 'abs')
|
|
123
|
+
return
|
|
124
|
+
case 'wheel': {
|
|
125
|
+
if (!num(x) || !num(y) || !num(dy)) return fail('bad-input', 'wheel needs x, y and dy')
|
|
126
|
+
await reader().mouse(x, y, 'abs')
|
|
127
|
+
const steps = Math.min(10, Math.max(1, Math.round(Math.abs(dy))))
|
|
128
|
+
for (let i = 0; i < steps; i++) await reader().mouse(x, y, dy < 0 ? 'b4c' : 'b5c')
|
|
129
|
+
return
|
|
130
|
+
}
|
|
131
|
+
case 'action':
|
|
132
|
+
if (!int(id)) return fail('bad-input', 'action needs a node id')
|
|
133
|
+
await reader().doAction(id, int(index) ? index : 0)
|
|
134
|
+
return
|
|
135
|
+
case 'focus':
|
|
136
|
+
if (!int(id)) return fail('bad-input', 'focus needs a node id')
|
|
137
|
+
await reader().focus(id)
|
|
138
|
+
return
|
|
139
|
+
case 'text':
|
|
140
|
+
if (typeof text !== 'string' || !text) return fail('bad-input', 'text needs some text')
|
|
141
|
+
if (text.length > MAX_TYPED) return fail('too-long', `at most ${MAX_TYPED} characters at a time`)
|
|
142
|
+
await reader().key({ text })
|
|
143
|
+
return
|
|
144
|
+
case 'key':
|
|
145
|
+
if (!int(keysym) || keysym <= 0) return fail('bad-input', 'key needs a keysym')
|
|
146
|
+
await reader().key({ keysym })
|
|
147
|
+
return
|
|
148
|
+
default:
|
|
149
|
+
return fail('unknown-type', `unknown message type: ${String(msg.type).slice(0, 32)}`)
|
|
150
|
+
}
|
|
151
|
+
} catch (e) {
|
|
152
|
+
log(`session: ${/** @type {Error} */ (e).message}`)
|
|
153
|
+
failWith(e)
|
|
154
|
+
}
|
|
155
|
+
})
|
|
156
|
+
session.on('close', () => { unwatch?.(); unwatch = null })
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Arranca el agente: el escritorio (perezoso: no lee nada hasta que alguien mira) y la parte
|
|
161
|
+
* remota. Sin enlace no arranca: este agente no tiene ventanas locales a las que atender, así
|
|
162
|
+
* que sin bóveda no sirve para nada, y se dice.
|
|
163
|
+
*
|
|
164
|
+
* @param {object} [opts]
|
|
165
|
+
* @param {string} [opts.dir] dónde vive el enlace (default dataDir()).
|
|
166
|
+
* @param {string} [opts.proxyUrl] override del proxio del enlace.
|
|
167
|
+
* @param {boolean} [opts.quiet]
|
|
168
|
+
* @param {boolean} [opts.a11y] encender la accesibilidad mientras alguien mira (default sí).
|
|
169
|
+
* @param {() => void} [opts.onRevoked]
|
|
170
|
+
* @param {(e: Error) => void} [opts.onRemoteError] la parte remota no arrancó (se reintenta).
|
|
171
|
+
* @param {(r: RemoteAgent) => void} [opts.onRemote] arrancó.
|
|
172
|
+
*/
|
|
173
|
+
export async function startAgent (opts = {}) {
|
|
174
|
+
const dir = opts.dir || dataDir()
|
|
175
|
+
if (!loadLink(dir)) throw Object.assign(new Error(`this machine is not linked (${dir})`), { code: 'not-linked' })
|
|
176
|
+
const log = (/** @type {string} */ m) => { if (!opts.quiet) console.error(`[remote-desktop-agent] ${m}`) }
|
|
177
|
+
const desktop = makeDesktop({ log, ...(opts.a11y === false ? { a11y: false } : {}) })
|
|
178
|
+
/** @type {RemoteAgent | null} */
|
|
179
|
+
let remote = null
|
|
180
|
+
let stopped = false
|
|
181
|
+
const startRemote = () => startRemoteAgent({
|
|
182
|
+
label: LABEL,
|
|
183
|
+
product: LABEL,
|
|
184
|
+
version: VERSION,
|
|
185
|
+
dir,
|
|
186
|
+
proxyUrl: opts.proxyUrl,
|
|
187
|
+
quiet: opts.quiet,
|
|
188
|
+
sessionTtlMs: SESSION_IDLE_MS,
|
|
189
|
+
onRevoked: () => { desktop.stop().catch(() => {}); opts.onRevoked?.() },
|
|
190
|
+
onSession: (session) => serveSession(session, desktop, { log })
|
|
191
|
+
})
|
|
192
|
+
/** @type {ReturnType<typeof setInterval> | null} */
|
|
193
|
+
let retry = null
|
|
194
|
+
try {
|
|
195
|
+
remote = await startRemote()
|
|
196
|
+
opts.onRemote?.(remote)
|
|
197
|
+
} catch (e) {
|
|
198
|
+
// Sin red al arrancar: se reintenta por detrás. Lo que no hay es acceso, y se dice.
|
|
199
|
+
log(`the remote side did not start (${/** @type {Error} */ (e).message}); retrying every ${REMOTE_RETRY_MS / 1000} s`)
|
|
200
|
+
opts.onRemoteError?.(/** @type {Error} */ (e))
|
|
201
|
+
let trying = false
|
|
202
|
+
retry = setInterval(() => {
|
|
203
|
+
if (trying) return
|
|
204
|
+
trying = true
|
|
205
|
+
startRemote().then((r) => {
|
|
206
|
+
if (stopped) { r.close(); return }
|
|
207
|
+
if (retry) clearInterval(retry)
|
|
208
|
+
retry = null
|
|
209
|
+
remote = r
|
|
210
|
+
opts.onRemote?.(r)
|
|
211
|
+
}).catch(() => {}).finally(() => { trying = false })
|
|
212
|
+
}, REMOTE_RETRY_MS)
|
|
213
|
+
retry.unref()
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
get remote () { return remote },
|
|
217
|
+
get machineId () { return remote?.machineId || null },
|
|
218
|
+
desktop,
|
|
219
|
+
close: async () => { stopped = true; if (retry) clearInterval(retry); remote?.close(); await desktop.stop() }
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export default { startAgent, LABEL }
|
package/link.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* link.js — dónde vive el enlace de esta máquina con la bóveda. Enlazar, cargar y renovar lo
|
|
3
|
+
* hace `@dotrino/remote-agent/link`; la carpeta la decide el estándar
|
|
4
|
+
* `@dotrino/remote-agent/instances`: `~/.dotrino/agent/remote-desktop-agent/<nombre>/`.
|
|
5
|
+
*/
|
|
6
|
+
import { loadLink as raLoad } from '@dotrino/remote-agent/link'
|
|
7
|
+
import { resolveInstance } from '@dotrino/remote-agent/instances'
|
|
8
|
+
|
|
9
|
+
/** El tipo de este agente: lo contesta al ping y da nombre a la carpeta de sus enlaces. */
|
|
10
|
+
export const LABEL = 'remote-desktop-agent'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* La carpeta del enlace. `DOTRINO_REMOTE_DESKTOP_DIR` fuerza una concreta (un contenedor); si
|
|
14
|
+
* no, la de la instancia `name` (sin nombre se busca y solo se exige con empate).
|
|
15
|
+
* @param {string | null} [name]
|
|
16
|
+
* @returns {string}
|
|
17
|
+
*/
|
|
18
|
+
export function dataDir (name) {
|
|
19
|
+
if (process.env.DOTRINO_REMOTE_DESKTOP_DIR) return process.env.DOTRINO_REMOTE_DESKTOP_DIR
|
|
20
|
+
return resolveInstance(LABEL, name).dir
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const loadLink = (dir = dataDir()) => raLoad(dir)
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/remote-desktop-agent",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Dotrino Remote Desktop: usa el escritorio de esta máquina desde los otros aparatos de tu cuenta. Lo dibuja a partir de su árbol de accesibilidad (ligero y nítido), cifrado punto a punto.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"dotrino-remote-desktop-agent": "bin/cli.js"
|
|
8
|
+
},
|
|
9
|
+
"exports": {
|
|
10
|
+
".": "./index.js",
|
|
11
|
+
"./scene": "./scene.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"index.js",
|
|
15
|
+
"atspi.js",
|
|
16
|
+
"desktop.js",
|
|
17
|
+
"scene.js",
|
|
18
|
+
"link.js",
|
|
19
|
+
"bin"
|
|
20
|
+
],
|
|
21
|
+
"scripts": {
|
|
22
|
+
"start": "node bin/cli.js",
|
|
23
|
+
"test": "node --test \"test/**/*.test.mjs\"",
|
|
24
|
+
"type-check": "tsc --noEmit"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@dotrino/identity": "0.138.0",
|
|
28
|
+
"@dotrino/proxy-client": "0.49.0",
|
|
29
|
+
"@dotrino/remote-agent": "0.36.0",
|
|
30
|
+
"@dotrino/update": "0.9.4",
|
|
31
|
+
"@dotrino/vault": "0.121.2"
|
|
32
|
+
},
|
|
33
|
+
"engines": {
|
|
34
|
+
"node": "^20.19.0 || >=22.12.0"
|
|
35
|
+
},
|
|
36
|
+
"license": "MIT",
|
|
37
|
+
"repository": {
|
|
38
|
+
"type": "git",
|
|
39
|
+
"url": "git+https://github.com/imdotrino/dotrino-remote-desktop.git",
|
|
40
|
+
"directory": "agent"
|
|
41
|
+
},
|
|
42
|
+
"homepage": "https://remote-desktop.dotrino.com/",
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@types/node": "22.20.1",
|
|
45
|
+
"typescript": "5.9.3"
|
|
46
|
+
},
|
|
47
|
+
"optionalDependencies": {
|
|
48
|
+
"@dotrino/webrtc": "0.1.0"
|
|
49
|
+
}
|
|
50
|
+
}
|
package/scene.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* scene.js — la ESCENA: qué hay en pantalla, como nodos, y qué cambió desde la última vez.
|
|
3
|
+
*
|
|
4
|
+
* Sin dependencias ni red (funciones puras): la misma lógica de diferencias la usa el cliente
|
|
5
|
+
* para aplicar lo que llega (`applyPatch`), y se prueba sin escritorio.
|
|
6
|
+
*
|
|
7
|
+
* El cable:
|
|
8
|
+
* agente → cliente
|
|
9
|
+
* { type:'scene', seq, screen:{w,h}, wins:[{id,app,name,active}], nodes:[Node…] } entera
|
|
10
|
+
* { type:'patch', seq, base, screen?, wins?, order?, put:[Node…], del:[id…] } lo que cambió
|
|
11
|
+
* `base` es el `seq` sobre el que se aplica: si el cliente no lo tiene, pide la escena
|
|
12
|
+
* entera (`{ type:'scene' }`) en vez de pintar algo a medias.
|
|
13
|
+
* `order` (la lista de ids en orden de pintado) solo viaja si cambió el orden: lo normal
|
|
14
|
+
* es que cambie un texto o una posición, y eso no lo toca.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** @typedef {import('./atspi.js').Node} Node */
|
|
18
|
+
/** @typedef {{ id: number, app: string, name: string, active: boolean }} Win */
|
|
19
|
+
/** @typedef {{ seq: number, screen: { w: number, h: number }, wins: Win[], nodes: Node[] }} Scene */
|
|
20
|
+
/**
|
|
21
|
+
* @typedef {{ seq: number, base: number, screen?: { w: number, h: number }, wins?: Win[],
|
|
22
|
+
* order?: number[], put: Node[], del: number[] }} Patch
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/** Dos nodos iguales, campo a campo (los que viajan). @param {Node} a @param {Node} b */
|
|
26
|
+
export function sameNode (a, b) {
|
|
27
|
+
if (a.p !== b.p || a.r !== b.r || a.x !== b.x || a.y !== b.y || a.w !== b.w || a.h !== b.h) return false
|
|
28
|
+
if (a.n !== b.n || a.t !== b.t || a.s !== b.s || a.hole !== b.hole) return false
|
|
29
|
+
const aa = a.a || []; const ba = b.a || []
|
|
30
|
+
return aa.length === ba.length && aa.every((v, i) => v === ba[i])
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** @param {{ w: number, h: number }} a @param {{ w: number, h: number }} b */
|
|
34
|
+
const sameScreen = (a, b) => a.w === b.w && a.h === b.h
|
|
35
|
+
/** @param {Win[]} a @param {Win[]} b */
|
|
36
|
+
const sameWins = (a, b) => a.length === b.length && a.every((w, i) => w.id === b[i].id && w.app === b[i].app && w.name === b[i].name && w.active === b[i].active)
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Lo que cambió de `prev` a `next`. `null` si no cambió nada (no se manda nada: una pantalla
|
|
40
|
+
* quieta no gasta red).
|
|
41
|
+
* @param {Scene} prev @param {Scene} next
|
|
42
|
+
* @returns {Patch | null}
|
|
43
|
+
*/
|
|
44
|
+
export function diff (prev, next) {
|
|
45
|
+
/** @type {Map<number, Node>} */
|
|
46
|
+
const before = new Map(prev.nodes.map((n) => [n.id, n]))
|
|
47
|
+
/** @type {Node[]} */
|
|
48
|
+
const put = []
|
|
49
|
+
const nextIds = new Set()
|
|
50
|
+
for (const n of next.nodes) {
|
|
51
|
+
nextIds.add(n.id)
|
|
52
|
+
const o = before.get(n.id)
|
|
53
|
+
if (!o || !sameNode(o, n)) put.push(n)
|
|
54
|
+
}
|
|
55
|
+
/** @type {number[]} */
|
|
56
|
+
const del = []
|
|
57
|
+
for (const id of before.keys()) if (!nextIds.has(id)) del.push(id)
|
|
58
|
+
// El orden cambió si, quitando los borrados y los nuevos, los que siguen no van igual.
|
|
59
|
+
const kept = prev.nodes.filter((n) => nextIds.has(n.id)).map((n) => n.id)
|
|
60
|
+
const keptNext = next.nodes.filter((n) => before.has(n.id)).map((n) => n.id)
|
|
61
|
+
const added = next.nodes.some((n) => !before.has(n.id))
|
|
62
|
+
const reordered = added || kept.length !== keptNext.length || kept.some((id, i) => id !== keptNext[i])
|
|
63
|
+
const screenChanged = !sameScreen(prev.screen, next.screen)
|
|
64
|
+
const winsChanged = !sameWins(prev.wins, next.wins)
|
|
65
|
+
if (!put.length && !del.length && !reordered && !screenChanged && !winsChanged) return null
|
|
66
|
+
/** @type {Patch} */
|
|
67
|
+
const patch = { seq: next.seq, base: prev.seq, put, del }
|
|
68
|
+
if (reordered) patch.order = next.nodes.map((n) => n.id)
|
|
69
|
+
if (screenChanged) patch.screen = next.screen
|
|
70
|
+
if (winsChanged) patch.wins = next.wins
|
|
71
|
+
return patch
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Aplica un parche a una escena. Lanza `stale` si el parche no es para esta escena: pintarlo
|
|
76
|
+
* dejaría la pantalla a medias sin que nadie se entere. Quien lo recibe pide la entera.
|
|
77
|
+
* @param {Scene} scene @param {Patch} patch
|
|
78
|
+
* @returns {Scene}
|
|
79
|
+
*/
|
|
80
|
+
export function applyPatch (scene, patch) {
|
|
81
|
+
if (patch.base !== scene.seq) throw Object.assign(new Error(`patch for ${patch.base}, scene is ${scene.seq}`), { code: 'stale' })
|
|
82
|
+
/** @type {Map<number, Node>} */
|
|
83
|
+
const byId = new Map(scene.nodes.map((n) => [n.id, n]))
|
|
84
|
+
for (const id of patch.del) byId.delete(id)
|
|
85
|
+
for (const n of patch.put) byId.set(n.id, n)
|
|
86
|
+
/** @type {Node[]} */
|
|
87
|
+
let nodes
|
|
88
|
+
if (patch.order) {
|
|
89
|
+
nodes = []
|
|
90
|
+
for (const id of patch.order) {
|
|
91
|
+
const n = byId.get(id)
|
|
92
|
+
if (!n) throw Object.assign(new Error(`order names node ${id}, which the patch does not carry`), { code: 'bad-patch' })
|
|
93
|
+
nodes.push(n)
|
|
94
|
+
}
|
|
95
|
+
} else {
|
|
96
|
+
nodes = scene.nodes.filter((n) => byId.has(n.id)).map((n) => /** @type {Node} */ (byId.get(n.id)))
|
|
97
|
+
}
|
|
98
|
+
return { seq: patch.seq, screen: patch.screen || scene.screen, wins: patch.wins || scene.wins, nodes }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* El tamaño del escritorio: lo que abarcan las ventanas. AT-SPI no da el tamaño de la
|
|
103
|
+
* pantalla; el fondo de escritorio (una ventana a pantalla completa) suele darlo de hecho.
|
|
104
|
+
* @param {Array<{ ext: number[] }>} wins
|
|
105
|
+
*/
|
|
106
|
+
export function screenOf (wins) {
|
|
107
|
+
let w = 0; let h = 0
|
|
108
|
+
for (const { ext } of wins) { w = Math.max(w, ext[0] + ext[2]); h = Math.max(h, ext[1] + ext[3]) }
|
|
109
|
+
return { w, h }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* El nodo que hay bajo un punto: el último en orden de pintado que lo contiene (el de más
|
|
114
|
+
* arriba). Lo usa el cliente para decidir a qué se le hizo clic.
|
|
115
|
+
* @param {Node[]} nodes @param {number} x @param {number} y
|
|
116
|
+
* @returns {Node | null}
|
|
117
|
+
*/
|
|
118
|
+
export function hit (nodes, x, y) {
|
|
119
|
+
for (let i = nodes.length - 1; i >= 0; i--) {
|
|
120
|
+
const n = nodes[i]
|
|
121
|
+
if (x >= n.x && y >= n.y && x < n.x + n.w && y < n.y + n.h) return n
|
|
122
|
+
}
|
|
123
|
+
return null
|
|
124
|
+
}
|
|
125
|
+
|
package/README.md
DELETED