forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

mutter_display_config.rs349 lines, 11.4 KiBHistoryRawDownload
1use std::collections::HashMap;
2use std::str::FromStr;
3use std::sync::{Arc, Mutex};
4
5use serde::{Deserialize, Serialize};
6use smithay::utils::Size;
7use zbus::object_server::SignalEmitter;
8use zbus::zvariant::{self, OwnedValue, Type};
9use zbus::{fdo, interface};
10
11use super::{request_name, Start};
12use crate::backend::IpcOutputMap;
13use crate::utils::is_laptop_panel;
14use crate::utils::scale::supported_scales;
15
16pub struct DisplayConfig {
17 to_niri: calloop::channel::Sender<HashMap<String, Option<niri_config::Output>>>,
18 ipc_outputs: Arc<Mutex<IpcOutputMap>>,
19}
20
21#[derive(Serialize, Type)]
22pub struct Monitor {
23 names: (String, String, String, String),
24 modes: Vec<Mode>,
25 properties: HashMap<String, OwnedValue>,
26}
27
28#[derive(Serialize, Type)]
29pub struct Mode {
30 id: String,
31 width: i32,
32 height: i32,
33 refresh_rate: f64,
34 preferred_scale: f64,
35 supported_scales: Vec<f64>,
36 properties: HashMap<String, OwnedValue>,
37}
38
39#[derive(Serialize, Type)]
40pub struct LogicalMonitor {
41 x: i32,
42 y: i32,
43 scale: f64,
44 transform: u32,
45 is_primary: bool,
46 monitors: Vec<(String, String, String, String)>,
47 properties: HashMap<String, OwnedValue>,
48}
49
50// ApplyMonitorsConfig
51#[derive(Deserialize, Type)]
52pub struct LogicalMonitorConfiguration {
53 x: i32,
54 y: i32,
55 scale: f64,
56 transform: u32,
57 _is_primary: bool,
58 monitors: Vec<(String, String, HashMap<String, OwnedValue>)>,
59}
60
61#[interface(name = "org.gnome.Mutter.DisplayConfig")]
62impl DisplayConfig {
63 async fn get_current_state(
64 &self,
65 ) -> fdo::Result<(
66 u32,
67 Vec<Monitor>,
68 Vec<LogicalMonitor>,
69 HashMap<String, OwnedValue>,
70 )> {
71 // Construct the DBus response.
72 let mut monitors = Vec::new();
73 let mut logical_monitors = Vec::new();
74
75 for output in self.ipc_outputs.lock().unwrap().values() {
76 // Loosely matches the check in Mutter.
77 let c = &output.name;
78 let is_laptop_panel = is_laptop_panel(c);
79 let display_name = make_display_name(output, is_laptop_panel);
80
81 let mut properties = HashMap::new();
82 properties.insert(
83 String::from("display-name"),
84 OwnedValue::from(zvariant::Str::from(display_name)),
85 );
86 properties.insert(
87 String::from("is-builtin"),
88 OwnedValue::from(is_laptop_panel),
89 );
90
91 let mut modes: Vec<Mode> = output
92 .modes
93 .iter()
94 .map(|m| {
95 let niri_ipc::Mode {
96 width,
97 height,
98 refresh_rate,
99 is_preferred,
100 } = *m;
101 let width = i32::from(width);
102 let height = i32::from(height);
103 let refresh_rate = refresh_rate as f64 / 1000.;
104
105 Mode {
106 id: format!("{width}x{height}@{refresh_rate:.3}"),
107 width,
108 height,
109 refresh_rate,
110 preferred_scale: 1.,
111 supported_scales: supported_scales(Size::from((width, height))).collect(),
112 properties: HashMap::from([(
113 String::from("is-preferred"),
114 OwnedValue::from(is_preferred),
115 )]),
116 }
117 })
118 .collect();
119 if let Some(mode) = output.current_mode {
120 modes[mode]
121 .properties
122 .insert(String::from("is-current"), OwnedValue::from(true));
123 }
124
125 let connector = c.clone();
126 let model = output.model.clone();
127 let make = output.make.clone();
128
129 // Serial is used for session restore, so fall back to the connector name if it's
130 // not available.
131 let serial = output.serial.as_ref().unwrap_or(&connector).clone();
132
133 let names = (connector, make, model, serial);
134
135 if let Some(logical) = output.logical.as_ref() {
136 let transform = match logical.transform {
137 niri_ipc::Transform::Normal => 0,
138 niri_ipc::Transform::_90 => 1,
139 niri_ipc::Transform::_180 => 2,
140 niri_ipc::Transform::_270 => 3,
141 niri_ipc::Transform::Flipped => 4,
142 niri_ipc::Transform::Flipped90 => 5,
143 niri_ipc::Transform::Flipped180 => 6,
144 niri_ipc::Transform::Flipped270 => 7,
145 };
146
147 logical_monitors.push(LogicalMonitor {
148 x: logical.x,
149 y: logical.y,
150 scale: logical.scale,
151 transform,
152 is_primary: false,
153 monitors: vec![names.clone()],
154 properties: HashMap::new(),
155 });
156 }
157
158 monitors.push(Monitor {
159 names,
160 modes,
161 properties,
162 });
163 }
164
165 // Sort by connector.
166 monitors.sort_unstable_by(|a, b| a.names.0.cmp(&b.names.0));
167 logical_monitors.sort_unstable_by(|a, b| a.monitors[0].0.cmp(&b.monitors[0].0));
168
169 let properties = HashMap::from([(String::from("layout-mode"), OwnedValue::from(1u32))]);
170 Ok((0, monitors, logical_monitors, properties))
171 }
172
173 async fn apply_monitors_config(
174 &self,
175 _serial: u32,
176 method: u32,
177 logical_monitor_configs: Vec<LogicalMonitorConfiguration>,
178 _properties: HashMap<String, OwnedValue>,
179 ) -> fdo::Result<()> {
180 let current_conf = self.ipc_outputs.lock().unwrap();
181 let mut new_conf = HashMap::new();
182 for requested_config in logical_monitor_configs {
183 if requested_config.monitors.len() > 1 {
184 return Err(zbus::fdo::Error::Failed(
185 "Mirroring is not yet supported".to_owned(),
186 ));
187 }
188 for (connector, mode, _props) in requested_config.monitors {
189 if !current_conf.values().any(|o| o.name == connector) {
190 return Err(zbus::fdo::Error::Failed(format!(
191 "Connector '{connector}' not found",
192 )));
193 }
194 new_conf.insert(
195 connector.clone(),
196 Some(niri_config::Output {
197 off: false,
198 name: connector,
199 scale: Some(niri_config::FloatOrInt(requested_config.scale)),
200 transform: match requested_config.transform {
201 0 => niri_ipc::Transform::Normal,
202 1 => niri_ipc::Transform::_90,
203 2 => niri_ipc::Transform::_180,
204 3 => niri_ipc::Transform::_270,
205 4 => niri_ipc::Transform::Flipped,
206 5 => niri_ipc::Transform::Flipped90,
207 6 => niri_ipc::Transform::Flipped180,
208 7 => niri_ipc::Transform::Flipped270,
209 x => {
210 return Err(zbus::fdo::Error::Failed(format!(
211 "Unknown transform {x}",
212 )))
213 }
214 },
215 position: Some(niri_config::Position {
216 x: requested_config.x,
217 y: requested_config.y,
218 }),
219 mode: Some(niri_config::output::Mode {
220 custom: false,
221 mode: niri_ipc::ConfiguredMode::from_str(&mode).map_err(|e| {
222 zbus::fdo::Error::Failed(format!(
223 "Could not parse mode '{mode}': {e}"
224 ))
225 })?,
226 }),
227 // FIXME: VRR
228 ..Default::default()
229 }),
230 );
231 }
232 }
233 if new_conf.is_empty() {
234 return Err(zbus::fdo::Error::Failed(
235 "At least one output must be enabled".to_owned(),
236 ));
237 }
238 for output in current_conf.values() {
239 if !new_conf.contains_key(&output.name) {
240 new_conf.insert(output.name.clone(), None);
241 }
242 }
243 if method == 0 {
244 // 0 means "verify", so don't actually apply here
245 return Ok(());
246 }
247 if let Err(err) = self.to_niri.send(new_conf) {
248 warn!("error sending message to niri: {err:?}");
249 return Err(fdo::Error::Failed("internal error".to_owned()));
250 }
251 Ok(())
252 }
253
254 #[zbus(signal)]
255 pub async fn monitors_changed(ctxt: &SignalEmitter<'_>) -> zbus::Result<()>;
256
257 #[zbus(property)]
258 fn power_save_mode(&self) -> i32 {
259 -1
260 }
261
262 #[zbus(property)]
263 fn set_power_save_mode(&self, _mode: i32) -> zbus::Result<()> {
264 Err(zbus::Error::Unsupported)
265 }
266
267 #[zbus(property)]
268 fn panel_orientation_managed(&self) -> bool {
269 false
270 }
271
272 #[zbus(property)]
273 fn apply_monitors_config_allowed(&self) -> bool {
274 true
275 }
276
277 #[zbus(property)]
278 fn night_light_supported(&self) -> bool {
279 false
280 }
281}
282
283impl DisplayConfig {
284 pub fn new(
285 to_niri: calloop::channel::Sender<HashMap<String, Option<niri_config::Output>>>,
286 ipc_outputs: Arc<Mutex<IpcOutputMap>>,
287 ) -> Self {
288 Self {
289 to_niri,
290 ipc_outputs,
291 }
292 }
293}
294
295impl Start for DisplayConfig {
296 fn start(self, monitor: bool) -> anyhow::Result<zbus::blocking::Connection> {
297 let conn = zbus::blocking::Connection::session()?;
298 conn.object_server()
299 .at("/org/gnome/Mutter/DisplayConfig", self)?;
300 request_name(&conn, "org.gnome.Mutter.DisplayConfig", monitor)?;
301
302 Ok(conn)
303 }
304}
305
306// Adapted from Mutter.
307fn make_display_name(output: &niri_ipc::Output, is_laptop_panel: bool) -> String {
308 if is_laptop_panel {
309 return String::from("Built-in display");
310 }
311
312 let make = &output.make;
313 let model = &output.model;
314 if let Some(diagonal) = output.physical_size.map(|(width_mm, height_mm)| {
315 let diagonal = f64::hypot(f64::from(width_mm), f64::from(height_mm)) / 25.4;
316 format_diagonal(diagonal)
317 }) {
318 format!("{make} {diagonal}")
319 } else if model != "Unknown" {
320 format!("{make} {model}")
321 } else {
322 make.clone()
323 }
324}
325
326fn format_diagonal(diagonal_inches: f64) -> String {
327 let known = [12.1, 13.3, 15.6];
328 if let Some(d) = known.iter().find(|d| (*d - diagonal_inches).abs() < 0.1) {
329 format!("{d:.1}″")
330 } else {
331 format!("{}″", diagonal_inches.round() as u32)
332 }
333}
334
335#[cfg(test)]
336mod tests {
337 use insta::assert_snapshot;
338
339 use super::*;
340
341 #[test]
342 fn test_format_diagonal() {
343 assert_snapshot!(format_diagonal(12.11), @"12.1″");
344 assert_snapshot!(format_diagonal(13.28), @"13.3″");
345 assert_snapshot!(format_diagonal(15.6), @"15.6″");
346 assert_snapshot!(format_diagonal(23.2), @"23″");
347 assert_snapshot!(format_diagonal(24.8), @"25″");
348 }
349}