talk-rs 0.8.0

Voice dictation for Linux -- record, transcribe, and paste
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! X11 window management helpers.
//!
//! Centre, raise, and activate windows using the `x11rb` crate.
//! Shared by the dictate picker and recordings browser.

pub mod clipboard;
mod keyboard;
pub use keyboard::KeyComboError;
pub mod monitor;
pub mod overlay;
pub mod render_util;
pub mod visualizer;

/// Centre a known X11 window on the monitor containing the mouse
/// pointer, set it always-on-top, and activate it.
///
/// This is the core positioning helper — callers supply the XID
/// directly (from GDK or from a title search).
pub fn x11_centre_and_raise_xid(wid: u32) -> bool {
    use x11rb::connection::Connection;
    use x11rb::protocol::randr::ConnectionExt as _;
    use x11rb::protocol::xproto::*;

    let (conn, screen_num) = match x11rb::connect(None) {
        Ok(c) => c,
        Err(_) => return false,
    };
    let screen = &conn.setup().roots[screen_num];
    let root = screen.root;

    // ── Intern atoms ────────────────────────────────────────────
    let atom_names: &[&[u8]] = &[
        b"_NET_WM_STATE",
        b"_NET_WM_STATE_ABOVE",
        b"_NET_ACTIVE_WINDOW",
    ];
    let cookies: Vec<_> = atom_names
        .iter()
        .map(|n| conn.intern_atom(false, n))
        .collect::<Vec<_>>();
    let mut atoms = Vec::new();
    for cookie in cookies {
        let cookie = match cookie {
            Ok(c) => c,
            Err(_) => return false,
        };
        let atom = match cookie.reply() {
            Ok(r) => r.atom,
            Err(_) => return false,
        };
        atoms.push(atom);
    }
    let a_wm_state = atoms[0];
    let a_above = atoms[1];
    let a_active = atoms[2];

    // ── Query pointer position ──────────────────────────────────
    let pointer = match conn.query_pointer(root) {
        Ok(cookie) => match cookie.reply() {
            Ok(p) => p,
            Err(_) => return false,
        },
        Err(_) => return false,
    };
    let px = pointer.root_x as i32;
    let py = pointer.root_y as i32;

    // ── Find monitor at pointer via RandR ───────────────────────
    let (mon_x, mon_y, mon_w, mon_h) = {
        let default = (0i32, 0i32, 1920i32, 1080i32);
        let resources = match conn.randr_get_screen_resources(root) {
            Ok(cookie) => match cookie.reply() {
                Ok(r) => r,
                Err(_) => return false,
            },
            Err(_) => return false,
        };

        let mut found = default;
        let mut any_monitor = false;
        for &crtc in &resources.crtcs {
            let info = match conn.randr_get_crtc_info(crtc, 0) {
                Ok(cookie) => match cookie.reply() {
                    Ok(i) => i,
                    Err(_) => continue,
                },
                Err(_) => continue,
            };
            if info.width == 0 || info.height == 0 {
                continue;
            }
            let cx = info.x as i32;
            let cy = info.y as i32;
            let cw = info.width as i32;
            let ch = info.height as i32;

            if !any_monitor {
                found = (cx, cy, cw, ch);
                any_monitor = true;
            }

            if px >= cx && px < cx + cw && py >= cy && py < cy + ch {
                found = (cx, cy, cw, ch);
                break;
            }
        }
        found
    };

    // ── Get physical window geometry ────────────────────────────
    let geom = match conn.get_geometry(wid) {
        Ok(cookie) => match cookie.reply() {
            Ok(g) => g,
            Err(_) => return false,
        },
        Err(_) => return false,
    };

    let win_w = geom.width as i32;
    let win_h = geom.height as i32;
    if win_w == 0 || win_h == 0 {
        return false;
    }

    // ── Centre window on monitor ────────────────────────────────
    let x = mon_x + (mon_w - win_w) / 2;
    let y = mon_y + (mon_h - win_h) / 2;

    let _ = conn.configure_window(wid, &ConfigureWindowAux::new().x(x).y(y));

    // ── Set always-on-top (_NET_WM_STATE_ADD ABOVE) ─────────────
    let above_event = ClientMessageEvent::new(32, wid, a_wm_state, [1u32, a_above, 0, 0, 0]);
    let _ = conn.send_event(
        false,
        root,
        EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
        above_event,
    );

    // ── Activate window (_NET_ACTIVE_WINDOW) ────────────────────
    let activate_event = ClientMessageEvent::new(32, wid, a_active, [1u32, 0, 0, 0, 0]);
    let _ = conn.send_event(
        false,
        root,
        EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
        activate_event,
    );

    let _ = conn.flush();
    true
}

/// Find the X11 window whose `_NET_WM_NAME` matches `title`, centre
/// it on the monitor containing the mouse pointer, set it
/// always-on-top, and activate it.
///
/// Used for single-instance detection (raising an already-open
/// picker).  For newly created windows, prefer
/// [`x11_centre_and_raise_xid`] with the XID obtained from
/// [`gdk4_x11`] — it avoids the `_NET_CLIENT_LIST` race entirely.
pub fn x11_centre_and_raise(title: &str) -> bool {
    use x11rb::connection::Connection;
    use x11rb::protocol::xproto::*;

    let (conn, screen_num) = match x11rb::connect(None) {
        Ok(c) => c,
        Err(_) => return false,
    };
    let screen = &conn.setup().roots[screen_num];
    let root = screen.root;

    // ── Intern atoms for title search ───────────────────────────
    let atom_names: &[&[u8]] = &[b"_NET_CLIENT_LIST", b"_NET_WM_NAME", b"UTF8_STRING"];
    let cookies: Vec<_> = atom_names
        .iter()
        .map(|n| conn.intern_atom(false, n))
        .collect::<Vec<_>>();
    let mut atoms = Vec::new();
    for cookie in cookies {
        let cookie = match cookie {
            Ok(c) => c,
            Err(_) => return false,
        };
        let atom = match cookie.reply() {
            Ok(r) => r.atom,
            Err(_) => return false,
        };
        atoms.push(atom);
    }
    let a_client_list = atoms[0];
    let a_wm_name = atoms[1];
    let a_utf8 = atoms[2];

    // ── Find window by _NET_WM_NAME ─────────────────────────────
    let client_list = match conn.get_property(false, root, a_client_list, AtomEnum::WINDOW, 0, 1024)
    {
        Ok(cookie) => match cookie.reply() {
            Ok(prop) => prop,
            Err(_) => return false,
        },
        Err(_) => return false,
    };

    let wid_vec: Vec<u32> = match client_list.value32() {
        Some(iter) => iter.collect(),
        None => return false,
    };

    for &wid in &wid_vec {
        // Try _NET_WM_NAME (UTF-8) first.
        if let Ok(cookie) = conn.get_property(false, wid, a_wm_name, a_utf8, 0, 256) {
            if let Ok(prop) = cookie.reply() {
                if String::from_utf8_lossy(&prop.value) == title {
                    return x11_centre_and_raise_xid(wid);
                }
            }
        }
        // Fallback: WM_NAME (Latin-1).
        if let Ok(cookie) =
            conn.get_property(false, wid, AtomEnum::WM_NAME, AtomEnum::STRING, 0, 256)
        {
            if let Ok(prop) = cookie.reply() {
                if String::from_utf8_lossy(&prop.value) == title {
                    return x11_centre_and_raise_xid(wid);
                }
            }
        }
    }

    false
}

/// Activate (focus) a window by XID via `_NET_ACTIVE_WINDOW`.
///
/// Sends a ClientMessage to the root window requesting the window
/// manager to bring `wid` to the foreground.  Returns `true` if the
/// request was sent successfully, `false` on connection or protocol
/// error.
///
/// Equivalent to `xdotool windowactivate <wid>` (without `--sync`).
pub fn x11_activate_window(wid: u32) -> bool {
    use x11rb::connection::Connection;
    use x11rb::protocol::xproto::*;

    let (conn, screen_num) = match x11rb::connect(None) {
        Ok(c) => c,
        Err(_) => return false,
    };
    let root = conn.setup().roots[screen_num].root;

    let atom = match conn.intern_atom(false, b"_NET_ACTIVE_WINDOW") {
        Ok(cookie) => match cookie.reply() {
            Ok(r) => r.atom,
            Err(_) => return false,
        },
        Err(_) => return false,
    };

    // data[0] = 2 → "message from a pager" (same as xdotool)
    // data[1] = 0 → CurrentTime
    let event = ClientMessageEvent::new(32, wid, atom, [2u32, 0, 0, 0, 0]);
    let _ = conn.send_event(
        false,
        root,
        EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
        event,
    );

    let _ = conn.flush();
    true
}

/// Simulate a key combination (e.g. Ctrl+Shift+V) using the XTest
/// extension.
///
/// `keysyms` is a slice of X11 keysyms to press simultaneously.
/// All keys are pressed in order, then released in reverse order,
/// matching the behaviour of `xdotool key`.
///
/// Compatibility wrapper returning whether checked injection succeeded.
pub fn x11_send_key_combo(keysyms: &[u32]) -> bool {
    x11_send_key_combo_checked(keysyms).is_ok()
}

/// Checked key-combination injection used by internal paste callers.
///
/// Returns a phase-specific error if keyboard state cannot be read, a
/// conflicting key remains active past the bounded wait, or a checked XTest
/// request fails. Cleanup attempts releases for every key that may have been
/// injected; server failure or disconnect can still prevent a release.
pub fn x11_send_key_combo_checked(keysyms: &[u32]) -> Result<(), KeyComboError> {
    keyboard::send_key_combo(keysyms)
}

/// Send a single key press+release `count` times with no inter-key
/// delay, matching `xdotool key --delay 0 --repeat N <key>`.
///
/// Compatibility wrapper returning whether checked repeated injection
/// succeeded.
pub fn x11_send_key_repeat(keysym: u32, count: usize) -> bool {
    x11_send_key_repeat_checked(keysym, count).is_ok()
}

/// Checked repeated key injection used for replacement backspaces.
pub fn x11_send_key_repeat_checked(keysym: u32, count: usize) -> Result<(), KeyComboError> {
    keyboard::send_key_repeat(keysym, count)
}

/// Resolve the X11 client-base of a window XID via a fresh server
/// round-trip.
///
/// X11 packs every client's resources (windows, atoms, pixmaps, …)
/// into a contiguous block: every XID minted by a given client
/// shares the same high-bits prefix.  The prefix is exactly
/// `xid & !resource_id_mask`, where `resource_id_mask` is reported
/// in the connection setup.  Two windows from the SAME client
/// (e.g. a toplevel and the focus-grabbing child widget it created)
/// therefore yield the same client-base — the stable identity the
/// deterministic paste gate uses to confirm "the target consumed
/// this chunk".
///
/// Returns `None` when the X11 connection cannot be established.
/// Does NOT validate that `wid` is a live window — masking is a pure
/// bit operation, so a stale XID still yields its (now-defunct)
/// client-base.  Callers should treat a `None` here as "blind paste"
/// and fall back to the legacy gate, never as "abort".
pub fn x11_client_base(wid: u32) -> Option<u32> {
    use x11rb::connection::Connection;

    let (conn, _screen_num) = x11rb::connect(None).ok()?;
    let mask = conn.setup().resource_id_mask;
    Some(crate::x11::clipboard::client_base(wid, mask))
}

/// Return the XID of the currently active (focused) window via
/// `_NET_ACTIVE_WINDOW` on the root window, or `None` if the query
/// fails.
///
/// Equivalent to `xdotool getactivewindow`.
pub fn x11_get_active_window() -> Option<u32> {
    use x11rb::connection::Connection;
    use x11rb::protocol::xproto::*;

    let (conn, screen_num) = x11rb::connect(None).ok()?;
    let root = conn.setup().roots[screen_num].root;

    let atom = conn
        .intern_atom(false, b"_NET_ACTIVE_WINDOW")
        .ok()?
        .reply()
        .ok()?
        .atom;

    let prop = conn
        .get_property(false, root, atom, AtomEnum::WINDOW, 0, 1)
        .ok()?
        .reply()
        .ok()?;

    let wid = prop.value32()?.next()?;
    if wid == 0 {
        return None;
    }
    Some(wid)
}

/// Read the `WM_CLASS` property of `wid` and return its
/// `(instance, class)` pair, or `None` if the property is missing or
/// malformed.
///
/// `WM_CLASS` is a STRING property containing two NUL-terminated
/// strings: the resource-name (instance) followed by the class.
/// Per ICCCM § 4.1.2.5.  This is what `xprop -id <wid> WM_CLASS`
/// prints and what the `match-wm-class` paste node uses for routing.
pub fn x11_get_wm_class(wid: u32) -> Option<(String, String)> {
    let (conn, _screen_num) = x11rb::connect(None).ok()?;
    x11_get_wm_class_from_connection(&conn, wid)
}

fn x11_get_wm_class_from_connection<C: x11rb::connection::Connection>(
    conn: &C,
    wid: u32,
) -> Option<(String, String)> {
    use x11rb::protocol::xproto::*;

    // WM_CLASS is a pre-defined ICCCM atom — fetch via `intern_atom`
    // (cheaper than hard-coding the atom id, robust across servers).
    let atom_wm_class = conn
        .intern_atom(false, b"WM_CLASS")
        .ok()?
        .reply()
        .ok()?
        .atom;

    // Request up to 1 KiB; WM_CLASS pairs are always tiny.  Type
    // STRING (Latin-1) is the ICCCM-mandated encoding; a few apps
    // ship UTF8_STRING — we accept any 8-bit value the server hands
    // back.
    let prop = conn
        .get_property(false, wid, atom_wm_class, AtomEnum::ANY, 0, 1024 / 4)
        .ok()?
        .reply()
        .ok()?;

    if prop.format != 8 {
        return None;
    }
    let bytes = prop.value;
    // Split on the FIRST NUL to separate instance from class; class
    // is up to the second NUL (or end of buffer).
    let mut parts = bytes.split(|&b| b == 0);
    let instance = parts.next()?;
    let class = parts.next()?;
    if instance.is_empty() && class.is_empty() {
        return None;
    }
    Some((
        String::from_utf8_lossy(instance).into_owned(),
        String::from_utf8_lossy(class).into_owned(),
    ))
}

/// Stable fields used to bind a foreground-process probe to one mapped X11
/// client window. Callers query this before and after probing and reject a
/// changed snapshot rather than applying stale identity to a new surface.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct X11TargetSnapshot {
    pub pid: u32,
    pub wm_class: (String, String),
}

/// Read the mapped target's `_NET_WM_PID` and `WM_CLASS` in one fresh X11
/// connection. This does not claim X11 atomicity; callers must re-read and
/// compare the result after process inspection.
pub fn x11_target_snapshot(wid: u32) -> Option<X11TargetSnapshot> {
    use x11rb::protocol::xproto::*;

    let (conn, _screen_num) = x11rb::connect(None).ok()?;
    let attributes = conn.get_window_attributes(wid).ok()?.reply().ok()?;
    if attributes.map_state != MapState::VIEWABLE {
        return None;
    }
    let pid_atom = conn
        .intern_atom(false, b"_NET_WM_PID")
        .ok()?
        .reply()
        .ok()?
        .atom;
    let pid_property = conn
        .get_property(false, wid, pid_atom, AtomEnum::CARDINAL, 0, 1)
        .ok()?
        .reply()
        .ok()?;
    let pid = pid_property.value32()?.next()?;
    if pid == 0 {
        return None;
    }
    let wm_class = x11_get_wm_class_from_connection(&conn, wid)?;
    Some(X11TargetSnapshot { pid, wm_class })
}

#[cfg(test)]
mod keyboard_api_tests {
    #[test]
    fn public_bool_wrappers_remain_compatible() {
        let _combo: fn(&[u32]) -> bool = super::x11_send_key_combo;
        let _repeat: fn(u32, usize) -> bool = super::x11_send_key_repeat;
    }
}