forge
Explore
Log in

Don't you dare go Hollow

Add support for custom modes and modelines. (#2479)

Browse files at this commit

6a2c6261df130cccb5262eddf71d40b2fffcf8f9UnverifiedMerlijn and Christian Meissl, Ivan MolodetskikhParent: e6f3c53
* Implement custom modes and modelines

Co-authored-by: ToxicMushroom <32853531+ToxicMushroom@users.noreply.github.com>

* fixes

* refactor mode and modeline kdl parsers.

* add IPC parse checks

* refactor: address feedback

* fix: add missing > 0 refresh rate check

* move things around

* fixes

* wiki fixes

---------
docs/wiki/Configuration:-Outputs.mdmodified+40 -0
@@ -27,6 +27,10 @@ output "eDP-1" {
2727 layout {
2828 // ...layout settings for eDP-1...
2929 }
30+
31+ // Custom modes. Caution: may damage your display.
32+ // mode custom=true "1920x1080@100"
33+ // modeline 173.00 1920 2048 2248 2576 1080 1083 1088 1120 "-hsync" "+vsync"
3034 }
3135
3236 output "HDMI-A-1" {
@@ -86,6 +90,42 @@ output "eDP-1" {
8690 }
8791 ```
8892
93+#### `mode custom=true`
94+
95+<sup>Since: next release</sup>
96+
97+You can configure a custom mode (not offered by the monitor) by setting `custom=true`.
98+In this case, the refresh rate is mandatory.
99+
100+> [!CAUTION]
101+> Custom modes may damage your monitor, especially if it's a CRT.
102+> Follow the maximum supported limits in your monitor's instructions.
103+
104+```kdl
105+// Use a custom mode for this display.
106+output "HDMI-A-1" {
107+ mode custom=true "2560x1440@143.912"
108+}
109+```
110+
111+### `modeline`
112+
113+<sup>Since: next release</sup>
114+
115+Directly configures the monitor's mode via a modeline, overriding any configured `mode`.
116+The modeline can be calculated via utilities such as [cvt](https://man.archlinux.org/man/cvt.1.en) or [gtf](https://man.archlinux.org/man/gtf.1.en).
117+
118+> [!CAUTION]
119+> Out of spec modelines may damage your monitor, especially if it's a CRT.
120+> Follow the maximum supported limits in your monitor's instructions.
121+
122+```kdl
123+// Use a modeline for this display.
124+output "eDP-3" {
125+ modeline 173.00 1920 2048 2248 2576 1080 1083 1088 1120 "-hsync" "+vsync"
126+}
127+```
128+
89129 ### `scale`
90130
91131 Set the scale of the monitor.
niri-config/src/lib.rsmodified+73 -6
@@ -663,6 +663,14 @@ mod tests {
663663 }
664664 }
665665
666+ output "eDP-2" {
667+ mode custom=true "1920x1080@144"
668+ }
669+
670+ output "eDP-3" {
671+ modeline 173.00 1920 2048 2248 2576 1080 1083 1088 1120 "-hsync" "+vsync"
672+ }
673+
666674 layout {
667675 focus-ring {
668676 width 5
@@ -1035,14 +1043,18 @@ mod tests {
10351043 },
10361044 ),
10371045 mode: Some(
1038- ConfiguredMode {
1039- width: 1920,
1040- height: 1080,
1041- refresh: Some(
1042- 144.0,
1043- ),
1046+ Mode {
1047+ custom: false,
1048+ mode: ConfiguredMode {
1049+ width: 1920,
1050+ height: 1080,
1051+ refresh: Some(
1052+ 144.0,
1053+ ),
1054+ },
10441055 },
10451056 ),
1057+ modeline: None,
10461058 variable_refresh_rate: Some(
10471059 Vrr {
10481060 on_demand: true,
@@ -1069,6 +1081,61 @@ mod tests {
10691081 ),
10701082 layout: None,
10711083 },
1084+ Output {
1085+ off: false,
1086+ name: "eDP-2",
1087+ scale: None,
1088+ transform: Normal,
1089+ position: None,
1090+ mode: Some(
1091+ Mode {
1092+ custom: true,
1093+ mode: ConfiguredMode {
1094+ width: 1920,
1095+ height: 1080,
1096+ refresh: Some(
1097+ 144.0,
1098+ ),
1099+ },
1100+ },
1101+ ),
1102+ modeline: None,
1103+ variable_refresh_rate: None,
1104+ focus_at_startup: false,
1105+ background_color: None,
1106+ backdrop_color: None,
1107+ hot_corners: None,
1108+ layout: None,
1109+ },
1110+ Output {
1111+ off: false,
1112+ name: "eDP-3",
1113+ scale: None,
1114+ transform: Normal,
1115+ position: None,
1116+ mode: None,
1117+ modeline: Some(
1118+ Modeline {
1119+ clock: 173.0,
1120+ hdisplay: 1920,
1121+ hsync_start: 2048,
1122+ hsync_end: 2248,
1123+ htotal: 2576,
1124+ vdisplay: 1080,
1125+ vsync_start: 1083,
1126+ vsync_end: 1088,
1127+ vtotal: 1120,
1128+ hsync_polarity: NHSync,
1129+ vsync_polarity: PVSync,
1130+ },
1131+ ),
1132+ variable_refresh_rate: None,
1133+ focus_at_startup: false,
1134+ background_color: None,
1135+ backdrop_color: None,
1136+ hot_corners: None,
1137+ layout: None,
1138+ },
10721139 ],
10731140 ),
10741141 spawn_at_startup: [
niri-config/src/output.rsmodified+283 -3
@@ -1,4 +1,11 @@
1-use niri_ipc::{ConfiguredMode, Transform};
1+use std::str::FromStr;
2+
3+use knuffel::ast::SpannedNode;
4+use knuffel::decode::Context;
5+use knuffel::errors::DecodeError;
6+use knuffel::traits::ErrorSpan;
7+use knuffel::Decode;
8+use niri_ipc::{ConfiguredMode, HSyncPolarity, Transform, VSyncPolarity};
29
310 use crate::gestures::HotCorners;
411 use crate::{Color, FloatOrInt, LayoutPart};
@@ -6,6 +13,40 @@ use crate::{Color, FloatOrInt, LayoutPart};
613 #[derive(Debug, Default, Clone, PartialEq)]
714 pub struct Outputs(pub Vec<Output>);
815
16+#[derive(Debug, Clone, Copy, PartialEq)]
17+pub struct Mode {
18+ pub custom: bool,
19+ pub mode: ConfiguredMode,
20+}
21+
22+#[derive(Debug, Clone, Copy, PartialEq)]
23+pub struct Modeline {
24+ /// The rate at which pixels are drawn in MHz.
25+ pub clock: f64,
26+ /// Horizontal active pixels.
27+ pub hdisplay: u16,
28+ /// Horizontal sync pulse start position in pixels.
29+ pub hsync_start: u16,
30+ /// Horizontal sync pulse end position in pixels.
31+ pub hsync_end: u16,
32+ /// Total horizontal number of pixels before resetting the horizontal drawing position to
33+ /// zero.
34+ pub htotal: u16,
35+
36+ /// Vertical active pixels.
37+ pub vdisplay: u16,
38+ /// Vertical sync pulse start position in pixels.
39+ pub vsync_start: u16,
40+ /// Vertical sync pulse end position in pixels.
41+ pub vsync_end: u16,
42+ /// Total vertical number of pixels before resetting the vertical drawing position to zero.
43+ pub vtotal: u16,
44+ /// Horizontal sync polarity: "+hsync" or "-hsync".
45+ pub hsync_polarity: niri_ipc::HSyncPolarity,
46+ /// Vertical sync polarity: "+vsync" or "-vsync".
47+ pub vsync_polarity: niri_ipc::VSyncPolarity,
48+}
49+
950 #[derive(knuffel::Decode, Debug, Clone, PartialEq)]
1051 pub struct Output {
1152 #[knuffel(child)]
@@ -18,8 +59,10 @@ pub struct Output {
1859 pub transform: Transform,
1960 #[knuffel(child)]
2061 pub position: Option<Position>,
21- #[knuffel(child, unwrap(argument, str))]
22- pub mode: Option<ConfiguredMode>,
62+ #[knuffel(child)]
63+ pub mode: Option<Mode>,
64+ #[knuffel(child)]
65+ pub modeline: Option<Modeline>,
2366 #[knuffel(child)]
2467 pub variable_refresh_rate: Option<Vrr>,
2568 #[knuffel(child)]
@@ -59,6 +102,7 @@ impl Default for Output {
59102 transform: Transform::Normal,
60103 position: None,
61104 mode: None,
105+ modeline: None,
62106 variable_refresh_rate: None,
63107 background_color: None,
64108 backdrop_color: None,
@@ -213,6 +257,242 @@ impl OutputName {
213257 }
214258 }
215259
260+impl<S: ErrorSpan> knuffel::Decode<S> for Mode {
261+ fn decode_node(node: &SpannedNode<S>, ctx: &mut Context<S>) -> Result<Self, DecodeError<S>> {
262+ if let Some(type_name) = &node.type_name {
263+ ctx.emit_error(DecodeError::unexpected(
264+ type_name,
265+ "type name",
266+ "no type name expected for this node",
267+ ));
268+ }
269+
270+ for child in node.children() {
271+ ctx.emit_error(DecodeError::unexpected(
272+ child,
273+ "node",
274+ format!("unexpected node `{}`", child.node_name.escape_default()),
275+ ));
276+ }
277+
278+ let mut custom: Option<bool> = None;
279+ for (name, val) in &node.properties {
280+ match &***name {
281+ "custom" => {
282+ if custom.is_some() {
283+ ctx.emit_error(DecodeError::unexpected(
284+ name,
285+ "property",
286+ "unexpected duplicate property `custom`",
287+ ))
288+ }
289+ custom = Some(knuffel::traits::DecodeScalar::decode(val, ctx)?)
290+ }
291+ name_str => ctx.emit_error(DecodeError::unexpected(
292+ node,
293+ "property",
294+ format!("unexpected property `{}`", name_str.escape_default()),
295+ )),
296+ }
297+ }
298+ let custom = custom.unwrap_or(false);
299+
300+ let mut arguments = node.arguments.iter();
301+ let mode = if let Some(mode_str) = arguments.next() {
302+ let temp_mode: String = knuffel::traits::DecodeScalar::decode(mode_str, ctx)?;
303+
304+ let res = ConfiguredMode::from_str(temp_mode.as_str()).and_then(|mode| {
305+ if custom {
306+ if mode.refresh.is_none() {
307+ return Err("no refresh rate found; required for custom mode");
308+ } else if let Some(refresh) = mode.refresh {
309+ if refresh <= 0. {
310+ return Err("custom mode refresh rate must be > 0");
311+ }
312+ }
313+ }
314+ Ok(mode)
315+ });
316+ res.map_err(|err_msg| DecodeError::conversion(&mode_str.literal, err_msg))?
317+ } else {
318+ return Err(DecodeError::missing(node, "argument `mode` is required"));
319+ };
320+
321+ if let Some(surplus) = arguments.next() {
322+ ctx.emit_error(DecodeError::unexpected(
323+ &surplus.literal,
324+ "argument",
325+ "unexpected argument",
326+ ))
327+ }
328+
329+ Ok(Mode { custom, mode })
330+ }
331+}
332+
333+macro_rules! ensure {
334+ ($cond:expr, $ctx:expr, $span:expr, $fmt:literal $($arg:tt)* ) => {
335+ if !$cond {
336+ $ctx.emit_error(DecodeError::Conversion {
337+ source: format!($fmt $($arg)*).into(),
338+ span: $span.literal.span().clone()
339+ });
340+ }
341+ };
342+}
343+
344+impl<S: ErrorSpan> Decode<S> for Modeline {
345+ fn decode_node(node: &SpannedNode<S>, ctx: &mut Context<S>) -> Result<Self, DecodeError<S>> {
346+ if let Some(type_name) = &node.type_name {
347+ ctx.emit_error(DecodeError::unexpected(
348+ type_name,
349+ "type name",
350+ "no type name expected for this node",
351+ ));
352+ }
353+
354+ for child in node.children() {
355+ ctx.emit_error(DecodeError::unexpected(
356+ child,
357+ "node",
358+ format!("unexpected node `{}`", child.node_name.escape_default()),
359+ ));
360+ }
361+
362+ for span in node.properties.keys() {
363+ ctx.emit_error(DecodeError::unexpected(
364+ span,
365+ "node",
366+ format!("unexpected node `{}`", span.escape_default()),
367+ ));
368+ }
369+
370+ let mut arguments = node.arguments.iter();
371+
372+ macro_rules! m_required {
373+ // This could be one identifier if macro_metavar_expr_concat stabilizes
374+ ($field:ident, $value_field:ident) => {
375+ let $value_field = arguments.next().ok_or_else(|| {
376+ DecodeError::missing(node, format!("missing {} argument", stringify!($value)))
377+ })?;
378+ let $field = knuffel::traits::DecodeScalar::decode($value_field, ctx)?;
379+ };
380+ }
381+
382+ m_required!(clock, clock_value);
383+ m_required!(hdisplay, hdisplay_value);
384+ m_required!(hsync_start, hsync_start_value);
385+ m_required!(hsync_end, hsync_end_value);
386+ m_required!(htotal, htotal_value);
387+ m_required!(vdisplay, vdisplay_value);
388+ m_required!(vsync_start, vsync_start_value);
389+ m_required!(vsync_end, vsync_end_value);
390+ m_required!(vtotal, vtotal_value);
391+ m_required!(hsync_polarity, hsync_polarity_value);
392+ let hsync_polarity =
393+ HSyncPolarity::from_str(String::as_str(&hsync_polarity)).map_err(|msg| {
394+ DecodeError::Conversion {
395+ span: hsync_polarity_value.literal.span().clone(),
396+ source: msg.into(),
397+ }
398+ })?;
399+
400+ m_required!(vsync_polarity, vsync_polarity_value);
401+ let vsync_polarity =
402+ VSyncPolarity::from_str(String::as_str(&vsync_polarity)).map_err(|msg| {
403+ DecodeError::Conversion {
404+ span: vsync_polarity_value.literal.span().clone(),
405+ source: msg.into(),
406+ }
407+ })?;
408+
409+ ensure!(
410+ hdisplay < hsync_start,
411+ ctx,
412+ hdisplay_value,
413+ "hdisplay {} must be < hsync_start {}",
414+ hdisplay,
415+ hsync_start
416+ );
417+ ensure!(
418+ hsync_start < hsync_end,
419+ ctx,
420+ hsync_start_value,
421+ "hsync_start {} must be < hsync_end {}",
422+ hsync_start,
423+ hsync_end,
424+ );
425+ ensure!(
426+ hsync_end < htotal,
427+ ctx,
428+ hsync_end_value,
429+ "hsync_end {} must be < htotal {}",
430+ hsync_end,
431+ htotal,
432+ );
433+ ensure!(
434+ 0u16 < htotal,
435+ ctx,
436+ htotal_value,
437+ "htotal {} must be > 0",
438+ htotal
439+ );
440+ ensure!(
441+ vdisplay < vsync_start,
442+ ctx,
443+ vdisplay_value,
444+ "vdisplay {} must be < vsync_start {}",
445+ vdisplay,
446+ vsync_start,
447+ );
448+ ensure!(
449+ vsync_start < vsync_end,
450+ ctx,
451+ vsync_start_value,
452+ "vsync_start {} must be < vsync_end {}",
453+ vsync_start,
454+ vsync_end,
455+ );
456+ ensure!(
457+ vsync_end < vtotal,
458+ ctx,
459+ vsync_end_value,
460+ "vsync_end {} must be < vtotal {}",
461+ vsync_end,
462+ vtotal,
463+ );
464+ ensure!(
465+ 0u16 < vtotal,
466+ ctx,
467+ vtotal_value,
468+ "vtotal {} must be > 0",
469+ vtotal
470+ );
471+
472+ if let Some(extra) = arguments.next() {
473+ ctx.emit_error(DecodeError::unexpected(
474+ &extra.literal,
475+ "argument",
476+ "unexpected argument, all possible arguments were already provided",
477+ ))
478+ }
479+
480+ Ok(Modeline {
481+ clock,
482+ hdisplay,
483+ hsync_start,
484+ hsync_end,
485+ htotal,
486+ vdisplay,
487+ vsync_start,
488+ vsync_end,
489+ vtotal,
490+ hsync_polarity,
491+ vsync_polarity,
492+ })
493+ }
494+}
495+
216496 #[cfg(test)]
217497 mod tests {
218498 use insta::assert_debug_snapshot;
niri-ipc/src/lib.rsmodified+172 -0
@@ -1000,6 +1000,51 @@ pub enum OutputAction {
10001000 #[cfg_attr(feature = "clap", arg())]
10011001 mode: ModeToSet,
10021002 },
1003+ /// Set a custom output mode.
1004+ CustomMode {
1005+ /// Custom mode to set.
1006+ #[cfg_attr(feature = "clap", arg())]
1007+ mode: ConfiguredMode,
1008+ },
1009+ /// Set a custom VESA CVT modeline.
1010+ #[cfg_attr(feature = "clap", arg())]
1011+ Modeline {
1012+ /// The rate at which pixels are drawn in MHz.
1013+ #[cfg_attr(feature = "clap", arg())]
1014+ clock: f64,
1015+ /// Horizontal active pixels.
1016+ #[cfg_attr(feature = "clap", arg())]
1017+ hdisplay: u16,
1018+ /// Horizontal sync pulse start position in pixels.
1019+ #[cfg_attr(feature = "clap", arg())]
1020+ hsync_start: u16,
1021+ /// Horizontal sync pulse end position in pixels.
1022+ #[cfg_attr(feature = "clap", arg())]
1023+ hsync_end: u16,
1024+ /// Total horizontal number of pixels before resetting the horizontal drawing position to
1025+ /// zero.
1026+ #[cfg_attr(feature = "clap", arg())]
1027+ htotal: u16,
1028+
1029+ /// Vertical active pixels.
1030+ #[cfg_attr(feature = "clap", arg())]
1031+ vdisplay: u16,
1032+ /// Vertical sync pulse start position in pixels.
1033+ #[cfg_attr(feature = "clap", arg())]
1034+ vsync_start: u16,
1035+ /// Vertical sync pulse end position in pixels.
1036+ #[cfg_attr(feature = "clap", arg())]
1037+ vsync_end: u16,
1038+ /// Total vertical number of pixels before resetting the vertical drawing position to zero.
1039+ #[cfg_attr(feature = "clap", arg())]
1040+ vtotal: u16,
1041+ /// Horizontal sync polarity: "+hsync" or "-hsync".
1042+ #[cfg_attr(feature = "clap", arg(allow_hyphen_values = true))]
1043+ hsync_polarity: HSyncPolarity,
1044+ /// Vertical sync polarity: "+vsync" or "-vsync".
1045+ #[cfg_attr(feature = "clap", arg(allow_hyphen_values = true))]
1046+ vsync_polarity: VSyncPolarity,
1047+ },
10031048 /// Set the output scale.
10041049 Scale {
10051050 /// Scale factor to set, or "auto" for automatic selection.
@@ -1048,6 +1093,26 @@ pub struct ConfiguredMode {
10481093 pub refresh: Option<f64>,
10491094 }
10501095
1096+/// Modeline horizontal syncing polarity.
1097+#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1098+#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1099+pub enum HSyncPolarity {
1100+ /// Positive polarity.
1101+ PHSync,
1102+ /// Negative polarity.
1103+ NHSync,
1104+}
1105+
1106+/// Modeline vertical syncing polarity.
1107+#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1108+#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1109+pub enum VSyncPolarity {
1110+ /// Positive polarity.
1111+ PVSync,
1112+ /// Negative polarity.
1113+ NVSync,
1114+}
1115+
10511116 /// Output scale to set.
10521117 #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
10531118 #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
@@ -1125,6 +1190,8 @@ pub struct Output {
11251190 ///
11261191 /// `None` if the output is disabled.
11271192 pub current_mode: Option<usize>,
1193+ /// Whether the current_mode is a custom mode.
1194+ pub is_custom_mode: bool,
11281195 /// Whether the output supports variable refresh rate.
11291196 pub vrr_supported: bool,
11301197 /// Whether variable refresh rate is enabled on the output.
@@ -1680,6 +1747,30 @@ impl FromStr for ConfiguredMode {
16801747 }
16811748 }
16821749
1750+impl FromStr for HSyncPolarity {
1751+ type Err = &'static str;
1752+
1753+ fn from_str(s: &str) -> Result<Self, Self::Err> {
1754+ match s {
1755+ "+hsync" => Ok(Self::PHSync),
1756+ "-hsync" => Ok(Self::NHSync),
1757+ _ => Err(r#"invalid horizontal sync polarity, can be "+hsync" or "-hsync"#),
1758+ }
1759+ }
1760+}
1761+
1762+impl FromStr for VSyncPolarity {
1763+ type Err = &'static str;
1764+
1765+ fn from_str(s: &str) -> Result<Self, Self::Err> {
1766+ match s {
1767+ "+vsync" => Ok(Self::PVSync),
1768+ "-vsync" => Ok(Self::NVSync),
1769+ _ => Err(r#"invalid vertical sync polarity, can be "+vsync" or "-vsync"#),
1770+ }
1771+ }
1772+}
1773+
16831774 impl FromStr for ScaleToSet {
16841775 type Err = &'static str;
16851776
@@ -1693,6 +1784,87 @@ impl FromStr for ScaleToSet {
16931784 }
16941785 }
16951786
1787+macro_rules! ensure {
1788+ ($cond:expr, $fmt:literal $($arg:tt)* ) => {
1789+ if !$cond {
1790+ return Err(format!($fmt $($arg)*));
1791+ }
1792+ };
1793+}
1794+
1795+impl OutputAction {
1796+ /// Validates some required constraints on the modeline and custom mode.
1797+ pub fn validate(&self) -> Result<(), String> {
1798+ match self {
1799+ OutputAction::Modeline {
1800+ hdisplay,
1801+ hsync_start,
1802+ hsync_end,
1803+ htotal,
1804+ vdisplay,
1805+ vsync_start,
1806+ vsync_end,
1807+ vtotal,
1808+ ..
1809+ } => {
1810+ ensure!(
1811+ hdisplay < hsync_start,
1812+ "hdisplay {} must be < hsync_start {}",
1813+ hdisplay,
1814+ hsync_start
1815+ );
1816+ ensure!(
1817+ hsync_start < hsync_end,
1818+ "hsync_start {} must be < hsync_end {}",
1819+ hsync_start,
1820+ hsync_end
1821+ );
1822+ ensure!(
1823+ hsync_end < htotal,
1824+ "hsync_end {} must be < htotal {}",
1825+ hsync_end,
1826+ htotal
1827+ );
1828+ ensure!(0 < *htotal, "htotal {} must be > 0", htotal);
1829+ ensure!(
1830+ vdisplay < vsync_start,
1831+ "vdisplay {} must be < vsync_start {}",
1832+ vdisplay,
1833+ vsync_start
1834+ );
1835+ ensure!(
1836+ vsync_start < vsync_end,
1837+ "vsync_start {} must be < vsync_end {}",
1838+ vsync_start,
1839+ vsync_end
1840+ );
1841+ ensure!(
1842+ vsync_end < vtotal,
1843+ "vsync_end {} must be < vtotal {}",
1844+ vsync_end,
1845+ vtotal
1846+ );
1847+ ensure!(0 < *vtotal, "vtotal {} must be > 0", vtotal);
1848+ Ok(())
1849+ }
1850+ OutputAction::CustomMode {
1851+ mode: ConfiguredMode { refresh, .. },
1852+ } => {
1853+ if refresh.is_none() {
1854+ return Err("refresh rate is required for custom modes".to_string());
1855+ }
1856+ if let Some(refresh) = refresh {
1857+ if *refresh <= 0. {
1858+ return Err(format!("custom mode refresh rate {refresh} must be > 0"));
1859+ }
1860+ }
1861+ Ok(())
1862+ }
1863+ _ => Ok(()),
1864+ }
1865+ }
1866+}
1867+
16961868 #[cfg(test)]
16971869 mod tests {
16981870 use super::*;
src/backend/headless.rsmodified+1 -0
@@ -105,6 +105,7 @@ impl Headless {
105105 is_preferred: true,
106106 }],
107107 current_mode: Some(0),
108+ is_custom_mode: true,
108109 vrr_supported: false,
109110 vrr_enabled: false,
110111 logical: Some(logical_output(&output)),
src/backend/tty.rsmodified+379 -15
@@ -12,8 +12,11 @@ use std::{io, mem};
1212
1313 use anyhow::{anyhow, bail, ensure, Context};
1414 use bytemuck::cast_slice_mut;
15+use drm_ffi::drm_mode_modeinfo;
1516 use libc::dev_t;
17+use niri_config::output::Modeline;
1618 use niri_config::{Config, OutputName};
19+use niri_ipc::{HSyncPolarity, VSyncPolarity};
1720 use smithay::backend::allocator::dmabuf::Dmabuf;
1821 use smithay::backend::allocator::format::FormatSet;
1922 use smithay::backend::allocator::gbm::{GbmAllocator, GbmBufferFlags, GbmDevice};
@@ -907,21 +910,35 @@ impl Tty {
907910 trace!("{m:?}");
908911 }
909912
910- let (mode, fallback) =
911- pick_mode(&connector, config.mode).ok_or_else(|| anyhow!("no mode"))?;
913+ let mut mode = None;
914+ if let Some(modeline) = &config.modeline {
915+ match calculate_drm_mode_from_modeline(modeline) {
916+ Ok(x) => mode = Some(x),
917+ Err(err) => {
918+ warn!("invalid custom modeline; falling back to advertised modes: {err:?}");
919+ }
920+ }
921+ }
922+
923+ let (mode, fallback) = match mode {
924+ Some(x) => (x, false),
925+ None => pick_mode(&connector, config.mode).ok_or_else(|| anyhow!("no mode"))?,
926+ };
927+
912928 if fallback {
913929 let target = config.mode.unwrap();
914930 warn!(
915931 "configured mode {}x{}{} could not be found, falling back to preferred",
916- target.width,
917- target.height,
918- if let Some(refresh) = target.refresh {
932+ target.mode.width,
933+ target.mode.height,
934+ if let Some(refresh) = target.mode.refresh {
919935 format!("@{refresh}")
920936 } else {
921937 String::new()
922938 },
923939 );
924940 }
941+
925942 debug!("picking mode: {mode:?}");
926943
927944 if let Ok(props) = ConnectorProperties::try_new(&device.drm, connector.handle()) {
@@ -1711,8 +1728,9 @@ impl Tty {
17111728 let surface = device.surfaces.get(&crtc);
17121729 let current_crtc_mode = surface.map(|surface| surface.compositor.pending_mode());
17131730 let mut current_mode = None;
1731+ let mut is_custom_mode = false;
17141732
1715- let modes = connector
1733+ let mut modes: Vec<niri_ipc::Mode> = connector
17161734 .modes()
17171735 .iter()
17181736 .filter(|m| !m.flags().contains(ModeFlags::INTERLACE))
@@ -1732,6 +1750,21 @@ impl Tty {
17321750 .collect();
17331751
17341752 if let Some(crtc_mode) = current_crtc_mode {
1753+ // Custom mode
1754+ if crtc_mode.mode_type().contains(ModeTypeFlags::USERDEF) {
1755+ modes.insert(
1756+ 0,
1757+ niri_ipc::Mode {
1758+ width: crtc_mode.size().0,
1759+ height: crtc_mode.size().1,
1760+ refresh_rate: Mode::from(crtc_mode).refresh as u32,
1761+ is_preferred: false,
1762+ },
1763+ );
1764+ current_mode = Some(0);
1765+ is_custom_mode = true;
1766+ }
1767+
17351768 if current_mode.is_none() {
17361769 if crtc_mode.flags().contains(ModeFlags::INTERLACE) {
17371770 warn!("connector mode list missing current mode (interlaced)");
@@ -1776,6 +1809,7 @@ impl Tty {
17761809 physical_size,
17771810 modes,
17781811 current_mode,
1812+ is_custom_mode,
17791813 vrr_supported,
17801814 vrr_enabled,
17811815 logical,
@@ -1962,9 +1996,29 @@ impl Tty {
19621996 continue;
19631997 };
19641998
1965- let Some((mode, fallback)) = pick_mode(connector, config.mode) else {
1966- warn!("couldn't pick mode for enabled connector");
1967- continue;
1999+ let mut mode = None;
2000+ if let Some(modeline) = &config.modeline {
2001+ match calculate_drm_mode_from_modeline(modeline) {
2002+ Ok(x) => mode = Some(x),
2003+ Err(err) => {
2004+ warn!(
2005+ "output {:?}: invalid custom modeline; \
2006+ falling back to advertised modes: {err:?}",
2007+ surface.name.connector
2008+ );
2009+ }
2010+ }
2011+ }
2012+
2013+ let (mode, fallback) = match mode {
2014+ Some(x) => (x, false),
2015+ None => match pick_mode(connector, config.mode) {
2016+ Some(result) => result,
2017+ None => {
2018+ warn!("couldn't pick mode for enabled connector");
2019+ continue;
2020+ }
2021+ },
19682022 };
19692023
19702024 let change_mode = surface.compositor.pending_mode() != mode;
@@ -2017,9 +2071,9 @@ impl Tty {
20172071 "output {:?}: configured mode {}x{}{} could not be found, \
20182072 falling back to preferred",
20192073 surface.name.connector,
2020- target.width,
2021- target.height,
2022- if let Some(refresh) = target.refresh {
2074+ target.mode.width,
2075+ target.mode.height,
2076+ if let Some(refresh) = target.mode.refresh {
20232077 format!("@{refresh}")
20242078 } else {
20252079 String::new()
@@ -2517,18 +2571,188 @@ fn queue_estimated_vblank_timer(
25172571 output_state.redraw_state = RedrawState::WaitingForEstimatedVBlank(token);
25182572 }
25192573
2574+pub fn calculate_drm_mode_from_modeline(modeline: &Modeline) -> anyhow::Result<DrmMode> {
2575+ ensure!(
2576+ modeline.hdisplay < modeline.hsync_start,
2577+ "hdisplay {} must be < hsync_start {}",
2578+ modeline.hdisplay,
2579+ modeline.hsync_start
2580+ );
2581+ ensure!(
2582+ modeline.hsync_start < modeline.hsync_end,
2583+ "hsync_start {} must be < hsync_end {}",
2584+ modeline.hsync_start,
2585+ modeline.hsync_end
2586+ );
2587+ ensure!(
2588+ modeline.hsync_end < modeline.htotal,
2589+ "hsync_end {} must be < htotal {}",
2590+ modeline.hsync_end,
2591+ modeline.htotal
2592+ );
2593+ ensure!(
2594+ modeline.vdisplay < modeline.vsync_start,
2595+ "vdisplay {} must be < vsync_start {}",
2596+ modeline.vdisplay,
2597+ modeline.vsync_start
2598+ );
2599+ ensure!(
2600+ modeline.vsync_start < modeline.vsync_end,
2601+ "vsync_start {} must be < vsync_end {}",
2602+ modeline.vsync_start,
2603+ modeline.vsync_end
2604+ );
2605+ ensure!(
2606+ modeline.vsync_end < modeline.vtotal,
2607+ "vsync_end {} must be < vtotal {}",
2608+ modeline.vsync_end,
2609+ modeline.vtotal
2610+ );
2611+
2612+ let pixel_clock_kilo_hertz = modeline.clock * 1000.0;
2613+ // Calculated as documented in the CVT 1.2 standard:
2614+ // https://app.box.com/s/vcocw3z73ta09txiskj7cnk6289j356b/file/93518784646
2615+ let vrefresh_hertz = (pixel_clock_kilo_hertz * 1000.0)
2616+ / (modeline.htotal as u64 * modeline.vtotal as u64) as f64;
2617+ ensure!(
2618+ vrefresh_hertz.is_finite(),
2619+ "calculated refresh rate is not finite"
2620+ );
2621+ let vrefresh_rounded = vrefresh_hertz.round() as u32;
2622+
2623+ let flags = match modeline.hsync_polarity {
2624+ HSyncPolarity::PHSync => ModeFlags::PHSYNC,
2625+ HSyncPolarity::NHSync => ModeFlags::NHSYNC,
2626+ } | match modeline.vsync_polarity {
2627+ VSyncPolarity::PVSync => ModeFlags::PVSYNC,
2628+ VSyncPolarity::NVSync => ModeFlags::NVSYNC,
2629+ };
2630+
2631+ let mode_name = format!(
2632+ "{}x{}@{:.2}",
2633+ modeline.hdisplay, modeline.vdisplay, vrefresh_hertz
2634+ );
2635+ let name = modeinfo_name_slice_from_string(&mode_name);
2636+
2637+ // https://www.kernel.org/doc/html/v6.17/gpu/drm-uapi.html#c.drm_mode_modeinfo
2638+ Ok(DrmMode::from(drm_mode_modeinfo {
2639+ clock: pixel_clock_kilo_hertz.round() as u32,
2640+ hdisplay: modeline.hdisplay,
2641+ hsync_start: modeline.hsync_start,
2642+ hsync_end: modeline.hsync_end,
2643+ htotal: modeline.htotal,
2644+ vdisplay: modeline.vdisplay,
2645+ vsync_start: modeline.vsync_start,
2646+ vsync_end: modeline.vsync_end,
2647+ vtotal: modeline.vtotal,
2648+ vrefresh: vrefresh_rounded,
2649+ flags: flags.bits(),
2650+ name,
2651+ // Defaults
2652+ type_: drm_ffi::DRM_MODE_TYPE_USERDEF,
2653+ hskew: 0,
2654+ vscan: 0,
2655+ }))
2656+}
2657+
2658+pub fn calculate_mode_cvt(width: u16, height: u16, refresh: f64) -> DrmMode {
2659+ // Cross-checked with sway's implementation:
2660+ // https://gitlab.freedesktop.org/wlroots/wlroots/-/blob/22528542970687720556035790212df8d9bb30bb/backend/drm/util.c#L251
2661+
2662+ let options = libdisplay_info::cvt::Options {
2663+ red_blank_ver: libdisplay_info::cvt::ReducedBlankingVersion::None,
2664+ h_pixels: width as i32,
2665+ v_lines: height as i32,
2666+ ip_freq_rqd: refresh,
2667+
2668+ // Defaults
2669+ video_opt: false,
2670+ vblank: 0f64,
2671+ additional_hblank: 0,
2672+ early_vsync_rqd: false,
2673+ int_rqd: false,
2674+ margins_rqd: false,
2675+ };
2676+ let cvt_timing = libdisplay_info::cvt::Timing::compute(options);
2677+
2678+ let hsync_start = width + cvt_timing.h_front_porch as u16;
2679+ let vsync_start = (cvt_timing.v_lines_rnd + cvt_timing.v_front_porch) as u16;
2680+ let hsync_end = hsync_start + cvt_timing.h_sync as u16;
2681+ let vsync_end = vsync_start + cvt_timing.v_sync as u16;
2682+
2683+ let htotal = hsync_end + cvt_timing.h_back_porch as u16;
2684+ let vtotal = vsync_end + cvt_timing.v_back_porch as u16;
2685+
2686+ let clock = f64::round(cvt_timing.act_pixel_freq * 1000f64) as u32;
2687+ let vrefresh = f64::round(cvt_timing.act_frame_rate) as u32;
2688+
2689+ let flags = drm_ffi::DRM_MODE_FLAG_NHSYNC | drm_ffi::DRM_MODE_FLAG_PVSYNC;
2690+
2691+ let mode_name = format!("{width}x{height}@{:.2}", cvt_timing.act_frame_rate);
2692+ let name = modeinfo_name_slice_from_string(&mode_name);
2693+
2694+ let drm_ffi_mode = drm_ffi::drm_sys::drm_mode_modeinfo {
2695+ clock,
2696+
2697+ hdisplay: width,
2698+ hsync_start,
2699+ hsync_end,
2700+ htotal,
2701+
2702+ vdisplay: height,
2703+ vsync_start,
2704+ vsync_end,
2705+ vtotal,
2706+
2707+ vrefresh,
2708+
2709+ flags,
2710+ type_: drm_ffi::DRM_MODE_TYPE_USERDEF,
2711+ name,
2712+
2713+ // Defaults
2714+ hskew: 0,
2715+ vscan: 0,
2716+ };
2717+
2718+ DrmMode::from(drm_ffi_mode)
2719+}
2720+
2721+// Returns a c-string of maximally 31 Rust string chars + null terminator. Excess characters are
2722+// dropped.
2723+fn modeinfo_name_slice_from_string(mode_name: &str) -> [core::ffi::c_char; 32] {
2724+ let mut name: [core::ffi::c_char; 32] = [0; 32];
2725+
2726+ for (a, b) in zip(&mut name[..31], mode_name.as_bytes()) {
2727+ *a = *b as i8;
2728+ }
2729+
2730+ name
2731+}
2732+
25202733 fn pick_mode(
25212734 connector: &connector::Info,
2522- target: Option<niri_ipc::ConfiguredMode>,
2735+ target: Option<niri_config::output::Mode>,
25232736 ) -> Option<(control::Mode, bool)> {
25242737 let mut mode = None;
25252738 let mut fallback = false;
25262739
25272740 if let Some(target) = target {
2528- let refresh = target.refresh.map(|r| (r * 1000.).round() as i32);
2741+ let target_mode = target.mode;
2742+
2743+ if target.custom {
2744+ if let Some(refresh) = target_mode.refresh {
2745+ let custom_mode =
2746+ calculate_mode_cvt(target_mode.width, target_mode.height, refresh);
2747+ return Some((custom_mode, false));
2748+ } else {
2749+ warn!("ignoring custom mode without refresh rate");
2750+ }
2751+ }
25292752
2753+ let refresh = target_mode.refresh.map(|r| (r * 1000.).round() as i32);
25302754 for m in connector.modes() {
2531- if m.size() != (target.width, target.height) {
2755+ if m.size() != (target.mode.width, target.mode.height) {
25322756 continue;
25332757 }
25342758
@@ -2760,3 +2984,143 @@ fn make_output_name(
27602984 serial: info.as_ref().and_then(|info| info.serial()),
27612985 }
27622986 }
2987+
2988+#[cfg(test)]
2989+mod tests {
2990+ use insta::assert_debug_snapshot;
2991+ use niri_config::output::Modeline;
2992+ use niri_ipc::{HSyncPolarity, VSyncPolarity};
2993+
2994+ use crate::backend::tty::{calculate_drm_mode_from_modeline, calculate_mode_cvt};
2995+
2996+ #[test]
2997+ fn test_calculate_drmmode_from_modeline() {
2998+ let modeline1 = Modeline {
2999+ clock: 173.0,
3000+ hdisplay: 1920,
3001+ vdisplay: 1080,
3002+ hsync_start: 2048,
3003+ hsync_end: 2248,
3004+ htotal: 2576,
3005+ vsync_start: 1083,
3006+ vsync_end: 1088,
3007+ vtotal: 1120,
3008+ hsync_polarity: HSyncPolarity::NHSync,
3009+ vsync_polarity: VSyncPolarity::PVSync,
3010+ };
3011+ assert_debug_snapshot!(calculate_drm_mode_from_modeline(&modeline1).unwrap(), @"Mode {
3012+ name: \"1920x1080@59.96\",
3013+ clock: 173000,
3014+ size: (
3015+ 1920,
3016+ 1080,
3017+ ),
3018+ hsync: (
3019+ 2048,
3020+ 2248,
3021+ 2576,
3022+ ),
3023+ vsync: (
3024+ 1083,
3025+ 1088,
3026+ 1120,
3027+ ),
3028+ hskew: 0,
3029+ vscan: 0,
3030+ vrefresh: 60,
3031+ mode_type: ModeTypeFlags(
3032+ USERDEF,
3033+ ),
3034+}");
3035+ let modeline2 = Modeline {
3036+ clock: 452.5,
3037+ hdisplay: 1920,
3038+ vdisplay: 1080,
3039+ hsync_start: 2088,
3040+ hsync_end: 2296,
3041+ htotal: 2672,
3042+ vsync_start: 1083,
3043+ vsync_end: 1088,
3044+ vtotal: 1177,
3045+ hsync_polarity: HSyncPolarity::NHSync,
3046+ vsync_polarity: VSyncPolarity::PVSync,
3047+ };
3048+ assert_debug_snapshot!(calculate_drm_mode_from_modeline(&modeline2).unwrap(), @"Mode {
3049+ name: \"1920x1080@143.88\",
3050+ clock: 452500,
3051+ size: (
3052+ 1920,
3053+ 1080,
3054+ ),
3055+ hsync: (
3056+ 2088,
3057+ 2296,
3058+ 2672,
3059+ ),
3060+ vsync: (
3061+ 1083,
3062+ 1088,
3063+ 1177,
3064+ ),
3065+ hskew: 0,
3066+ vscan: 0,
3067+ vrefresh: 144,
3068+ mode_type: ModeTypeFlags(
3069+ USERDEF,
3070+ ),
3071+}");
3072+ }
3073+
3074+ #[test]
3075+ fn test_calc_cvt() {
3076+ // Crosschecked with other calculators like the cvt commandline utility.
3077+ assert_debug_snapshot!(calculate_mode_cvt(1920, 1080, 60.0), @"Mode {
3078+ name: \"1920x1080@59.96\",
3079+ clock: 173000,
3080+ size: (
3081+ 1920,
3082+ 1080,
3083+ ),
3084+ hsync: (
3085+ 2048,
3086+ 2248,
3087+ 2576,
3088+ ),
3089+ vsync: (
3090+ 1083,
3091+ 1088,
3092+ 1120,
3093+ ),
3094+ hskew: 0,
3095+ vscan: 0,
3096+ vrefresh: 60,
3097+ mode_type: ModeTypeFlags(
3098+ USERDEF,
3099+ ),
3100+}");
3101+ assert_debug_snapshot!(calculate_mode_cvt(1920, 1080, 144.0), @"Mode {
3102+ name: \"1920x1080@143.88\",
3103+ clock: 452500,
3104+ size: (
3105+ 1920,
3106+ 1080,
3107+ ),
3108+ hsync: (
3109+ 2088,
3110+ 2296,
3111+ 2672,
3112+ ),
3113+ vsync: (
3114+ 1083,
3115+ 1088,
3116+ 1177,
3117+ ),
3118+ hskew: 0,
3119+ vscan: 0,
3120+ vrefresh: 144,
3121+ mode_type: ModeTypeFlags(
3122+ USERDEF,
3123+ ),
3124+}");
3125+ }
3126+}
src/backend/winit.rsmodified+1 -0
@@ -83,6 +83,7 @@ impl Winit {
8383 is_preferred: true,
8484 }],
8585 current_mode: Some(0),
86+ is_custom_mode: true,
8687 vrr_supported: false,
8788 vrr_enabled: false,
8889 logical: Some(logical_output(&output)),
src/dbus/mutter_display_config.rsmodified+8 -3
@@ -217,9 +217,14 @@ impl DisplayConfig {
217217 x: requested_config.x,
218218 y: requested_config.y,
219219 }),
220- mode: Some(niri_ipc::ConfiguredMode::from_str(&mode).map_err(|e| {
221- zbus::fdo::Error::Failed(format!("Could not parse mode '{mode}': {e}"))
222- })?),
220+ mode: Some(niri_config::output::Mode {
221+ custom: false,
222+ mode: niri_ipc::ConfiguredMode::from_str(&mode).map_err(|e| {
223+ zbus::fdo::Error::Failed(format!(
224+ "Could not parse mode '{mode}': {e}"
225+ ))
226+ })?,
227+ }),
223228 // FIXME: VRR
224229 ..Default::default()
225230 }),
src/ipc/client.rsmodified+26 -8
@@ -526,6 +526,7 @@ fn print_output(output: Output) -> anyhow::Result<()> {
526526 physical_size,
527527 modes,
528528 current_mode,
529+ is_custom_mode,
529530 vrr_supported,
530531 vrr_enabled,
531532 logical,
@@ -534,6 +535,26 @@ fn print_output(output: Output) -> anyhow::Result<()> {
534535 let serial = serial.as_deref().unwrap_or("Unknown");
535536 println!(r#"Output "{make} {model} {serial}" ({name})"#);
536537
538+ let print_qualifier = |is_preferred: bool, is_current: bool, is_custom_mode: bool| {
539+ let mut qualifier = Vec::new();
540+ if is_current {
541+ qualifier.push("current");
542+ if is_custom_mode {
543+ qualifier.push("custom");
544+ };
545+ };
546+
547+ if is_preferred {
548+ qualifier.push("preferred");
549+ };
550+
551+ if qualifier.is_empty() {
552+ String::new()
553+ } else {
554+ format!(" ({})", qualifier.join(", "))
555+ }
556+ };
557+
537558 if let Some(current) = current_mode {
538559 let mode = *modes
539560 .get(current)
@@ -545,8 +566,10 @@ fn print_output(output: Output) -> anyhow::Result<()> {
545566 is_preferred,
546567 } = mode;
547568 let refresh = refresh_rate as f64 / 1000.;
548- let preferred = if is_preferred { " (preferred)" } else { "" };
549- println!(" Current mode: {width}x{height} @ {refresh:.3} Hz{preferred}");
569+
570+ // This is technically the current mode, but the println below already specifies that.
571+ let qualifier = print_qualifier(is_preferred, false, is_custom_mode);
572+ println!(" Current mode: {width}x{height} @ {refresh:.3} Hz{qualifier}");
550573 } else {
551574 println!(" Disabled");
552575 }
@@ -601,12 +624,7 @@ fn print_output(output: Output) -> anyhow::Result<()> {
601624 let refresh = refresh_rate as f64 / 1000.;
602625
603626 let is_current = Some(idx) == current_mode;
604- let qualifier = match (is_current, is_preferred) {
605- (true, true) => " (current, preferred)",
606- (true, false) => " (current)",
607- (false, true) => " (preferred)",
608- (false, false) => "",
609- };
627+ let qualifier = print_qualifier(is_preferred, is_current, is_custom_mode);
610628
611629 println!(" {width}x{height}@{refresh:.3}{qualifier}");
612630 }
src/ipc/server.rsmodified+2 -0
@@ -399,6 +399,8 @@ async fn process(ctx: &ClientCtx, request: Request) -> Reply {
399399 Response::Handled
400400 }
401401 Request::Output { output, action } => {
402+ action.validate()?;
403+
402404 let ipc_outputs = ctx.ipc_outputs.lock().unwrap();
403405 let found = ipc_outputs
404406 .values()
src/niri.rsmodified+38 -2
@@ -1777,8 +1777,44 @@ impl State {
17771777 niri_ipc::OutputAction::Mode { mode } => {
17781778 config.mode = match mode {
17791779 niri_ipc::ModeToSet::Automatic => None,
1780- niri_ipc::ModeToSet::Specific(mode) => Some(mode),
1781- }
1780+ niri_ipc::ModeToSet::Specific(mode) => Some(niri_config::output::Mode {
1781+ custom: false,
1782+ mode,
1783+ }),
1784+ };
1785+ config.modeline = None;
1786+ }
1787+ niri_ipc::OutputAction::CustomMode { mode } => {
1788+ config.mode = Some(niri_config::output::Mode { custom: true, mode });
1789+ config.modeline = None;
1790+ }
1791+ niri_ipc::OutputAction::Modeline {
1792+ clock,
1793+ hdisplay,
1794+ hsync_start,
1795+ hsync_end,
1796+ htotal,
1797+ vdisplay,
1798+ vsync_start,
1799+ vsync_end,
1800+ vtotal,
1801+ hsync_polarity,
1802+ vsync_polarity,
1803+ } => {
1804+ // Do not reset config.mode to None since it's used as a fallback.
1805+ config.modeline = Some(niri_config::output::Modeline {
1806+ clock,
1807+ hdisplay,
1808+ hsync_start,
1809+ hsync_end,
1810+ htotal,
1811+ vdisplay,
1812+ vsync_start,
1813+ vsync_end,
1814+ vtotal,
1815+ hsync_polarity,
1816+ vsync_polarity,
1817+ })
17821818 }
17831819 niri_ipc::OutputAction::Scale { scale } => {
17841820 config.scale = match scale {
src/protocols/output_management.rsmodified+57 -31
@@ -110,19 +110,47 @@ impl OutputManagementManagerState {
110110 }
111111 }
112112
113- // TTY outputs can't change modes I think, however, winit and virtual outputs can.
113+ // Winit and virtual outputs can change modes; on a TTY custom modes can add/remove
114+ // a mode.
114115 let modes_changed = old.modes != conf.modes;
115116 if modes_changed {
116117 changed = true;
117- if old.modes.len() != conf.modes.len() {
118- error!("output's old mode count doesn't match new modes");
119- } else {
120- for client in self.clients.values() {
121- if let Some((_, modes)) = client.heads.get(output) {
122- for (wl_mode, mode) in zip(modes, &conf.modes) {
123- wl_mode.size(i32::from(mode.width), i32::from(mode.height));
124- if let Ok(refresh_rate) = mode.refresh_rate.try_into() {
125- wl_mode.refresh(refresh_rate);
118+ for client in self.clients.values_mut() {
119+ if let Some((head, modes)) = client.heads.get_mut(output) {
120+ // Ends on the shortest iterator.
121+ let zwlr_modes_with_modes = zip(modes.iter(), &conf.modes);
122+ let least_modes_len = zwlr_modes_with_modes.len();
123+
124+ for (wl_mode, mode) in zwlr_modes_with_modes {
125+ wl_mode.size(i32::from(mode.width), i32::from(mode.height));
126+ if let Ok(refresh_rate) = mode.refresh_rate.try_into() {
127+ wl_mode.refresh(refresh_rate);
128+ }
129+ }
130+
131+ if let Some(client) = client.manager.client() {
132+ if conf.modes.len() > least_modes_len {
133+ for mode in &conf.modes[least_modes_len..] {
134+ // One or more modes were added.
135+ let new_mode = client
136+ .create_resource::<ZwlrOutputModeV1, _, State>(
137+ &self.display,
138+ head.version(),
139+ (),
140+ )
141+ .unwrap();
142+ head.mode(&new_mode);
143+ new_mode
144+ .size(i32::from(mode.width), i32::from(mode.height));
145+ if let Ok(refresh_rate) = mode.refresh_rate.try_into() {
146+ new_mode.refresh(refresh_rate)
147+ }
148+ modes.push(new_mode);
149+ }
150+ } else if modes.len() > least_modes_len {
151+ // One or more modes were removed.
152+ for mode in modes.drain(least_modes_len..) {
153+ mode.finished();
126154 }
127155 }
128156 }
@@ -619,18 +647,21 @@ where
619647 return;
620648 };
621649
622- new_config.mode = Some(niri_ipc::ConfiguredMode {
623- width: mode.width,
624- height: mode.height,
625- refresh: Some(mode.refresh_rate as f64 / 1000.),
650+ new_config.mode = Some(niri_config::output::Mode {
651+ custom: false,
652+ mode: niri_ipc::ConfiguredMode {
653+ width: mode.width,
654+ height: mode.height,
655+ refresh: Some(mode.refresh_rate as f64 / 1000.),
656+ },
626657 });
658+ new_config.modeline = None;
627659 }
628660 zwlr_output_configuration_head_v1::Request::SetCustomMode {
629661 width,
630662 height,
631663 refresh,
632664 } => {
633- // FIXME: Support custom mode
634665 let (width, height, refresh): (u16, u16, u32) =
635666 match (width.try_into(), height.try_into(), refresh.try_into()) {
636667 (Ok(width), Ok(height), Ok(refresh)) => (width, height, refresh),
@@ -640,25 +671,20 @@ where
640671 }
641672 };
642673
643- let Some(current_config) = g_state.current_state.get(output_id) else {
644- warn!("SetMode: output missing from the current config");
645- return;
646- };
647-
648- let Some(mode) = current_config.modes.iter().find(|m| {
649- m.width == width
650- && m.height == height
651- && (refresh == 0 || m.refresh_rate == refresh)
652- }) else {
653- warn!("SetCustomMode: no matching mode");
674+ if refresh == 0 {
675+ warn!("SetCustomMode: refresh 0 requested, ignoring");
654676 return;
655- };
677+ }
656678
657- new_config.mode = Some(niri_ipc::ConfiguredMode {
658- width: mode.width,
659- height: mode.height,
660- refresh: Some(mode.refresh_rate as f64 / 1000.),
679+ new_config.mode = Some(niri_config::output::Mode {
680+ custom: true,
681+ mode: niri_ipc::ConfiguredMode {
682+ width,
683+ height,
684+ refresh: Some(refresh as f64 / 1000.),
685+ },
661686 });
687+ new_config.modeline = None;
662688 }
663689 zwlr_output_configuration_head_v1::Request::SetPosition { x, y } => {
664690 new_config.position = Some(niri_config::Position { x, y });