codex-wrangler 1.3.5

Linux/X11/i3 tray switcher for live coding-agent TUI sessions
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
470
471
472
473
474
475
476
477
478
use std::{
    collections::{HashMap, HashSet},
    os::fd::{AsFd as _, BorrowedFd},
};

use anyhow::{Context as _, Result};
use x11rb::{
    CURRENT_TIME, NONE,
    connection::Connection,
    errors::ReplyError,
    protocol::{
        ErrorKind, Event,
        xproto::{
            Atom, AtomEnum, ChangeWindowAttributesAux, ClientMessageEvent, ConfigureWindowAux,
            ConnectionExt as _, EventMask, PropMode, StackMode, Window,
        },
    },
    rust_connection::RustConnection,
    wrapper::ConnectionExt as _,
};

struct Atoms {
    clients: Atom,
    pid: Atom,
    active: Atom,
    desktop: Atom,
    desktop_names: Atom,
    current_desktop: Atom,
    name: Atom,
    net_name: Atom,
    protocols: Atom,
    delete_window: Atom,
}

pub struct Desktop {
    conn: RustConnection,
    root: Window,
    atoms: Atoms,
    watched: HashSet<Window>,
    action_required: HashMap<Window, bool>,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum DesktopSignal {
    Focus,
    Topology,
    Workspace,
    Terminal,
}

impl Desktop {
    pub fn connect() -> Result<Self> {
        let (conn, screen) = RustConnection::connect(None).context("connect to X11")?;
        let root = conn.setup().roots[screen].root;
        let atoms = Atoms {
            clients: intern(&conn, "_NET_CLIENT_LIST")?,
            pid: intern(&conn, "_NET_WM_PID")?,
            active: intern(&conn, "_NET_ACTIVE_WINDOW")?,
            desktop: intern(&conn, "_NET_WM_DESKTOP")?,
            desktop_names: intern(&conn, "_NET_DESKTOP_NAMES")?,
            current_desktop: intern(&conn, "_NET_CURRENT_DESKTOP")?,
            name: intern(&conn, "WM_NAME")?,
            net_name: intern(&conn, "_NET_WM_NAME")?,
            protocols: intern(&conn, "WM_PROTOCOLS")?,
            delete_window: intern(&conn, "WM_DELETE_WINDOW")?,
        };
        conn.change_window_attributes(
            root,
            &ChangeWindowAttributesAux::new().event_mask(EventMask::PROPERTY_CHANGE),
        )?
        .check()
        .context("subscribe to X11 desktop changes")?;
        conn.flush().context("arm X11 desktop watch")?;
        Ok(Self {
            conn,
            root,
            atoms,
            watched: HashSet::new(),
            action_required: HashMap::new(),
        })
    }

    pub fn as_fd(&self) -> BorrowedFd<'_> {
        self.conn.stream().as_fd()
    }

    pub fn active_window(&self) -> Result<Option<Window>> {
        self.window(self.root, self.atoms.active)
    }

    pub fn requires_action(&self, window: Window) -> bool {
        self.action_required.get(&window).copied().unwrap_or(false)
    }

    fn read_requires_action(&self, window: Window) -> Result<bool> {
        let title = match self.text(window, self.atoms.net_name)? {
            Some(title) => Some(title),
            None => self.text(window, self.atoms.name)?,
        };
        Ok(title.is_some_and(|title| title_requires_action(&title)))
    }

    pub fn watch_terminals(&mut self, windows: impl IntoIterator<Item = Window>) -> Result<()> {
        let windows = windows.into_iter().collect::<HashSet<_>>();
        let mut watched = self
            .watched
            .intersection(&windows)
            .copied()
            .collect::<HashSet<_>>();
        for window in windows.difference(&self.watched) {
            let result = self
                .conn
                .change_window_attributes(
                    *window,
                    &ChangeWindowAttributesAux::new().event_mask(EventMask::PROPERTY_CHANGE),
                )?
                .check();
            match result {
                Ok(()) => {
                    let _new = watched.insert(*window);
                    let required = self.read_requires_action(*window)?;
                    let _prior = self.action_required.insert(*window, required);
                }
                Err(error) if window_vanished(&error) => {}
                Err(error) => {
                    return Err(error).with_context(|| format!("watch terminal window {window}"));
                }
            }
        }
        self.watched = watched;
        self.action_required
            .retain(|window, _required| self.watched.contains(window));
        self.conn.flush().context("arm terminal title watches")
    }

    pub fn drain_events(&mut self) -> Result<HashSet<DesktopSignal>> {
        let mut signals = HashSet::new();
        while let Some(event) = self
            .conn
            .poll_for_event()
            .context("poll X11 desktop events")?
        {
            if let Event::PropertyNotify(event) = event {
                if event.window == self.root {
                    if event.atom == self.atoms.active {
                        let _new = signals.insert(DesktopSignal::Focus);
                    }
                    if event.atom == self.atoms.clients {
                        let _new = signals.insert(DesktopSignal::Topology);
                    }
                    if event.atom == self.atoms.desktop_names
                        || event.atom == self.atoms.current_desktop
                    {
                        let _new = signals.insert(DesktopSignal::Workspace);
                    }
                } else if self.watched.contains(&event.window) {
                    if event.atom == self.atoms.desktop {
                        let _new = signals.insert(DesktopSignal::Workspace);
                    }
                    if event.atom == self.atoms.name || event.atom == self.atoms.net_name {
                        let required = self.read_requires_action(event.window)?;
                        let _prior = self.action_required.insert(event.window, required);
                        let _new = signals.insert(DesktopSignal::Terminal);
                    }
                }
            }
        }
        Ok(signals)
    }

    pub fn windows_by_pid(&self) -> Result<HashMap<u32, Vec<Window>>> {
        let clients = self
            .conn
            .get_property(
                false,
                self.root,
                self.atoms.clients,
                AtomEnum::WINDOW,
                0,
                u32::MAX,
            )?
            .reply()
            .context("read X11 client list")?
            .value32()
            .map(Iterator::collect::<Vec<_>>)
            .unwrap_or_default();
        let clients = if clients.is_empty() {
            self.descendants()?
        } else {
            clients
        };
        let mut windows = HashMap::new();
        for window in clients {
            if let Some(pid) = self.window_pid(window)? {
                windows.entry(pid).or_insert_with(Vec::new).push(window);
            }
        }
        Ok(windows)
    }

    pub fn activate(&self, window: Window) -> Result<()> {
        self.drive_window(window, None)?;
        self.conn.flush().context("activate harness terminal")
    }

    pub fn close(&self, window: Window) -> Result<()> {
        let event = ClientMessageEvent::new(
            32,
            window,
            self.atoms.protocols,
            [self.atoms.delete_window, CURRENT_TIME, 0, 0, 0],
        );
        self.conn
            .send_event(false, window, EventMask::NO_EVENT, event)?
            .check()
            .context("request terminal close")?;
        self.conn.flush().context("flush terminal close")
    }

    fn drive_window(&self, window: Window, destination: Option<u32>) -> Result<()> {
        if let Some(index) = destination {
            self.conn
                .change_property32(
                    PropMode::REPLACE,
                    window,
                    self.atoms.desktop,
                    AtomEnum::CARDINAL,
                    &[index],
                )?
                .check()
                .context("prime destination workspace")?;
            let event =
                ClientMessageEvent::new(32, window, self.atoms.desktop, [index, 2, 0, 0, 0]);
            self.conn
                .send_event(
                    false,
                    self.root,
                    EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
                    event,
                )?
                .check()
                .context("move window to destination workspace")?;
        }
        self.conn
            .map_window(window)?
            .check()
            .context("map destination window")?;
        self.conn
            .configure_window(
                window,
                &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
            )?
            .check()
            .context("raise destination window")?;
        let event =
            ClientMessageEvent::new(32, window, self.atoms.active, [2, CURRENT_TIME, 0, 0, 0]);
        self.conn
            .send_event(
                false,
                self.root,
                EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
                event,
            )?
            .check()
            .context("announce active window")?;
        Ok(())
    }

    pub fn workspace_numbers(
        &self,
        windows: impl IntoIterator<Item = Window>,
    ) -> Result<HashMap<Window, u32>> {
        let names = self.desktop_names()?;
        let mut workspaces = HashMap::new();
        for window in windows {
            let Some(index) = self.cardinal(window, self.atoms.desktop)? else {
                continue;
            };
            let Some(Some(number)) = usize::try_from(index)
                .ok()
                .and_then(|index| names.get(index))
            else {
                continue;
            };
            let _old = workspaces.insert(window, *number);
        }
        Ok(workspaces)
    }

    pub fn current_desktop() -> Result<Option<u32>> {
        let desktop = Self::connect()?;
        desktop.cardinal(desktop.root, desktop.atoms.current_desktop)
    }

    pub fn process_floating(pid: u32) -> Result<Option<bool>> {
        let desktop = Self::connect()?;
        let Some(window) = desktop.window_by_pid(pid)? else {
            return Ok(None);
        };
        crate::i3::window_floating(window)
    }

    pub fn summon_process_to(pid: u32, index: Option<u32>, floating: bool) -> Result<bool> {
        let desktop = Self::connect()?;
        let Some(window) = desktop.window_by_pid(pid)? else {
            return Ok(false);
        };
        let destination = floating.then_some(index).flatten();
        desktop.drive_window(window, destination)?;
        desktop.conn.flush().context("summon Wrangler")?;
        let workspace = desktop.cardinal(window, desktop.atoms.desktop)?;
        let workspace_settled = match destination {
            Some(index) => desktop.cardinal(window, desktop.atoms.desktop)? == Some(index),
            None => match workspace {
                Some(index) => {
                    desktop.cardinal(desktop.root, desktop.atoms.current_desktop)? == Some(index)
                }
                None => true,
            },
        };
        let focus_settled = desktop.window(desktop.root, desktop.atoms.active)? == Some(window);
        Ok(workspace_settled && focus_settled)
    }

    fn window_pid(&self, window: Window) -> Result<Option<u32>> {
        self.cardinal(window, self.atoms.pid)
    }

    pub fn window_by_pid(&self, pid: u32) -> Result<Option<Window>> {
        if let Some(window) = self
            .windows_by_pid()?
            .get(&pid)
            .and_then(|windows| windows.first())
        {
            return Ok(Some(*window));
        }
        for window in self.descendants()? {
            if self.window_pid(window)? == Some(pid) {
                return Ok(Some(window));
            }
        }
        Ok(None)
    }

    fn cardinal(&self, window: Window, atom: Atom) -> Result<Option<u32>> {
        let reply = self
            .conn
            .get_property(false, window, atom, AtomEnum::CARDINAL, 0, 1)?
            .reply();
        match reply {
            Ok(reply) => Ok(reply.value32().and_then(|mut values| values.next())),
            Err(error) if window_vanished(&error) => Ok(None),
            Err(error) => {
                Err(error).with_context(|| format!("read X11 cardinal {atom} from window {window}"))
            }
        }
    }

    fn window(&self, window: Window, atom: Atom) -> Result<Option<Window>> {
        let reply = self
            .conn
            .get_property(false, window, atom, AtomEnum::WINDOW, 0, 1)?
            .reply();
        match reply {
            Ok(reply) => Ok(reply.value32().and_then(|mut values| values.next())),
            Err(error) if window_vanished(&error) => Ok(None),
            Err(error) => {
                Err(error).with_context(|| format!("read X11 window {atom} from window {window}"))
            }
        }
    }

    fn text(&self, window: Window, atom: Atom) -> Result<Option<String>> {
        let reply = self
            .conn
            .get_property(false, window, atom, AtomEnum::ANY, 0, u32::MAX)?
            .reply();
        match reply {
            Ok(reply) if reply.value.is_empty() => Ok(None),
            Ok(reply) => Ok(Some(String::from_utf8_lossy(&reply.value).into_owned())),
            Err(error) if window_vanished(&error) => Ok(None),
            Err(error) => {
                Err(error).with_context(|| format!("read X11 text {atom} from window {window}"))
            }
        }
    }

    fn desktop_names(&self) -> Result<Vec<Option<u32>>> {
        let bytes = self
            .conn
            .get_property(
                false,
                self.root,
                self.atoms.desktop_names,
                AtomEnum::ANY,
                0,
                u32::MAX,
            )?
            .reply()
            .context("read X11 desktop names")?
            .value;
        Ok(bytes
            .split(|byte| *byte == 0)
            .map(workspace_number)
            .collect())
    }

    fn descendants(&self) -> Result<Vec<Window>> {
        let mut frontier = vec![self.root];
        let mut seen = HashSet::from([self.root]);
        let mut descendants = Vec::new();
        while let Some(parent) = frontier.pop() {
            let reply = self.conn.query_tree(parent)?.reply();
            let children = match reply {
                Ok(reply) => reply.children,
                Err(error) if window_vanished(&error) => continue,
                Err(error) => {
                    return Err(error).with_context(|| format!("walk X11 window {parent}"));
                }
            };
            for child in children {
                if child != NONE && seen.insert(child) {
                    descendants.push(child);
                    frontier.push(child);
                }
            }
        }
        Ok(descendants)
    }
}

fn window_vanished(error: &ReplyError) -> bool {
    matches!(error, ReplyError::X11Error(error) if error.error_kind == ErrorKind::Window)
}

fn title_requires_action(title: &str) -> bool {
    title
        .split('|')
        .next()
        .is_some_and(|head| head.trim_end().ends_with("Action Required"))
}

fn workspace_number(name: &[u8]) -> Option<u32> {
    let end = name
        .iter()
        .position(|byte| !byte.is_ascii_digit())
        .unwrap_or(name.len());
    (end > 0).then(|| std::str::from_utf8(&name[..end]).ok()?.parse().ok())?
}

fn intern(conn: &RustConnection, name: &str) -> Result<Atom> {
    Ok(conn
        .intern_atom(false, name.as_bytes())?
        .reply()
        .with_context(|| format!("intern X11 atom `{name}`"))?
        .atom)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn extracts_i3s_numeric_workspace_prefix() {
        assert_eq!(workspace_number(b"17: codex"), Some(17));
        assert_eq!(workspace_number(b"8"), Some(8));
        assert_eq!(workspace_number(b"codex"), None);
        assert_eq!(workspace_number(b""), None);
    }

    #[test]
    fn recognizes_codex_action_required_titles_without_eating_project_names() {
        assert!(title_requires_action("[ ! ] Action Required | projects"));
        assert!(title_requires_action("[ . ] Action Required | projects"));
        assert!(!title_requires_action("[ * ] Working | projects"));
        assert!(!title_requires_action("Action Required Cleanup"));
    }
}