@dotrino/remote-desktop-agent 0.1.1 → 0.2.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/atspi.js CHANGED
@@ -324,8 +324,19 @@ export function makeReader (bus) {
324
324
  throw Object.assign(new Error('nothing to type'), { code: 'bad-key' })
325
325
  }
326
326
 
327
+ /**
328
+ * El proceso de la app a la que pertenece un nodo: el bus lo sabe por su nombre en el bus.
329
+ * @param {number} id
330
+ */
331
+ async function pidOf (id) {
332
+ const ref = refs.get(id)
333
+ if (!ref) throw Object.assign(new Error(`unknown node ${id}`), { code: 'no-node' })
334
+ const [pid] = await bus.call({ destination: 'org.freedesktop.DBus', path: '/org/freedesktop/DBus', iface: 'org.freedesktop.DBus', member: 'GetConnectionUnixProcessID', signature: 's', body: [ref[0]] })
335
+ return Number(pid)
336
+ }
337
+
327
338
  /** El objeto de un id, para quien lo necesite (las pruebas). @param {number} id */
328
339
  const refOf = (id) => refs.get(id) || null
329
340
 
330
- return { apps, windows, walkWindow, doAction, focus, mouse, key, refOf, idOf }
341
+ return { apps, windows, walkWindow, doAction, focus, mouse, key, refOf, idOf, pidOf }
331
342
  }
package/desktop.js CHANGED
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import { makeReader, openA11yBus, setA11y, restoreA11y } from './atspi.js'
17
17
  import { diff, screenOf } from './scene.js'
18
+ import { activeWindow } from './raise.js'
18
19
 
19
20
  export const SETTLE_MS = 120
20
21
  export const WINDOWS_MS = 1000
@@ -43,6 +44,8 @@ export function makeDesktop (opts = {}) {
43
44
  const perWin = new Map()
44
45
  /** @type {Set<(p: Patch) => void>} */
45
46
  const watchers = new Set()
47
+ /** @type {Map<string, number>} el proceso de cada app, por su nombre en el bus */
48
+ const pids = new Map()
46
49
  /** @type {Set<string>} apps (su nombre en el bus) con algo nuevo */
47
50
  const dirtyApps = new Set()
48
51
  let fullDue = true
@@ -106,6 +109,17 @@ export function makeDesktop (opts = {}) {
106
109
  async function refresh () {
107
110
  if (!reader) return
108
111
  const wins = await reader.windows()
112
+ // Cuál está activa lo dice el gestor de ventanas si se le puede preguntar: la accesibilidad
113
+ // la informa mal (una app de Electron se queda «activa» para siempre).
114
+ const real = await activeWindow()
115
+ if (real) {
116
+ for (const w of wins) {
117
+ let pid = pids.get(w.ref[0])
118
+ if (pid == null) { try { pid = await reader.pidOf(w.id) } catch (_) { pid = -1 } pids.set(w.ref[0], pid) }
119
+ w.active = pid === real.pid && w.name === real.title
120
+ }
121
+ wins.sort((a, b) => Number(a.active) - Number(b.active))
122
+ }
109
123
  const full = fullDue
110
124
  fullDue = false
111
125
  const dirty = new Set(dirtyApps)
package/index.js CHANGED
@@ -23,6 +23,7 @@
23
23
  * { type:'focus', id } poner el foco en un nodo
24
24
  * { type:'text', text } escribir un texto
25
25
  * { type:'key', keysym } una tecla especial, por su keysym de X (Intro, flechas…)
26
+ * { type:'raise', id } traer al frente esa ventana (id de su nodo), con el foco
26
27
  * agente → cliente:
27
28
  * { type:'scene', seq, screen, wins, nodes } · { type:'patch', seq, base, … } (scene.js)
28
29
  * { type:'fail', code, message }
@@ -35,6 +36,7 @@ import { createRequire } from 'node:module'
35
36
  import { startRemoteAgent } from '@dotrino/remote-agent/agent'
36
37
  import { dataDir, loadLink, LABEL } from './link.js'
37
38
  import { makeDesktop } from './desktop.js'
39
+ import { raiseWindow } from './raise.js'
38
40
 
39
41
  /** @typedef {Awaited<ReturnType<typeof startRemoteAgent>>} RemoteAgent */
40
42
 
@@ -141,6 +143,13 @@ export function serveSession (session, desktop, { log = () => {} } = {}) {
141
143
  if (text.length > MAX_TYPED) return fail('too-long', `at most ${MAX_TYPED} characters at a time`)
142
144
  await reader().key({ text })
143
145
  return
146
+ case 'raise': {
147
+ if (!int(id)) return fail('bad-input', 'raise needs a window id')
148
+ const win = desktop.scene.wins.find((w) => w.id === id)
149
+ if (!win) return fail('window-not-found', `no window ${id} in the scene`)
150
+ await raiseWindow({ pid: await reader().pidOf(id), title: win.name })
151
+ return
152
+ }
144
153
  case 'key':
145
154
  if (!int(keysym) || keysym <= 0) return fail('bad-input', 'key needs a keysym')
146
155
  await reader().key({ keysym })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/remote-desktop-agent",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
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
5
  "type": "module",
6
6
  "bin": {
@@ -12,6 +12,7 @@
12
12
  },
13
13
  "files": [
14
14
  "index.js",
15
+ "raise.js",
15
16
  "atspi.js",
16
17
  "desktop.js",
17
18
  "scene.js",
package/raise.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * raise.js — traer una ventana al frente, con el foco, en la pantalla de la máquina.
3
+ *
4
+ * Elegir una ventana en la tableta es decir «quiero trabajar en esta» (dueño, 2026-11-16): si
5
+ * otra la tapa en la máquina, un toque caería en la de encima. Así lo que se ve y lo que se toca
6
+ * coinciden.
7
+ *
8
+ * La accesibilidad no lo sabe hacer (`GrabFocus` sobre una ventana devuelve `false`, probado en
9
+ * XFCE), así que se le pide al gestor de ventanas con `xdotool`, que en X11 manda el
10
+ * `_NET_ACTIVE_WINDOW` de siempre. Solo X11: en Wayland ningún programa puede traer ventanas al
11
+ * frente, por diseño. Cuando no se puede se dice con su `code` (`no-raise`), y la tableta lo
12
+ * enseña: la vista se centra igual.
13
+ */
14
+ import { execFile } from 'node:child_process'
15
+
16
+ /** @param {string} cmd @param {string[]} args @returns {Promise<string>} */
17
+ const run = (cmd, args) => new Promise((resolve, reject) => {
18
+ execFile(cmd, args, { timeout: 3000 }, (err, stdout) => { if (err) reject(err); else resolve(String(stdout)) })
19
+ })
20
+
21
+ /** @type {(code: string, message: string) => Error & { code: string }} */
22
+ const fail = (code, message) => Object.assign(new Error(message), { code })
23
+
24
+ /**
25
+ * Trae al frente la ventana de ese proceso que se llama así.
26
+ * @param {{ pid: number, title: string, session?: string, exec?: typeof run }} o
27
+ */
28
+ export async function raiseWindow ({ pid, title, session = process.env.XDG_SESSION_TYPE || '', exec = run }) {
29
+ if (session === 'wayland') throw fail('no-raise', 'Wayland does not let a program bring windows to the front')
30
+ /** @type {string[]} */
31
+ let ids
32
+ try {
33
+ ids = (await exec('xdotool', ['search', '--pid', String(pid)])).split('\n').map((s) => s.trim()).filter(Boolean)
34
+ } catch (e) {
35
+ const err = /** @type {NodeJS.ErrnoException & { code?: string | number }} */ (e)
36
+ if (err.code === 'ENOENT') throw fail('no-raise', 'xdotool is not installed on this machine')
37
+ // `search` sale con 1 cuando no encuentra nada: no hay ventana de ese proceso.
38
+ throw fail('window-not-found', `no window of process ${pid}`)
39
+ }
40
+ // De las ventanas del proceso, la que tiene ese título (un proceso puede tener varias).
41
+ for (const id of ids) {
42
+ let name = ''
43
+ try { name = (await exec('xdotool', ['getwindowname', id])).trim() } catch (_) { continue }
44
+ if (name === title) {
45
+ await exec('xdotool', ['windowactivate', id])
46
+ return { window: id }
47
+ }
48
+ }
49
+ throw fail('window-not-found', `no window titled "${title.slice(0, 60)}" in process ${pid}`)
50
+ }
51
+
52
+ /**
53
+ * La ventana activa DE VERDAD, según el gestor de ventanas: `{ pid, title }`, o `null` si no se
54
+ * puede saber (Wayland, sin xdotool). La accesibilidad la informa mal: una app de Electron se
55
+ * queda «activa» para siempre (visto el 2026-11-16 con dos ventanas activas a la vez).
56
+ * @param {{ session?: string, exec?: typeof run }} [o]
57
+ * @returns {Promise<{ pid: number, title: string } | null>}
58
+ */
59
+ export async function activeWindow ({ session = process.env.XDG_SESSION_TYPE || '', exec = run } = {}) {
60
+ if (session === 'wayland') return null
61
+ try {
62
+ const [title = '', pid = ''] = (await exec('xdotool', ['getactivewindow', 'getwindowname', 'getwindowpid'])).split('\n')
63
+ return pid.trim() ? { pid: Number(pid.trim()), title: title.trim() } : null
64
+ } catch (_) {
65
+ // Sin xdotool, o sin ventana activa (el escritorio): no se sabe, y se usa la accesibilidad.
66
+ return null
67
+ }
68
+ }