Skip to main content

agentmux_srv/server/streamed_browser/screen/
randr.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A person resizes the pane: the virtual screen follows (the RANDR extension), and the browser's maximised window with it. Xvfb can make
5//! its screen smaller or bigger only up to the size it was started with, so a session starts the screen at `MAX_W` by `MAX_H` and sets it to
6//! the pane's size at once, and every later resize is a new mode of that screen. Nothing here attaches to the browser.
7
8use std::time::{Duration, Instant};
9
10use x11rb::connection::Connection;
11use x11rb::protocol::randr::{ConnectionExt as _, GetScreenResourcesCurrentReply, ModeFlag, ModeInfo, Rotation, SetConfig};
12use x11rb::CURRENT_TIME;
13
14use super::x::Screen;
15
16/// The smallest side of a screen, and the largest screen a session can have (the size its Xvfb is started with).
17pub const MIN_SIDE: u16 = 100;
18pub const MAX_W: u16 = 4096;
19pub const MAX_H: u16 = 2304;
20/// The prefix of the names of the modes this makes, so the ones no longer used can be told from the screen's own.
21const MODE_PREFIX: &str = "amx-";
22/// How long the pane's size must stay the same before the screen is resized (a drag sends many sizes).
23pub const SETTLE: Duration = Duration::from_millis(150);
24
25/// A size asked for, cut to what a screen can be.
26pub fn clamp(w: u32, h: u32) -> (u16, u16) {
27    (w.clamp(u32::from(MIN_SIDE), u32::from(MAX_W)) as u16, h.clamp(u32::from(MIN_SIDE), u32::from(MAX_H)) as u16)
28}
29
30/// The size the screen is set to first, so that the screen's output (which is as big as the screen was) fits in it while it changes size:
31/// big enough for both the old size and the new.
32pub fn bridge(from: (u16, u16), to: (u16, u16)) -> (u16, u16) {
33    (from.0.max(to.0), from.1.max(to.1))
34}
35
36/// The name of the mode for a size.
37pub fn mode_name(w: u16, h: u16) -> String {
38    format!("{MODE_PREFIX}{w}x{h}")
39}
40
41/// The millimetres a side of `pixels` is, at the 96 dots an inch the screen is made with.
42pub fn millimetres(pixels: u16) -> u32 {
43    u32::from(pixels) * 254 / 960
44}
45
46/// The last size the pane asked for, until it has stayed the same for `SETTLE`: then it is due.
47#[derive(Default)]
48pub struct Settle {
49    wanted: Option<((u16, u16), Instant)>,
50}
51
52impl Settle {
53    pub fn ask(&mut self, size: (u16, u16), now: Instant) {
54        if !matches!(self.wanted, Some((s, _)) if s == size) {
55            self.wanted = Some((size, now));
56        }
57    }
58
59    /// When the wanted size is due, if there is one.
60    pub fn due_at(&self) -> Option<Instant> {
61        self.wanted.map(|(_, at)| at + SETTLE)
62    }
63
64    /// The wanted size once it is due; it is forgotten when taken.
65    pub fn take(&mut self, now: Instant) -> Option<(u16, u16)> {
66        match self.wanted {
67            Some((size, at)) if now >= at + SETTLE => {
68                self.wanted = None;
69                Some(size)
70            }
71            _ => None,
72        }
73    }
74}
75
76impl Screen {
77    /// Make the screen `w` by `h` (cut to what a screen can be). The windows on it follow if the window manager lets a maximised window follow.
78    pub fn resize(&self, w: u16, h: u16) -> Result<(), String> {
79        let (w, h) = clamp(u32::from(w), u32::from(h));
80        let from = self.size();
81        if from == (w, h) {
82            return Ok(());
83        }
84        let x = |e: &dyn std::fmt::Display| format!("the screen could not be resized: {e}");
85        self.conn.randr_query_version(1, 3).map_err(|e| x(&e))?.reply().map_err(|e| x(&e))?;
86        let res = self.conn.randr_get_screen_resources_current(self.root).map_err(|e| x(&e))?.reply().map_err(|e| x(&e))?;
87        let (Some(&crtc), Some(&output)) = (res.crtcs.first(), res.outputs.first()) else {
88            return Err("the screen could not be resized: it has no output".to_string());
89        };
90        let mode = match found(&res, w, h) {
91            Some(id) => id,
92            None => self.make_mode(w, h)?,
93        };
94        self.conn.randr_add_output_mode(output, mode).map_err(|e| x(&e))?.check().map_err(|e| x(&e))?;
95        let (bw, bh) = bridge(from, (w, h));
96        if (bw, bh) != from {
97            self.set_screen(bw, bh)?;
98        }
99        // Adding a mode and changing the screen's size can advance the screen's configuration time, which the change below must quote: ask for it now.
100        let res = self.conn.randr_get_screen_resources_current(self.root).map_err(|e| x(&e))?.reply().map_err(|e| x(&e))?;
101        let set = self.conn.randr_set_crtc_config(crtc, CURRENT_TIME, res.config_timestamp, 0, 0, mode, Rotation::ROTATE0, &[output]).map_err(|e| x(&e))?.reply().map_err(|e| x(&e))?;
102        if set.status != SetConfig::SUCCESS {
103            return Err(format!("the screen could not be resized: the output refused the mode ({:?})", set.status));
104        }
105        self.set_screen(w, h)?;
106        self.set_size(w, h);
107        // The modes this made before and no longer shows are let go, so a long drag does not fill the screen's list.
108        for old in ours(&res).filter(|&id| id != mode) {
109            let _ = self.conn.randr_delete_output_mode(output, old);
110            let _ = self.conn.randr_destroy_mode(old);
111        }
112        self.conn.flush().map_err(|e| x(&e))?;
113        // The window manager has the new screen (its work area follows at once); a maximised window is asked again to fill it.
114        self.refit()
115    }
116
117    fn set_screen(&self, w: u16, h: u16) -> Result<(), String> {
118        self.conn
119            .randr_set_screen_size(self.root, w, h, millimetres(w), millimetres(h))
120            .map_err(|e| e.to_string())?
121            .check()
122            .map_err(|e| format!("the screen could not be resized: {e}"))
123    }
124
125    fn make_mode(&self, w: u16, h: u16) -> Result<u32, String> {
126        let name = mode_name(w, h);
127        // A mode with no timing of its own: a virtual screen has no monitor to drive.
128        let info = ModeInfo { id: 0, width: w, height: h, dot_clock: 0, hsync_start: w, hsync_end: w, htotal: w, hskew: 0, vsync_start: h, vsync_end: h, vtotal: h, name_len: name.len() as u16, mode_flags: ModeFlag::from(0u32) };
129        let made = self.conn.randr_create_mode(self.root, info, name.as_bytes()).map_err(|e| e.to_string())?.reply().map_err(|e| format!("the screen could not be resized: {e}"))?;
130        Ok(made.mode)
131    }
132
133}
134
135/// The id of the mode that is `w` by `h` and was made by this, if the screen has it.
136fn found(res: &GetScreenResourcesCurrentReply, w: u16, h: u16) -> Option<u32> {
137    let want = mode_name(w, h);
138    named(res).find(|(_, name)| *name == want.as_bytes()).map(|(id, _)| id)
139}
140
141/// The modes this made.
142fn ours(res: &GetScreenResourcesCurrentReply) -> impl Iterator<Item = u32> + '_ {
143    named(res).filter(|(_, name)| name.starts_with(MODE_PREFIX.as_bytes())).map(|(id, _)| id)
144}
145
146/// Each mode's id and name (the names are one run of bytes, in the order of the modes).
147fn named(res: &GetScreenResourcesCurrentReply) -> impl Iterator<Item = (u32, &[u8])> {
148    let mut at = 0usize;
149    res.modes.iter().map(move |m| {
150        let end = (at + usize::from(m.name_len)).min(res.names.len());
151        let name = &res.names[at.min(end)..end];
152        at = end;
153        (m.id, name)
154    })
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn a_size_is_cut_to_what_a_screen_can_be() {
163        assert_eq!(clamp(10, 10), (MIN_SIDE, MIN_SIDE));
164        assert_eq!(clamp(800, 600), (800, 600));
165        assert_eq!(clamp(100_000, 100_000), (MAX_W, MAX_H));
166    }
167
168    #[test]
169    fn the_screen_is_bridged_by_a_size_that_holds_both() {
170        assert_eq!(bridge((800, 600), (1024, 400)), (1024, 600));
171        assert_eq!(bridge((1280, 720), (640, 480)), (1280, 720));
172    }
173
174    #[test]
175    fn a_mode_is_named_for_its_size_and_a_side_has_millimetres() {
176        assert_eq!(mode_name(1280, 720), "amx-1280x720");
177        assert_eq!(millimetres(960), 254);
178    }
179
180    #[test]
181    fn a_size_is_due_when_it_has_stayed_the_same_for_the_settle_time() {
182        let t0 = Instant::now();
183        let mut s = Settle::default();
184        assert!(s.take(t0).is_none() && s.due_at().is_none());
185        s.ask((800, 600), t0);
186        assert!(s.take(t0 + SETTLE / 2).is_none(), "not yet");
187        // The same size asked again does not move the time; another size does.
188        s.ask((800, 600), t0 + SETTLE / 2);
189        assert_eq!(s.due_at(), Some(t0 + SETTLE));
190        s.ask((900, 600), t0 + SETTLE / 2);
191        assert!(s.take(t0 + SETTLE).is_none());
192        assert_eq!(s.take(t0 + SETTLE / 2 + SETTLE), Some((900, 600)));
193        assert!(s.take(t0 + SETTLE * 10).is_none(), "taken once");
194    }
195}