forge
Explore
Log in

Don't you dare go Hollow

Implement niri msg output

Browse files at this commit

65b9c74f624b4a78c2247135bf1a96dcac0bd009Ivan MolodetskikhParent: 2dff674
niri-config/src/lib.rsmodified+11 -53
@@ -11,7 +11,7 @@ use bitflags::bitflags;
1111 use knuffel::errors::DecodeError;
1212 use knuffel::Decode as _;
1313 use miette::{miette, Context, IntoDiagnostic, NarratableReportHandler};
14-use niri_ipc::{LayoutSwitchTarget, SizeChange, Transform};
14+use niri_ipc::{ConfiguredMode, LayoutSwitchTarget, SizeChange, Transform};
1515 use regex::Regex;
1616 use smithay::input::keyboard::keysyms::KEY_NoSymbol;
1717 use smithay::input::keyboard::xkb::{keysym_from_name, KEYSYM_CASE_INSENSITIVE};
@@ -250,7 +250,7 @@ pub struct Output {
250250 #[knuffel(child)]
251251 pub position: Option<Position>,
252252 #[knuffel(child, unwrap(argument, str))]
253- pub mode: Option<Mode>,
253+ pub mode: Option<ConfiguredMode>,
254254 #[knuffel(child)]
255255 pub variable_refresh_rate: bool,
256256 }
@@ -277,13 +277,6 @@ pub struct Position {
277277 pub y: i32,
278278 }
279279
280-#[derive(Debug, Clone, Copy, PartialEq)]
281-pub struct Mode {
282- pub width: u16,
283- pub height: u16,
284- pub refresh: Option<f64>,
285-}
286-
287280 #[derive(knuffel::Decode, Debug, Clone, PartialEq)]
288281 pub struct Layout {
289282 #[knuffel(child, default)]
@@ -1971,41 +1964,6 @@ where
19711964 }
19721965 }
19731966
1974-impl FromStr for Mode {
1975- type Err = miette::Error;
1976-
1977- fn from_str(s: &str) -> Result<Self, Self::Err> {
1978- let Some((width, rest)) = s.split_once('x') else {
1979- return Err(miette!("no 'x' separator found"));
1980- };
1981-
1982- let (height, refresh) = match rest.split_once('@') {
1983- Some((height, refresh)) => (height, Some(refresh)),
1984- None => (rest, None),
1985- };
1986-
1987- let width = width
1988- .parse()
1989- .into_diagnostic()
1990- .context("error parsing width")?;
1991- let height = height
1992- .parse()
1993- .into_diagnostic()
1994- .context("error parsing height")?;
1995- let refresh = refresh
1996- .map(str::parse)
1997- .transpose()
1998- .into_diagnostic()
1999- .context("error parsing refresh rate")?;
2000-
2001- Ok(Self {
2002- width,
2003- height,
2004- refresh,
2005- })
2006- }
2007-}
2008-
20091967 impl FromStr for Key {
20101968 type Err = miette::Error;
20111969
@@ -2336,7 +2294,7 @@ mod tests {
23362294 scale: 2.,
23372295 transform: Transform::Flipped90,
23382296 position: Some(Position { x: 10, y: 20 }),
2339- mode: Some(Mode {
2297+ mode: Some(ConfiguredMode {
23402298 width: 1920,
23412299 height: 1080,
23422300 refresh: Some(144.),
@@ -2574,8 +2532,8 @@ mod tests {
25742532 #[test]
25752533 fn parse_mode() {
25762534 assert_eq!(
2577- "2560x1600@165.004".parse::<Mode>().unwrap(),
2578- Mode {
2535+ "2560x1600@165.004".parse::<ConfiguredMode>().unwrap(),
2536+ ConfiguredMode {
25792537 width: 2560,
25802538 height: 1600,
25812539 refresh: Some(165.004),
@@ -2583,18 +2541,18 @@ mod tests {
25832541 );
25842542
25852543 assert_eq!(
2586- "1920x1080".parse::<Mode>().unwrap(),
2587- Mode {
2544+ "1920x1080".parse::<ConfiguredMode>().unwrap(),
2545+ ConfiguredMode {
25882546 width: 1920,
25892547 height: 1080,
25902548 refresh: None,
25912549 },
25922550 );
25932551
2594- assert!("1920".parse::<Mode>().is_err());
2595- assert!("1920x".parse::<Mode>().is_err());
2596- assert!("1920x1080@".parse::<Mode>().is_err());
2597- assert!("1920x1080@60Hz".parse::<Mode>().is_err());
2552+ assert!("1920".parse::<ConfiguredMode>().is_err());
2553+ assert!("1920x".parse::<ConfiguredMode>().is_err());
2554+ assert!("1920x1080@".parse::<ConfiguredMode>().is_err());
2555+ assert!("1920x1080@60Hz".parse::<ConfiguredMode>().is_err());
25982556 }
25992557
26002558 #[test]
niri-ipc/src/lib.rsmodified+153 -0
@@ -20,6 +20,17 @@ pub enum Request {
2020 FocusedWindow,
2121 /// Perform an action.
2222 Action(Action),
23+ /// Change output configuration temporarily.
24+ ///
25+ /// The configuration is changed temporarily and not saved into the config file. If the output
26+ /// configuration subsequently changes in the config file, these temporary changes will be
27+ /// forgotten.
28+ Output {
29+ /// Output name.
30+ output: String,
31+ /// Configuration to apply.
32+ action: OutputAction,
33+ },
2334 /// Respond with an error (for testing error handling).
2435 ReturnError,
2536 }
@@ -245,6 +256,103 @@ pub enum LayoutSwitchTarget {
245256 Prev,
246257 }
247258
259+/// Output actions that niri can perform.
260+// Variants in this enum should match the spelling of the ones in niri-config. Most thigs from
261+// niri-config should be present here.
262+#[derive(Serialize, Deserialize, Debug, Clone)]
263+#[cfg_attr(feature = "clap", derive(clap::Parser))]
264+#[cfg_attr(feature = "clap", command(subcommand_value_name = "ACTION"))]
265+#[cfg_attr(feature = "clap", command(subcommand_help_heading = "Actions"))]
266+pub enum OutputAction {
267+ /// Turn off the output.
268+ Off,
269+ /// Turn on the output.
270+ On,
271+ /// Set the output mode.
272+ Mode {
273+ /// Mode to set, or "auto" for automatic selection.
274+ ///
275+ /// Run `niri msg outputs` to see the avaliable modes.
276+ #[cfg_attr(feature = "clap", arg())]
277+ mode: ModeToSet,
278+ },
279+ /// Set the output scale.
280+ Scale {
281+ /// Scale factor to set.
282+ #[cfg_attr(feature = "clap", arg())]
283+ scale: f64,
284+ },
285+ /// Set the output transform.
286+ Transform {
287+ /// Transform to set, counter-clockwise.
288+ #[cfg_attr(feature = "clap", arg())]
289+ transform: Transform,
290+ },
291+ /// Set the output position.
292+ Position {
293+ /// Position to set, or "auto" for automatic selection.
294+ #[cfg_attr(feature = "clap", command(subcommand))]
295+ position: PositionToSet,
296+ },
297+ /// Toggle variable refresh rate.
298+ Vrr {
299+ /// Whether to enable variable refresh rate.
300+ #[cfg_attr(
301+ feature = "clap",
302+ arg(
303+ value_name = "ON|OFF",
304+ action = clap::ArgAction::Set,
305+ value_parser = clap::builder::BoolishValueParser::new(),
306+ ),
307+ )]
308+ enable: bool,
309+ },
310+}
311+
312+/// Output mode to set.
313+#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
314+pub enum ModeToSet {
315+ /// Niri will pick the mode automatically.
316+ Automatic,
317+ /// Specific mode.
318+ Specific(ConfiguredMode),
319+}
320+
321+/// Output mode as set in the config file.
322+#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
323+pub struct ConfiguredMode {
324+ /// Width in physical pixels.
325+ pub width: u16,
326+ /// Height in physical pixels.
327+ pub height: u16,
328+ /// Refresh rate.
329+ pub refresh: Option<f64>,
330+}
331+
332+/// Output position to set.
333+#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
334+#[cfg_attr(feature = "clap", derive(clap::Subcommand))]
335+#[cfg_attr(feature = "clap", command(subcommand_value_name = "POSITION"))]
336+#[cfg_attr(feature = "clap", command(subcommand_help_heading = "Position Values"))]
337+pub enum PositionToSet {
338+ /// Position the output automatically.
339+ #[cfg_attr(feature = "clap", command(name = "auto"))]
340+ Automatic,
341+ /// Set a specific position.
342+ #[cfg_attr(feature = "clap", command(name = "set"))]
343+ Specific(ConfiguredPosition),
344+}
345+
346+/// Output position as set in the config file.
347+#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
348+#[cfg_attr(feature = "clap", derive(clap::Args))]
349+pub struct ConfiguredPosition {
350+ /// Logical X position.
351+ pub x: i32,
352+ /// Logical Y position.
353+ pub y: i32,
354+}
355+
248356 /// Connected output.
249357 #[derive(Debug, Serialize, Deserialize, Clone)]
250358 pub struct Output {
@@ -304,6 +412,7 @@ pub struct LogicalOutput {
304412
305413 /// Output transform, which goes counter-clockwise.
306414 #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
415+#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
307416 pub enum Transform {
308417 /// Untransformed.
309418 Normal,
@@ -319,10 +428,13 @@ pub enum Transform {
319428 /// Flipped horizontally.
320429 Flipped,
321430 /// Rotated by 90° and flipped horizontally.
431+ #[cfg_attr(feature = "clap", value(name("flipped-90")))]
322432 Flipped90,
323433 /// Flipped vertically.
434+ #[cfg_attr(feature = "clap", value(name("flipped-180")))]
324435 Flipped180,
325436 /// Rotated by 270° and flipped horizontally.
437+ #[cfg_attr(feature = "clap", value(name("flipped-270")))]
326438 Flipped270,
327439 }
328440
@@ -407,3 +519,44 @@ impl FromStr for Transform {
407519 }
408520 }
409521 }
522+
523+impl FromStr for ModeToSet {
524+ type Err = &'static str;
525+
526+ fn from_str(s: &str) -> Result<Self, Self::Err> {
527+ if s.eq_ignore_ascii_case("auto") {
528+ return Ok(Self::Automatic);
529+ }
530+
531+ let mode = s.parse()?;
532+ Ok(Self::Specific(mode))
533+ }
534+}
535+
536+impl FromStr for ConfiguredMode {
537+ type Err = &'static str;
538+
539+ fn from_str(s: &str) -> Result<Self, Self::Err> {
540+ let Some((width, rest)) = s.split_once('x') else {
541+ return Err("no 'x' separator found");
542+ };
543+
544+ let (height, refresh) = match rest.split_once('@') {
545+ Some((height, refresh)) => (height, Some(refresh)),
546+ None => (rest, None),
547+ };
548+
549+ let width = width.parse().map_err(|_| "error parsing width")?;
550+ let height = height.parse().map_err(|_| "error parsing height")?;
551+ let refresh = refresh
552+ .map(str::parse)
553+ .transpose()
554+ .map_err(|_| "error parsing refresh rate")?;
555+
556+ Ok(Self {
557+ width,
558+ height,
559+ refresh,
560+ })
561+ }
562+}
src/backend/tty.rsmodified+1 -1
@@ -2111,7 +2111,7 @@ fn queue_estimated_vblank_timer(
21112111
21122112 fn pick_mode(
21132113 connector: &connector::Info,
2114- target: Option<niri_config::Mode>,
2114+ target: Option<niri_ipc::ConfiguredMode>,
21152115 ) -> Option<(control::Mode, bool)> {
21162116 let mut mode = None;
21172117 let mut fallback = false;
src/cli.rsmodified+16 -1
@@ -2,7 +2,7 @@ use std::ffi::OsString;
22 use std::path::PathBuf;
33
44 use clap::{Parser, Subcommand};
5-use niri_ipc::Action;
5+use niri_ipc::{Action, OutputAction};
66
77 use crate::utils::version;
88
@@ -63,6 +63,21 @@ pub enum Msg {
6363 #[command(subcommand)]
6464 action: Action,
6565 },
66+ /// Change output configuration temporarily.
67+ ///
68+ /// The configuration is changed temporarily and not saved into the config file. If the output
69+ /// configuration subsequently changes in the config file, these temporary changes will be
70+ /// forgotten.
71+ Output {
72+ /// Output name.
73+ ///
74+ /// Run `niri msg outputs` to see the output names.
75+ #[arg()]
76+ output: String,
77+ /// Configuration to apply.
78+ #[command(subcommand)]
79+ action: OutputAction,
80+ },
6681 /// Request an error from the running niri instance.
6782 RequestError,
6883 }
src/ipc/client.rsmodified+9 -0
@@ -11,6 +11,10 @@ pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
1111 Msg::Outputs => Request::Outputs,
1212 Msg::FocusedWindow => Request::FocusedWindow,
1313 Msg::Action { action } => Request::Action(action.clone()),
14+ Msg::Output { output, action } => Request::Output {
15+ output: output.clone(),
16+ action: action.clone(),
17+ },
1418 Msg::RequestError => Request::ReturnError,
1519 };
1620
@@ -237,6 +241,11 @@ pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
237241 bail!("unexpected response: expected Handled, got {response:?}");
238242 };
239243 }
244+ Msg::Output { .. } => {
245+ let Response::Handled = response else {
246+ bail!("unexpected response: expected Handled, got {response:?}");
247+ };
248+ }
240249 }
241250
242251 Ok(())
src/ipc/server.rsmodified+6 -0
@@ -169,6 +169,12 @@ fn process(ctx: &ClientCtx, request: Request) -> Reply {
169169 });
170170 Response::Handled
171171 }
172+ Request::Output { output, action } => {
173+ ctx.event_loop.insert_idle(move |state| {
174+ state.apply_transient_output_config(&output, action);
175+ });
176+ Response::Handled
177+ }
172178 };
173179
174180 Ok(response)
src/niri.rsmodified+115 -46
@@ -138,6 +138,13 @@ const FRAME_CALLBACK_THROTTLE: Option<Duration> = Some(Duration::from_millis(995
138138 pub struct Niri {
139139 pub config: Rc<RefCell<Config>>,
140140
141+ /// Output config from the config file.
142+ ///
143+ /// This does not include transient output config changes done via IPC. It is only used when
144+ /// reloading the config from disk to determine if the output configuration should be reloaded
145+ /// (and transient changes dropped).
146+ pub config_file_output_config: Vec<niri_config::Output>,
147+
141148 pub event_loop: LoopHandle<'static, State>,
142149 pub scheduler: Scheduler<()>,
143150 pub stop_signal: LoopSignal,
@@ -858,6 +865,7 @@ impl State {
858865 let mut reload_xkb = None;
859866 let mut libinput_config_changed = false;
860867 let mut output_config_changed = false;
868+ let mut preserved_output_config = None;
861869 let mut window_rules_changed = false;
862870 let mut debug_config_changed = false;
863871 let mut shaders_changed = false;
@@ -894,8 +902,15 @@ impl State {
894902 libinput_config_changed = true;
895903 }
896904
897- if config.outputs != old_config.outputs {
905+ if config.outputs != self.niri.config_file_output_config {
898906 output_config_changed = true;
907+ self.niri
908+ .config_file_output_config
909+ .clone_from(&config.outputs);
910+ } else {
911+ // Output config did not change from the last disk load, so we need to preserve the
912+ // transient changes.
913+ preserved_output_config = Some(mem::take(&mut old_config.outputs));
899914 }
900915
901916 if config.binds != old_config.binds {
@@ -926,6 +941,10 @@ impl State {
926941
927942 *old_config = config;
928943
944+ if let Some(outputs) = preserved_output_config {
945+ old_config.outputs = outputs;
946+ }
947+
929948 // Release the borrow.
930949 drop(old_config);
931950
@@ -945,51 +964,7 @@ impl State {
945964 }
946965
947966 if output_config_changed {
948- let mut resized_outputs = vec![];
949- for output in self.niri.global_space.outputs() {
950- let name = output.name();
951- let config = self.niri.config.borrow_mut();
952- let config = config.outputs.iter().find(|o| o.name == name);
953-
954- let scale = config.map(|c| c.scale).unwrap_or_else(|| {
955- let size_mm = output.physical_properties().size;
956- let resolution = output.current_mode().unwrap().size;
957- guess_monitor_scale(size_mm, resolution)
958- });
959- let scale = scale.clamp(1., 10.).ceil() as i32;
960-
961- let mut transform = config
962- .map(|c| ipc_transform_to_smithay(c.transform))
963- .unwrap_or(Transform::Normal);
964- // FIXME: fix winit damage on other transforms.
965- if name == "winit" {
966- transform = Transform::Flipped180;
967- }
968-
969- if output.current_scale().integer_scale() != scale
970- || output.current_transform() != transform
971- {
972- output.change_current_state(
973- None,
974- Some(transform),
975- Some(output::Scale::Integer(scale)),
976- None,
977- );
978- self.niri.ipc_outputs_changed = true;
979- resized_outputs.push(output.clone());
980- }
981- }
982- for output in resized_outputs {
983- self.niri.output_resized(&output);
984- }
985-
986- self.backend.on_output_config_changed(&mut self.niri);
987-
988- self.niri.reposition_outputs(None);
989-
990- if let Some(touch) = self.niri.seat.get_touch() {
991- touch.cancel(self);
992- }
967+ self.reload_output_config();
993968 }
994969
995970 if debug_config_changed {
@@ -1032,6 +1007,98 @@ impl State {
10321007 self.niri.queue_redraw_all();
10331008 }
10341009
1010+ fn reload_output_config(&mut self) {
1011+ let mut resized_outputs = vec![];
1012+ for output in self.niri.global_space.outputs() {
1013+ let name = output.name();
1014+ let config = self.niri.config.borrow_mut();
1015+ let config = config.outputs.iter().find(|o| o.name == name);
1016+
1017+ let scale = config.map(|c| c.scale).unwrap_or_else(|| {
1018+ let size_mm = output.physical_properties().size;
1019+ let resolution = output.current_mode().unwrap().size;
1020+ guess_monitor_scale(size_mm, resolution)
1021+ });
1022+ let scale = scale.clamp(1., 10.).ceil() as i32;
1023+
1024+ let mut transform = config
1025+ .map(|c| ipc_transform_to_smithay(c.transform))
1026+ .unwrap_or(Transform::Normal);
1027+ // FIXME: fix winit damage on other transforms.
1028+ if name == "winit" {
1029+ transform = Transform::Flipped180;
1030+ }
1031+
1032+ if output.current_scale().integer_scale() != scale
1033+ || output.current_transform() != transform
1034+ {
1035+ output.change_current_state(
1036+ None,
1037+ Some(transform),
1038+ Some(output::Scale::Integer(scale)),
1039+ None,
1040+ );
1041+ self.niri.ipc_outputs_changed = true;
1042+ resized_outputs.push(output.clone());
1043+ }
1044+ }
1045+ for output in resized_outputs {
1046+ self.niri.output_resized(&output);
1047+ }
1048+
1049+ self.backend.on_output_config_changed(&mut self.niri);
1050+
1051+ self.niri.reposition_outputs(None);
1052+
1053+ if let Some(touch) = self.niri.seat.get_touch() {
1054+ touch.cancel(self);
1055+ }
1056+ }
1057+
1058+ pub fn apply_transient_output_config(&mut self, name: &str, action: niri_ipc::OutputAction) {
1059+ {
1060+ let mut config = self.niri.config.borrow_mut();
1061+ let config = if let Some(config) = config.outputs.iter_mut().find(|o| o.name == name) {
1062+ config
1063+ } else {
1064+ config.outputs.push(niri_config::Output {
1065+ name: String::from(name),
1066+ ..Default::default()
1067+ });
1068+ config.outputs.last_mut().unwrap()
1069+ };
1070+
1071+ match action {
1072+ niri_ipc::OutputAction::Off => config.off = true,
1073+ niri_ipc::OutputAction::On => config.off = false,
1074+ niri_ipc::OutputAction::Mode { mode } => {
1075+ config.mode = match mode {
1076+ niri_ipc::ModeToSet::Automatic => None,
1077+ niri_ipc::ModeToSet::Specific(mode) => Some(mode),
1078+ }
1079+ }
1080+ niri_ipc::OutputAction::Scale { scale } => config.scale = scale,
1081+ niri_ipc::OutputAction::Transform { transform } => config.transform = transform,
1082+ niri_ipc::OutputAction::Position { position } => {
1083+ config.position = match position {
1084+ niri_ipc::PositionToSet::Automatic => None,
1085+ niri_ipc::PositionToSet::Specific(position) => {
1086+ Some(niri_config::Position {
1087+ x: position.x,
1088+ y: position.y,
1089+ })
1090+ }
1091+ }
1092+ }
1093+ niri_ipc::OutputAction::Vrr { enable } => {
1094+ config.variable_refresh_rate = enable;
1095+ }
1096+ }
1097+ }
1098+
1099+ self.reload_output_config();
1100+ }
1101+
10351102 pub fn refresh_ipc_outputs(&mut self) {
10361103 if !self.niri.ipc_outputs_changed {
10371104 return;
@@ -1175,6 +1242,7 @@ impl Niri {
11751242
11761243 let display_handle = display.handle();
11771244 let config_ = config.borrow();
1245+ let config_file_output_config = config_.outputs.clone();
11781246
11791247 let layout = Layout::new(&config_);
11801248
@@ -1353,6 +1421,7 @@ impl Niri {
13531421 drop(config_);
13541422 Self {
13551423 config,
1424+ config_file_output_config,
13561425
13571426 event_loop,
13581427 scheduler,