agentmux_srv/server/streamed_browser/screen/
randr.rs1use 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
16pub const MIN_SIDE: u16 = 100;
18pub const MAX_W: u16 = 4096;
19pub const MAX_H: u16 = 2304;
20const MODE_PREFIX: &str = "amx-";
22pub const SETTLE: Duration = Duration::from_millis(150);
24
25pub 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
30pub fn bridge(from: (u16, u16), to: (u16, u16)) -> (u16, u16) {
33 (from.0.max(to.0), from.1.max(to.1))
34}
35
36pub fn mode_name(w: u16, h: u16) -> String {
38 format!("{MODE_PREFIX}{w}x{h}")
39}
40
41pub fn millimetres(pixels: u16) -> u32 {
43 u32::from(pixels) * 254 / 960
44}
45
46#[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 pub fn due_at(&self) -> Option<Instant> {
61 self.wanted.map(|(_, at)| at + SETTLE)
62 }
63
64 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 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 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 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 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 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
135fn 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
141fn ours(res: &GetScreenResourcesCurrentReply) -> impl Iterator<Item = u32> + '_ {
143 named(res).filter(|(_, name)| name.starts_with(MODE_PREFIX.as_bytes())).map(|(id, _)| id)
144}
145
146fn 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 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}