forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

lib.rs2207 lines, 77.5 KiBHistoryRawDownload
1//! Types for communicating with niri via IPC.
2//!
3//! After connecting to the niri socket, you can send [`Request`]s. Niri will process them one by
4//! one, in order, and to each request it will respond with a single [`Reply`], which is a `Result`
5//! wrapping a [`Response`].
6//!
7//! If you send a [`Request::EventStream`], niri will *stop* reading subsequent [`Request`]s, and
8//! will start continuously writing compositor [`Event`]s to the socket. If you'd like to read an
9//! event stream and write more requests at the same time, you need to use two IPC sockets.
10//!
11//! <div class="warning">
12//!
13//! Requests are *always* processed separately. Time passes between requests, even when sending
14//! multiple requests to the socket at once. For example, sending [`Request::Workspaces`] and
15//! [`Request::Windows`] together may not return consistent results (e.g. a window may open on a
16//! new workspace in-between the two responses). This goes for actions too: sending
17//! [`Action::FocusWindow`] and <code>[Action::CloseWindow] { id: None }</code> together may close
18//! the wrong window because a different window got focused in-between these requests.
19//!
20//! </div>
21//!
22//! You can use the [`socket::Socket`] helper if you're fine with blocking communication. However,
23//! it is a fairly simple helper, so if you need async, or if you're using a different language,
24//! you are encouraged to communicate with the socket manually.
25//!
26//! 1. Read the socket filesystem path from [`socket::SOCKET_PATH_ENV`] (`$NIRI_SOCKET`).
27//! 2. Connect to the socket and write a JSON-formatted [`Request`] on a single line. You can follow
28//! up with a line break and a flush, or just flush and shutdown the write end of the socket.
29//! 3. Niri will respond with a single line JSON-formatted [`Reply`].
30//! 4. You can keep writing [`Request`]s, each on a single line, and read [`Reply`]s, also each on a
31//! separate line.
32//! 5. After you request an event stream, niri will keep responding with JSON-formatted [`Event`]s,
33//! on a single line each.
34//!
35//! ## Backwards compatibility
36//!
37//! This crate follows the niri version. It is **not** API-stable in terms of the Rust semver. In
38//! particular, expect new struct fields and enum variants to be added in patch version bumps.
39//!
40//! Use an exact version requirement to avoid breaking changes:
41//!
42//! ```toml
43//! [dependencies]
44//! niri-ipc = "=26.4.0"
45//! ```
46//!
47//! ## Features
48//!
49//! This crate defines the following features:
50//! - `json-schema`: derives the [schemars](https://lib.rs/crates/schemars) `JsonSchema` trait for
51//! the types.
52//! - `clap`: derives the clap CLI parsing traits for some types. Used internally by niri itself.
53#![warn(missing_docs)]
54
55use std::collections::HashMap;
56use std::str::FromStr;
57use std::time::Duration;
58
59use serde::{Deserialize, Serialize};
60
61pub mod socket;
62pub mod state;
63
64/// Request from client to niri.
65#[derive(Debug, Serialize, Deserialize, Clone)]
66#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
67pub enum Request {
68 /// Request the version string for the running niri instance.
69 Version,
70 /// Request information about connected outputs.
71 Outputs,
72 /// Request information about workspaces.
73 Workspaces,
74 /// Request information about open windows.
75 Windows,
76 /// Request information about layer-shell surfaces.
77 Layers,
78 /// Request information about the configured keyboard layouts.
79 KeyboardLayouts,
80 /// Request information about the focused output.
81 FocusedOutput,
82 /// Request information about the focused window.
83 FocusedWindow,
84 /// Request picking a window and get its information.
85 PickWindow,
86 /// Request picking a color from the screen.
87 PickColor,
88 /// Perform an action.
89 Action(Action),
90 /// Change output configuration temporarily.
91 ///
92 /// The configuration is changed temporarily and not saved into the config file. If the output
93 /// configuration subsequently changes in the config file, these temporary changes will be
94 /// forgotten.
95 Output {
96 /// Output name.
97 output: String,
98 /// Configuration to apply.
99 action: OutputAction,
100 },
101 /// Start continuously receiving events from the compositor.
102 ///
103 /// The compositor should reply with `Reply::Ok(Response::Handled)`, then continuously send
104 /// [`Event`]s, one per line.
105 ///
106 /// The event stream will always give you the full current state up-front. For example, the
107 /// first workspace-related event you will receive will be [`Event::WorkspacesChanged`]
108 /// containing the full current workspaces state. You *do not* need to separately send
109 /// [`Request::Workspaces`] when using the event stream.
110 ///
111 /// Where reasonable, event stream state updates are atomic, though this is not always the
112 /// case. For example, a window may end up with a workspace id for a workspace that had already
113 /// been removed. This can happen if the corresponding [`Event::WorkspacesChanged`] arrives
114 /// before the corresponding [`Event::WindowOpenedOrChanged`].
115 EventStream,
116 /// Respond with an error (for testing error handling).
117 ReturnError,
118 /// Request information about the overview.
119 OverviewState,
120 /// Request information about screencasts.
121 Casts,
122}
123
124/// Reply from niri to client.
125///
126/// Every request gets one reply.
127///
128/// * If an error had occurred, it will be an `Reply::Err`.
129/// * If the request does not need any particular response, it will be
130/// `Reply::Ok(Response::Handled)`. Kind of like an `Ok(())`.
131/// * Otherwise, it will be `Reply::Ok(response)` with one of the other [`Response`] variants.
132pub type Reply = Result<Response, String>;
133
134/// Successful response from niri to client.
135#[derive(Debug, Serialize, Deserialize, Clone)]
136#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
137pub enum Response {
138 /// A request that does not need a response was handled successfully.
139 Handled,
140 /// The version string for the running niri instance.
141 Version(String),
142 /// Information about connected outputs.
143 ///
144 /// Map from output name to output info.
145 Outputs(HashMap<String, Output>),
146 /// Information about workspaces.
147 Workspaces(Vec<Workspace>),
148 /// Information about open windows.
149 Windows(Vec<Window>),
150 /// Information about layer-shell surfaces.
151 Layers(Vec<LayerSurface>),
152 /// Information about the keyboard layout.
153 KeyboardLayouts(KeyboardLayouts),
154 /// Information about the focused output.
155 FocusedOutput(Option<Output>),
156 /// Information about the focused window.
157 FocusedWindow(Option<Window>),
158 /// Information about the picked window.
159 PickedWindow(Option<Window>),
160 /// Information about the picked color.
161 PickedColor(Option<PickedColor>),
162 /// Output configuration change result.
163 OutputConfigChanged(OutputConfigChanged),
164 /// Information about the overview.
165 OverviewState(Overview),
166 /// Information about screencasts.
167 Casts(Vec<Cast>),
168}
169
170/// Overview information.
171#[derive(Serialize, Deserialize, Debug, Clone)]
172#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
173pub struct Overview {
174 /// Whether the overview is currently open.
175 pub is_open: bool,
176}
177
178/// Color picked from the screen.
179#[derive(Serialize, Deserialize, Debug, Clone)]
180#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
181pub struct PickedColor {
182 /// Color values as red, green, blue, each ranging from 0.0 to 1.0.
183 pub rgb: [f64; 3],
184}
185
186/// Actions that niri can perform.
187// Variants in this enum should match the spelling of the ones in niri-config. Most, but not all,
188// variants from niri-config should be present here.
189#[derive(Serialize, Deserialize, Debug, Clone)]
190#[cfg_attr(feature = "clap", derive(clap::Parser))]
191#[cfg_attr(feature = "clap", command(subcommand_value_name = "ACTION"))]
192#[cfg_attr(feature = "clap", command(subcommand_help_heading = "Actions"))]
193#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
194pub enum Action {
195 /// Exit niri.
196 Quit {
197 /// Skip the "Press Enter to confirm" prompt.
198 #[serde(default)]
199 #[cfg_attr(feature = "clap", arg(short, long))]
200 skip_confirmation: bool,
201 },
202 /// Power off all monitors via DPMS.
203 PowerOffMonitors {},
204 /// Power on all monitors via DPMS.
205 PowerOnMonitors {},
206 /// Spawn a command.
207 Spawn {
208 /// Command to spawn.
209 #[cfg_attr(feature = "clap", arg(last = true, required = true))]
210 command: Vec<String>,
211 },
212 /// Spawn a command through the shell.
213 SpawnSh {
214 /// Command to run.
215 #[cfg_attr(feature = "clap", arg(last = true, required = true))]
216 command: String,
217 },
218 /// Do a screen transition.
219 DoScreenTransition {
220 /// Delay in milliseconds for the screen to freeze before starting the transition.
221 #[cfg_attr(feature = "clap", arg(short, long))]
222 delay_ms: Option<u16>,
223 },
224 /// Open the screenshot UI.
225 Screenshot {
226 /// Whether to show the mouse pointer by default in the screenshot UI.
227 #[serde(default = "default_true")]
228 #[cfg_attr(feature = "clap", arg(short = 'p', long, action = clap::ArgAction::Set, default_value_t = true))]
229 show_pointer: bool,
230
231 /// Path to save the screenshot to.
232 ///
233 /// The path must be absolute, otherwise an error is returned.
234 ///
235 /// If `None`, the screenshot is saved according to the `screenshot-path` config setting.
236 #[cfg_attr(feature = "clap", arg(long, action = clap::ArgAction::Set))]
237 path: Option<String>,
238 },
239 /// Screenshot the focused screen.
240 ScreenshotScreen {
241 /// Write the screenshot to disk in addition to putting it in your clipboard.
242 ///
243 /// The screenshot is saved according to the `screenshot-path` config setting.
244 #[serde(default = "default_true")]
245 #[cfg_attr(feature = "clap", arg(short = 'd', long, action = clap::ArgAction::Set, default_value_t = true))]
246 write_to_disk: bool,
247
248 /// Whether to include the mouse pointer in the screenshot.
249 #[serde(default = "default_true")]
250 #[cfg_attr(feature = "clap", arg(short = 'p', long, action = clap::ArgAction::Set, default_value_t = true))]
251 show_pointer: bool,
252
253 /// Path to save the screenshot to.
254 ///
255 /// The path must be absolute, otherwise an error is returned.
256 ///
257 /// If `None`, the screenshot is saved according to the `screenshot-path` config setting.
258 #[cfg_attr(feature = "clap", arg(long, action = clap::ArgAction::Set))]
259 path: Option<String>,
260 },
261 /// Screenshot a window.
262 #[cfg_attr(feature = "clap", clap(about = "Screenshot the focused window"))]
263 ScreenshotWindow {
264 /// Id of the window to screenshot.
265 ///
266 /// If `None`, uses the focused window.
267 #[cfg_attr(feature = "clap", arg(long))]
268 id: Option<u64>,
269 /// Write the screenshot to disk in addition to putting it in your clipboard.
270 ///
271 /// The screenshot is saved according to the `screenshot-path` config setting.
272 #[serde(default = "default_true")]
273 #[cfg_attr(feature = "clap", arg(short = 'd', long, action = clap::ArgAction::Set, default_value_t = true))]
274 write_to_disk: bool,
275
276 /// Whether to include the mouse pointer in the screenshot.
277 ///
278 /// The pointer will be included only if the window is currently receiving pointer input
279 /// (usually this means the pointer is on top of the window).
280 #[serde(default)]
281 #[cfg_attr(feature = "clap", arg(short = 'p', long, action = clap::ArgAction::Set, default_value_t = false))]
282 show_pointer: bool,
283
284 /// Path to save the screenshot to.
285 ///
286 /// The path must be absolute, otherwise an error is returned.
287 ///
288 /// If `None`, the screenshot is saved according to the `screenshot-path` config setting.
289 #[cfg_attr(feature = "clap", arg(long, action = clap::ArgAction::Set))]
290 path: Option<String>,
291 },
292 /// Enable or disable the keyboard shortcuts inhibitor (if any) for the focused surface.
293 ToggleKeyboardShortcutsInhibit {},
294 /// Close a window.
295 #[cfg_attr(feature = "clap", clap(about = "Close the focused window"))]
296 CloseWindow {
297 /// Id of the window to close.
298 ///
299 /// If `None`, uses the focused window.
300 #[cfg_attr(feature = "clap", arg(long))]
301 id: Option<u64>,
302 },
303 /// Toggle fullscreen on a window.
304 #[cfg_attr(
305 feature = "clap",
306 clap(about = "Toggle fullscreen on the focused window")
307 )]
308 FullscreenWindow {
309 /// Id of the window to toggle fullscreen of.
310 ///
311 /// If `None`, uses the focused window.
312 #[cfg_attr(feature = "clap", arg(long))]
313 id: Option<u64>,
314 },
315 /// Toggle windowed (fake) fullscreen on a window.
316 #[cfg_attr(
317 feature = "clap",
318 clap(about = "Toggle windowed (fake) fullscreen on the focused window")
319 )]
320 ToggleWindowedFullscreen {
321 /// Id of the window to toggle windowed fullscreen of.
322 ///
323 /// If `None`, uses the focused window.
324 #[cfg_attr(feature = "clap", arg(long))]
325 id: Option<u64>,
326 },
327 /// Focus a window by id.
328 FocusWindow {
329 /// Id of the window to focus.
330 #[cfg_attr(feature = "clap", arg(long))]
331 id: u64,
332 },
333 /// Focus a window in the focused column by index.
334 FocusWindowInColumn {
335 /// Index of the window in the column.
336 ///
337 /// The index starts from 1 for the topmost window.
338 #[cfg_attr(feature = "clap", arg())]
339 index: u8,
340 },
341 /// Focus the previously focused window.
342 FocusWindowPrevious {},
343 /// Focus the column to the left.
344 FocusColumnLeft {},
345 /// Focus the column to the right.
346 FocusColumnRight {},
347 /// Focus the first column.
348 FocusColumnFirst {},
349 /// Focus the last column.
350 FocusColumnLast {},
351 /// Focus the next column to the right, looping if at end.
352 FocusColumnRightOrFirst {},
353 /// Focus the next column to the left, looping if at start.
354 FocusColumnLeftOrLast {},
355 /// Focus a column by index.
356 FocusColumn {
357 /// Index of the column to focus.
358 ///
359 /// The index starts from 1 for the first column.
360 #[cfg_attr(feature = "clap", arg())]
361 index: usize,
362 },
363 /// Focus the window or the monitor above.
364 FocusWindowOrMonitorUp {},
365 /// Focus the window or the monitor below.
366 FocusWindowOrMonitorDown {},
367 /// Focus the column or the monitor to the left.
368 FocusColumnOrMonitorLeft {},
369 /// Focus the column or the monitor to the right.
370 FocusColumnOrMonitorRight {},
371 /// Focus the window below.
372 FocusWindowDown {},
373 /// Focus the window above.
374 FocusWindowUp {},
375 /// Focus the window below or the column to the left.
376 FocusWindowDownOrColumnLeft {},
377 /// Focus the window below or the column to the right.
378 FocusWindowDownOrColumnRight {},
379 /// Focus the window above or the column to the left.
380 FocusWindowUpOrColumnLeft {},
381 /// Focus the window above or the column to the right.
382 FocusWindowUpOrColumnRight {},
383 /// Focus the window or the workspace below.
384 FocusWindowOrWorkspaceDown {},
385 /// Focus the window or the workspace above.
386 FocusWindowOrWorkspaceUp {},
387 /// Focus the topmost window.
388 FocusWindowTop {},
389 /// Focus the bottommost window.
390 FocusWindowBottom {},
391 /// Focus the window below or the topmost window.
392 FocusWindowDownOrTop {},
393 /// Focus the window above or the bottommost window.
394 FocusWindowUpOrBottom {},
395 /// Move the focused column to the left.
396 MoveColumnLeft {},
397 /// Move the focused column to the right.
398 MoveColumnRight {},
399 /// Move the focused column to the start of the workspace.
400 MoveColumnToFirst {},
401 /// Move the focused column to the end of the workspace.
402 MoveColumnToLast {},
403 /// Move the focused column to the left or to the monitor to the left.
404 MoveColumnLeftOrToMonitorLeft {},
405 /// Move the focused column to the right or to the monitor to the right.
406 MoveColumnRightOrToMonitorRight {},
407 /// Move the focused column to a specific index on its workspace.
408 MoveColumnToIndex {
409 /// New index for the column.
410 ///
411 /// The index starts from 1 for the first column.
412 #[cfg_attr(feature = "clap", arg())]
413 index: usize,
414 },
415 /// Move the focused window down in a column.
416 MoveWindowDown {},
417 /// Move the focused window up in a column.
418 MoveWindowUp {},
419 /// Move the focused window down in a column or to the workspace below.
420 MoveWindowDownOrToWorkspaceDown {},
421 /// Move the focused window up in a column or to the workspace above.
422 MoveWindowUpOrToWorkspaceUp {},
423 /// Consume or expel a window left.
424 #[cfg_attr(
425 feature = "clap",
426 clap(about = "Consume or expel the focused window left")
427 )]
428 ConsumeOrExpelWindowLeft {
429 /// Id of the window to consume or expel.
430 ///
431 /// If `None`, uses the focused window.
432 #[cfg_attr(feature = "clap", arg(long))]
433 id: Option<u64>,
434 },
435 /// Consume or expel a window right.
436 #[cfg_attr(
437 feature = "clap",
438 clap(about = "Consume or expel the focused window right")
439 )]
440 ConsumeOrExpelWindowRight {
441 /// Id of the window to consume or expel.
442 ///
443 /// If `None`, uses the focused window.
444 #[cfg_attr(feature = "clap", arg(long))]
445 id: Option<u64>,
446 },
447 /// Consume the window to the right into the focused column.
448 ConsumeWindowIntoColumn {},
449 /// Expel the bottom window from the focused column.
450 ExpelWindowFromColumn {},
451 /// Swap focused window with one to the right.
452 SwapWindowRight {},
453 /// Swap focused window with one to the left.
454 SwapWindowLeft {},
455 /// Toggle the focused column between normal and tabbed display.
456 ToggleColumnTabbedDisplay {},
457 /// Set the display mode of the focused column.
458 SetColumnDisplay {
459 /// Display mode to set.
460 #[cfg_attr(feature = "clap", arg())]
461 display: ColumnDisplay,
462 },
463 /// Center the focused column on the screen.
464 CenterColumn {},
465 /// Center a window on the screen.
466 #[cfg_attr(
467 feature = "clap",
468 clap(about = "Center the focused window on the screen")
469 )]
470 CenterWindow {
471 /// Id of the window to center.
472 ///
473 /// If `None`, uses the focused window.
474 #[cfg_attr(feature = "clap", arg(long))]
475 id: Option<u64>,
476 },
477 /// Center all fully visible columns on the screen.
478 CenterVisibleColumns {},
479 /// Focus the workspace below.
480 FocusWorkspaceDown {},
481 /// Focus the workspace above.
482 FocusWorkspaceUp {},
483 /// Focus a workspace by reference (index or name).
484 FocusWorkspace {
485 /// Reference (index or name) of the workspace to focus.
486 #[cfg_attr(feature = "clap", arg())]
487 reference: WorkspaceReferenceArg,
488 },
489 /// Focus the previous workspace.
490 FocusWorkspacePrevious {},
491 /// Move the focused window to the workspace below.
492 MoveWindowToWorkspaceDown {
493 /// Whether the focus should follow the target workspace.
494 ///
495 /// If `true` (the default), the focus will follow the window to the new workspace. If
496 /// `false`, the focus will remain on the original workspace.
497 #[serde(default = "default_true")]
498 #[cfg_attr(feature = "clap", arg(long, action = clap::ArgAction::Set, default_value_t = true))]
499 focus: bool,
500 },
501 /// Move the focused window to the workspace above.
502 MoveWindowToWorkspaceUp {
503 /// Whether the focus should follow the target workspace.
504 ///
505 /// If `true` (the default), the focus will follow the window to the new workspace. If
506 /// `false`, the focus will remain on the original workspace.
507 #[serde(default = "default_true")]
508 #[cfg_attr(feature = "clap", arg(long, action = clap::ArgAction::Set, default_value_t = true))]
509 focus: bool,
510 },
511 /// Move a window to a workspace.
512 #[cfg_attr(
513 feature = "clap",
514 clap(about = "Move the focused window to a workspace by reference (index or name)")
515 )]
516 MoveWindowToWorkspace {
517 /// Id of the window to move.
518 ///
519 /// If `None`, uses the focused window.
520 #[cfg_attr(feature = "clap", arg(long))]
521 window_id: Option<u64>,
522
523 /// Reference (index or name) of the workspace to move the window to.
524 #[cfg_attr(feature = "clap", arg())]
525 reference: WorkspaceReferenceArg,
526
527 /// Whether the focus should follow the moved window.
528 ///
529 /// If `true` (the default) and the window to move is focused, the focus will follow the
530 /// window to the new workspace. If `false`, the focus will remain on the original
531 /// workspace.
532 #[serde(default = "default_true")]
533 #[cfg_attr(feature = "clap", arg(long, action = clap::ArgAction::Set, default_value_t = true))]
534 focus: bool,
535 },
536 /// Move the focused column to the workspace below.
537 MoveColumnToWorkspaceDown {
538 /// Whether the focus should follow the target workspace.
539 ///
540 /// If `true` (the default), the focus will follow the column to the new workspace. If
541 /// `false`, the focus will remain on the original workspace.
542 #[serde(default = "default_true")]
543 #[cfg_attr(feature = "clap", arg(long, action = clap::ArgAction::Set, default_value_t = true))]
544 focus: bool,
545 },
546 /// Move the focused column to the workspace above.
547 MoveColumnToWorkspaceUp {
548 /// Whether the focus should follow the target workspace.
549 ///
550 /// If `true` (the default), the focus will follow the column to the new workspace. If
551 /// `false`, the focus will remain on the original workspace.
552 #[serde(default = "default_true")]
553 #[cfg_attr(feature = "clap", arg(long, action = clap::ArgAction::Set, default_value_t = true))]
554 focus: bool,
555 },
556 /// Move the focused column to a workspace by reference (index or name).
557 MoveColumnToWorkspace {
558 /// Reference (index or name) of the workspace to move the column to.
559 #[cfg_attr(feature = "clap", arg())]
560 reference: WorkspaceReferenceArg,
561
562 /// Whether the focus should follow the target workspace.
563 ///
564 /// If `true` (the default), the focus will follow the column to the new workspace. If
565 /// `false`, the focus will remain on the original workspace.
566 #[serde(default = "default_true")]
567 #[cfg_attr(feature = "clap", arg(long, action = clap::ArgAction::Set, default_value_t = true))]
568 focus: bool,
569 },
570 /// Move the focused workspace down.
571 MoveWorkspaceDown {},
572 /// Move the focused workspace up.
573 MoveWorkspaceUp {},
574 /// Move a workspace to a specific index on its monitor.
575 #[cfg_attr(
576 feature = "clap",
577 clap(about = "Move the focused workspace to a specific index on its monitor")
578 )]
579 MoveWorkspaceToIndex {
580 /// New index for the workspace.
581 #[cfg_attr(feature = "clap", arg())]
582 index: usize,
583
584 /// Reference (index or name) of the workspace to move.
585 ///
586 /// If `None`, uses the focused workspace.
587 #[cfg_attr(feature = "clap", arg(long))]
588 reference: Option<WorkspaceReferenceArg>,
589 },
590 /// Set the name of a workspace.
591 #[cfg_attr(
592 feature = "clap",
593 clap(about = "Set the name of the focused workspace")
594 )]
595 SetWorkspaceName {
596 /// New name for the workspace.
597 #[cfg_attr(feature = "clap", arg())]
598 name: String,
599
600 /// Reference (index or name) of the workspace to name.
601 ///
602 /// If `None`, uses the focused workspace.
603 #[cfg_attr(feature = "clap", arg(long))]
604 workspace: Option<WorkspaceReferenceArg>,
605 },
606 /// Unset the name of a workspace.
607 #[cfg_attr(
608 feature = "clap",
609 clap(about = "Unset the name of the focused workspace")
610 )]
611 UnsetWorkspaceName {
612 /// Reference (index or name) of the workspace to unname.
613 ///
614 /// If `None`, uses the focused workspace.
615 #[cfg_attr(feature = "clap", arg())]
616 reference: Option<WorkspaceReferenceArg>,
617 },
618 /// Focus the monitor to the left.
619 FocusMonitorLeft {},
620 /// Focus the monitor to the right.
621 FocusMonitorRight {},
622 /// Focus the monitor below.
623 FocusMonitorDown {},
624 /// Focus the monitor above.
625 FocusMonitorUp {},
626 /// Focus the previous monitor.
627 FocusMonitorPrevious {},
628 /// Focus the next monitor.
629 FocusMonitorNext {},
630 /// Focus a monitor by name.
631 FocusMonitor {
632 /// Name of the output to focus.
633 #[cfg_attr(feature = "clap", arg())]
634 output: String,
635 },
636 /// Move the focused window to the monitor to the left.
637 MoveWindowToMonitorLeft {},
638 /// Move the focused window to the monitor to the right.
639 MoveWindowToMonitorRight {},
640 /// Move the focused window to the monitor below.
641 MoveWindowToMonitorDown {},
642 /// Move the focused window to the monitor above.
643 MoveWindowToMonitorUp {},
644 /// Move the focused window to the previous monitor.
645 MoveWindowToMonitorPrevious {},
646 /// Move the focused window to the next monitor.
647 MoveWindowToMonitorNext {},
648 /// Move a window to a specific monitor.
649 #[cfg_attr(
650 feature = "clap",
651 clap(about = "Move the focused window to a specific monitor")
652 )]
653 MoveWindowToMonitor {
654 /// Id of the window to move.
655 ///
656 /// If `None`, uses the focused window.
657 #[cfg_attr(feature = "clap", arg(long))]
658 id: Option<u64>,
659
660 /// The target output name.
661 #[cfg_attr(feature = "clap", arg())]
662 output: String,
663 },
664 /// Move the focused column to the monitor to the left.
665 MoveColumnToMonitorLeft {},
666 /// Move the focused column to the monitor to the right.
667 MoveColumnToMonitorRight {},
668 /// Move the focused column to the monitor below.
669 MoveColumnToMonitorDown {},
670 /// Move the focused column to the monitor above.
671 MoveColumnToMonitorUp {},
672 /// Move the focused column to the previous monitor.
673 MoveColumnToMonitorPrevious {},
674 /// Move the focused column to the next monitor.
675 MoveColumnToMonitorNext {},
676 /// Move the focused column to a specific monitor.
677 MoveColumnToMonitor {
678 /// The target output name.
679 #[cfg_attr(feature = "clap", arg())]
680 output: String,
681 },
682 /// Change the width of a window.
683 #[cfg_attr(
684 feature = "clap",
685 clap(about = "Change the width of the focused window")
686 )]
687 SetWindowWidth {
688 /// Id of the window whose width to set.
689 ///
690 /// If `None`, uses the focused window.
691 #[cfg_attr(feature = "clap", arg(long))]
692 id: Option<u64>,
693
694 /// How to change the width.
695 #[cfg_attr(feature = "clap", arg(allow_hyphen_values = true))]
696 change: SizeChange,
697 },
698 /// Change the height of a window.
699 #[cfg_attr(
700 feature = "clap",
701 clap(about = "Change the height of the focused window")
702 )]
703 SetWindowHeight {
704 /// Id of the window whose height to set.
705 ///
706 /// If `None`, uses the focused window.
707 #[cfg_attr(feature = "clap", arg(long))]
708 id: Option<u64>,
709
710 /// How to change the height.
711 #[cfg_attr(feature = "clap", arg(allow_hyphen_values = true))]
712 change: SizeChange,
713 },
714 /// Reset the height of a window back to automatic.
715 #[cfg_attr(
716 feature = "clap",
717 clap(about = "Reset the height of the focused window back to automatic")
718 )]
719 ResetWindowHeight {
720 /// Id of the window whose height to reset.
721 ///
722 /// If `None`, uses the focused window.
723 #[cfg_attr(feature = "clap", arg(long))]
724 id: Option<u64>,
725 },
726 /// Switch between preset column widths.
727 SwitchPresetColumnWidth {},
728 /// Switch between preset column widths backwards.
729 SwitchPresetColumnWidthBack {},
730 /// Switch between preset window widths.
731 SwitchPresetWindowWidth {
732 /// Id of the window whose width to switch.
733 ///
734 /// If `None`, uses the focused window.
735 #[cfg_attr(feature = "clap", arg(long))]
736 id: Option<u64>,
737 },
738 /// Switch between preset window widths backwards.
739 SwitchPresetWindowWidthBack {
740 /// Id of the window whose width to switch.
741 ///
742 /// If `None`, uses the focused window.
743 #[cfg_attr(feature = "clap", arg(long))]
744 id: Option<u64>,
745 },
746 /// Switch between preset window heights.
747 SwitchPresetWindowHeight {
748 /// Id of the window whose height to switch.
749 ///
750 /// If `None`, uses the focused window.
751 #[cfg_attr(feature = "clap", arg(long))]
752 id: Option<u64>,
753 },
754 /// Switch between preset window heights backwards.
755 SwitchPresetWindowHeightBack {
756 /// Id of the window whose height to switch.
757 ///
758 /// If `None`, uses the focused window.
759 #[cfg_attr(feature = "clap", arg(long))]
760 id: Option<u64>,
761 },
762 /// Toggle the maximized state of the focused column.
763 MaximizeColumn {},
764 /// Toggle the maximized-to-edges state of the focused window.
765 MaximizeWindowToEdges {
766 /// Id of the window to maximize.
767 ///
768 /// If `None`, uses the focused window.
769 #[cfg_attr(feature = "clap", arg(long))]
770 id: Option<u64>,
771 },
772 /// Change the width of the focused column.
773 SetColumnWidth {
774 /// How to change the width.
775 #[cfg_attr(feature = "clap", arg(allow_hyphen_values = true))]
776 change: SizeChange,
777 },
778 /// Expand the focused column to space not taken up by other fully visible columns.
779 ExpandColumnToAvailableWidth {},
780 /// Switch between keyboard layouts.
781 SwitchLayout {
782 /// Layout to switch to.
783 #[cfg_attr(feature = "clap", arg())]
784 layout: LayoutSwitchTarget,
785 },
786 /// Show the hotkey overlay.
787 ShowHotkeyOverlay {},
788 /// Move the focused workspace to the monitor to the left.
789 MoveWorkspaceToMonitorLeft {},
790 /// Move the focused workspace to the monitor to the right.
791 MoveWorkspaceToMonitorRight {},
792 /// Move the focused workspace to the monitor below.
793 MoveWorkspaceToMonitorDown {},
794 /// Move the focused workspace to the monitor above.
795 MoveWorkspaceToMonitorUp {},
796 /// Move the focused workspace to the previous monitor.
797 MoveWorkspaceToMonitorPrevious {},
798 /// Move the focused workspace to the next monitor.
799 MoveWorkspaceToMonitorNext {},
800 /// Move a workspace to a specific monitor.
801 #[cfg_attr(
802 feature = "clap",
803 clap(about = "Move the focused workspace to a specific monitor")
804 )]
805 MoveWorkspaceToMonitor {
806 /// The target output name.
807 #[cfg_attr(feature = "clap", arg())]
808 output: String,
809
810 // Reference (index or name) of the workspace to move.
811 ///
812 /// If `None`, uses the focused workspace.
813 #[cfg_attr(feature = "clap", arg(long))]
814 reference: Option<WorkspaceReferenceArg>,
815 },
816 /// Toggle a debug tint on windows.
817 ToggleDebugTint {},
818 /// Toggle visualization of render element opaque regions.
819 DebugToggleOpaqueRegions {},
820 /// Toggle visualization of output damage.
821 DebugToggleDamage {},
822 /// Toggle the touchpad on/off at runtime.
823 ToggleTouchpad {},
824 /// Move the focused window between the floating and the tiling layout.
825 ToggleWindowFloating {
826 /// Id of the window to move.
827 ///
828 /// If `None`, uses the focused window.
829 #[cfg_attr(feature = "clap", arg(long))]
830 id: Option<u64>,
831 },
832 /// Move the focused window to the floating layout.
833 MoveWindowToFloating {
834 /// Id of the window to move.
835 ///
836 /// If `None`, uses the focused window.
837 #[cfg_attr(feature = "clap", arg(long))]
838 id: Option<u64>,
839 },
840 /// Move the focused window to the tiling layout.
841 MoveWindowToTiling {
842 /// Id of the window to move.
843 ///
844 /// If `None`, uses the focused window.
845 #[cfg_attr(feature = "clap", arg(long))]
846 id: Option<u64>,
847 },
848 /// Switches focus to the floating layout.
849 FocusFloating {},
850 /// Switches focus to the tiling layout.
851 FocusTiling {},
852 /// Toggles the focus between the floating and the tiling layout.
853 SwitchFocusBetweenFloatingAndTiling {},
854 /// Move a floating window on screen.
855 #[cfg_attr(feature = "clap", clap(about = "Move the floating window on screen"))]
856 MoveFloatingWindow {
857 /// Id of the window to move.
858 ///
859 /// If `None`, uses the focused window.
860 #[cfg_attr(feature = "clap", arg(long))]
861 id: Option<u64>,
862
863 /// How to change the X position.
864 #[serde(default = "default_position_change")]
865 #[cfg_attr(
866 feature = "clap",
867 arg(short, long, default_value = "+0", allow_hyphen_values = true)
868 )]
869 x: PositionChange,
870
871 /// How to change the Y position.
872 #[serde(default = "default_position_change")]
873 #[cfg_attr(
874 feature = "clap",
875 arg(short, long, default_value = "+0", allow_hyphen_values = true)
876 )]
877 y: PositionChange,
878 },
879 /// Toggle the opacity of a window.
880 #[cfg_attr(
881 feature = "clap",
882 clap(about = "Toggle the opacity of the focused window")
883 )]
884 ToggleWindowRuleOpacity {
885 /// Id of the window.
886 ///
887 /// If `None`, uses the focused window.
888 #[cfg_attr(feature = "clap", arg(long))]
889 id: Option<u64>,
890 },
891 /// Set the dynamic cast target to a window.
892 #[cfg_attr(
893 feature = "clap",
894 clap(about = "Set the dynamic cast target to the focused window")
895 )]
896 SetDynamicCastWindow {
897 /// Id of the window to target.
898 ///
899 /// If `None`, uses the focused window.
900 #[cfg_attr(feature = "clap", arg(long))]
901 id: Option<u64>,
902 },
903 /// Set the dynamic cast target to a monitor.
904 #[cfg_attr(
905 feature = "clap",
906 clap(about = "Set the dynamic cast target to the focused monitor")
907 )]
908 SetDynamicCastMonitor {
909 /// Name of the output to target.
910 ///
911 /// If `None`, uses the focused output.
912 #[cfg_attr(feature = "clap", arg())]
913 output: Option<String>,
914 },
915 /// Clear the dynamic cast target, making it show nothing.
916 ClearDynamicCastTarget {},
917 /// Stop a PipeWire screencast.
918 ///
919 /// wlr-screencopy screencasts cannot currently be stopped via IPC.
920 StopCast {
921 /// Session ID of the screencast to stop.
922 ///
923 /// If the session has multiple screencast streams, this will stop all of them.
924 #[cfg_attr(feature = "clap", arg(long))]
925 session_id: u64,
926 },
927 /// Toggle (open/close) the Overview.
928 ToggleOverview {},
929 /// Open the Overview.
930 OpenOverview {},
931 /// Close the Overview.
932 CloseOverview {},
933 /// Toggle urgent status of a window.
934 ToggleWindowUrgent {
935 /// Id of the window to toggle urgent.
936 #[cfg_attr(feature = "clap", arg(long))]
937 id: u64,
938 },
939 /// Set urgent status of a window.
940 SetWindowUrgent {
941 /// Id of the window to set urgent.
942 #[cfg_attr(feature = "clap", arg(long))]
943 id: u64,
944 },
945 /// Unset urgent status of a window.
946 UnsetWindowUrgent {
947 /// Id of the window to unset urgent.
948 #[cfg_attr(feature = "clap", arg(long))]
949 id: u64,
950 },
951 /// Reload the config file.
952 ///
953 /// Can be useful for scripts changing the config file, to avoid waiting the small duration for
954 /// niri's config file watcher to notice the changes.
955 LoadConfigFile {
956 /// Path of a new config file to load.
957 ///
958 /// If unset, reloads the current config file.
959 #[cfg_attr(feature = "clap", arg(long))]
960 path: Option<String>,
961 },
962}
963
964/// Change in window or column size.
965#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
966#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
967pub enum SizeChange {
968 /// Set the size in logical pixels.
969 SetFixed(i32),
970 /// Set the size as a proportion of the working area.
971 SetProportion(f64),
972 /// Add or subtract to the current size in logical pixels.
973 AdjustFixed(i32),
974 /// Add or subtract to the current size as a proportion of the working area.
975 AdjustProportion(f64),
976}
977
978/// Change in floating window position.
979#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
980#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
981pub enum PositionChange {
982 /// Set the position in logical pixels.
983 SetFixed(f64),
984 /// Set the position as a proportion of the working area.
985 SetProportion(f64),
986 /// Add or subtract to the current position in logical pixels.
987 AdjustFixed(f64),
988 /// Add or subtract to the current position as a proportion of the working area.
989 AdjustProportion(f64),
990}
991
992/// Workspace reference (id, index or name) to operate on.
993#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
994#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
995pub enum WorkspaceReferenceArg {
996 /// Id of the workspace.
997 Id(u64),
998 /// Index of the workspace.
999 Index(u8),
1000 /// Name of the workspace.
1001 Name(String),
1002}
1003
1004/// Layout to switch to.
1005#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1006#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1007pub enum LayoutSwitchTarget {
1008 /// The next configured layout.
1009 Next,
1010 /// The previous configured layout.
1011 Prev,
1012 /// The specific layout by index.
1013 Index(u8),
1014}
1015
1016/// How windows display in a column.
1017#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1018#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1019pub enum ColumnDisplay {
1020 /// Windows are tiled vertically across the working area height.
1021 Normal,
1022 /// Windows are in tabs.
1023 Tabbed,
1024}
1025
1026/// Output actions that niri can perform.
1027// Variants in this enum should match the spelling of the ones in niri-config. Most thigs from
1028// niri-config should be present here.
1029#[derive(Serialize, Deserialize, Debug, Clone)]
1030#[cfg_attr(feature = "clap", derive(clap::Parser))]
1031#[cfg_attr(feature = "clap", command(subcommand_value_name = "ACTION"))]
1032#[cfg_attr(feature = "clap", command(subcommand_help_heading = "Actions"))]
1033#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1034pub enum OutputAction {
1035 /// Turn off the output.
1036 Off,
1037 /// Turn on the output.
1038 On,
1039 /// Set the output mode.
1040 Mode {
1041 /// Mode to set, or "auto" for automatic selection.
1042 ///
1043 /// Run `niri msg outputs` to see the available modes.
1044 #[cfg_attr(feature = "clap", arg())]
1045 mode: ModeToSet,
1046 },
1047 /// Set a custom output mode.
1048 CustomMode {
1049 /// Custom mode to set.
1050 #[cfg_attr(feature = "clap", arg())]
1051 mode: ConfiguredMode,
1052 },
1053 /// Set a custom VESA CVT modeline.
1054 #[cfg_attr(feature = "clap", arg())]
1055 Modeline {
1056 /// The rate at which pixels are drawn in MHz.
1057 #[cfg_attr(feature = "clap", arg())]
1058 clock: f64,
1059 /// Horizontal active pixels.
1060 #[cfg_attr(feature = "clap", arg())]
1061 hdisplay: u16,
1062 /// Horizontal sync pulse start position in pixels.
1063 #[cfg_attr(feature = "clap", arg())]
1064 hsync_start: u16,
1065 /// Horizontal sync pulse end position in pixels.
1066 #[cfg_attr(feature = "clap", arg())]
1067 hsync_end: u16,
1068 /// Total horizontal number of pixels before resetting the horizontal drawing position to
1069 /// zero.
1070 #[cfg_attr(feature = "clap", arg())]
1071 htotal: u16,
1072
1073 /// Vertical active pixels.
1074 #[cfg_attr(feature = "clap", arg())]
1075 vdisplay: u16,
1076 /// Vertical sync pulse start position in pixels.
1077 #[cfg_attr(feature = "clap", arg())]
1078 vsync_start: u16,
1079 /// Vertical sync pulse end position in pixels.
1080 #[cfg_attr(feature = "clap", arg())]
1081 vsync_end: u16,
1082 /// Total vertical number of pixels before resetting the vertical drawing position to zero.
1083 #[cfg_attr(feature = "clap", arg())]
1084 vtotal: u16,
1085 /// Horizontal sync polarity: "+hsync" or "-hsync".
1086 #[cfg_attr(feature = "clap", arg(allow_hyphen_values = true))]
1087 hsync_polarity: HSyncPolarity,
1088 /// Vertical sync polarity: "+vsync" or "-vsync".
1089 #[cfg_attr(feature = "clap", arg(allow_hyphen_values = true))]
1090 vsync_polarity: VSyncPolarity,
1091 },
1092 /// Set the output scale.
1093 Scale {
1094 /// Scale factor to set, or "auto" for automatic selection.
1095 #[cfg_attr(feature = "clap", arg())]
1096 scale: ScaleToSet,
1097 },
1098 /// Set the output transform.
1099 Transform {
1100 /// Transform to set, counter-clockwise.
1101 #[cfg_attr(feature = "clap", arg())]
1102 transform: Transform,
1103 },
1104 /// Set the output position.
1105 Position {
1106 /// Position to set, or "auto" for automatic selection.
1107 #[cfg_attr(feature = "clap", command(subcommand))]
1108 position: PositionToSet,
1109 },
1110 /// Set the variable refresh rate mode.
1111 Vrr {
1112 /// Variable refresh rate mode to set.
1113 #[cfg_attr(feature = "clap", command(flatten))]
1114 vrr: VrrToSet,
1115 },
1116 /// Set the maximum bits per channel (bit depth).
1117 MaxBpc {
1118 /// Maximum bits per channel to set.
1119 #[cfg_attr(feature = "clap", arg())]
1120 max_bpc: MaxBpc,
1121 },
1122}
1123
1124/// Output mode to set.
1125#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
1126#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1127pub enum ModeToSet {
1128 /// Niri will pick the mode automatically.
1129 Automatic,
1130 /// Specific mode.
1131 Specific(ConfiguredMode),
1132}
1133
1134/// Output mode as set in the config file.
1135#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
1136#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1137pub struct ConfiguredMode {
1138 /// Width in physical pixels.
1139 pub width: u16,
1140 /// Height in physical pixels.
1141 pub height: u16,
1142 /// Refresh rate.
1143 pub refresh: Option<f64>,
1144}
1145
1146/// Modeline horizontal syncing polarity.
1147#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1148#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1149pub enum HSyncPolarity {
1150 /// Positive polarity.
1151 PHSync,
1152 /// Negative polarity.
1153 NHSync,
1154}
1155
1156/// Modeline vertical syncing polarity.
1157#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1158#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1159pub enum VSyncPolarity {
1160 /// Positive polarity.
1161 PVSync,
1162 /// Negative polarity.
1163 NVSync,
1164}
1165
1166/// Output scale to set.
1167#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
1168#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1169pub enum ScaleToSet {
1170 /// Niri will pick the scale automatically.
1171 Automatic,
1172 /// Specific scale.
1173 Specific(f64),
1174}
1175
1176/// Output position to set.
1177#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
1178#[cfg_attr(feature = "clap", derive(clap::Subcommand))]
1179#[cfg_attr(feature = "clap", command(subcommand_value_name = "POSITION"))]
1180#[cfg_attr(feature = "clap", command(subcommand_help_heading = "Position Values"))]
1181#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1182pub enum PositionToSet {
1183 /// Position the output automatically.
1184 #[cfg_attr(feature = "clap", command(name = "auto"))]
1185 Automatic,
1186 /// Set a specific position.
1187 #[cfg_attr(feature = "clap", command(name = "set"))]
1188 Specific(ConfiguredPosition),
1189}
1190
1191/// Output position as set in the config file.
1192#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
1193#[cfg_attr(feature = "clap", derive(clap::Args))]
1194#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1195pub struct ConfiguredPosition {
1196 /// Logical X position.
1197 pub x: i32,
1198 /// Logical Y position.
1199 pub y: i32,
1200}
1201
1202/// Output VRR to set.
1203#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
1204#[cfg_attr(feature = "clap", derive(clap::Args))]
1205#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1206pub struct VrrToSet {
1207 /// Whether to enable variable refresh rate.
1208 #[cfg_attr(
1209 feature = "clap",
1210 arg(
1211 value_name = "ON|OFF",
1212 action = clap::ArgAction::Set,
1213 value_parser = clap::builder::BoolishValueParser::new(),
1214 hide_possible_values = true,
1215 ),
1216 )]
1217 pub vrr: bool,
1218 /// Only enable when the output shows a window matching the variable-refresh-rate window rule.
1219 #[serde(default)]
1220 #[cfg_attr(feature = "clap", arg(long))]
1221 pub on_demand: bool,
1222}
1223
1224/// Connected output.
1225#[derive(Debug, Serialize, Deserialize, Clone)]
1226#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1227pub struct Output {
1228 /// Name of the output.
1229 pub name: String,
1230 /// Textual description of the manufacturer.
1231 pub make: String,
1232 /// Textual description of the model.
1233 pub model: String,
1234 /// Serial of the output, if known.
1235 pub serial: Option<String>,
1236 /// Physical width and height of the output in millimeters, if known.
1237 pub physical_size: Option<(u32, u32)>,
1238 /// Available modes for the output.
1239 pub modes: Vec<Mode>,
1240 /// Index of the current mode in [`Self::modes`].
1241 ///
1242 /// `None` if the output is disabled.
1243 pub current_mode: Option<usize>,
1244 /// Whether the current_mode is a custom mode.
1245 pub is_custom_mode: bool,
1246 /// Whether the output supports variable refresh rate.
1247 pub vrr_supported: bool,
1248 /// Whether variable refresh rate is enabled on the output.
1249 pub vrr_enabled: bool,
1250 /// Logical output information.
1251 ///
1252 /// `None` if the output is not mapped to any logical output (for example, if it is disabled).
1253 pub logical: Option<LogicalOutput>,
1254 /// Maximum bits per channel (bit depth), if known.
1255 pub max_bpc: Option<u8>,
1256}
1257
1258/// Output mode.
1259#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
1260#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1261pub struct Mode {
1262 /// Width in physical pixels.
1263 pub width: u16,
1264 /// Height in physical pixels.
1265 pub height: u16,
1266 /// Refresh rate in millihertz.
1267 pub refresh_rate: u32,
1268 /// Whether this mode is preferred by the monitor.
1269 pub is_preferred: bool,
1270}
1271
1272/// Logical output in the compositor's coordinate space.
1273#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
1274#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1275pub struct LogicalOutput {
1276 /// Logical X position.
1277 pub x: i32,
1278 /// Logical Y position.
1279 pub y: i32,
1280 /// Width in logical pixels.
1281 pub width: u32,
1282 /// Height in logical pixels.
1283 pub height: u32,
1284 /// Scale factor.
1285 pub scale: f64,
1286 /// Transform.
1287 pub transform: Transform,
1288}
1289
1290/// Output transform, which goes counter-clockwise.
1291#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1292#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
1293#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1294pub enum Transform {
1295 /// Untransformed.
1296 Normal,
1297 /// Rotated by 90°.
1298 #[serde(rename = "90")]
1299 _90,
1300 /// Rotated by 180°.
1301 #[serde(rename = "180")]
1302 _180,
1303 /// Rotated by 270°.
1304 #[serde(rename = "270")]
1305 _270,
1306 /// Flipped horizontally.
1307 Flipped,
1308 /// Rotated by 90° and flipped horizontally.
1309 #[cfg_attr(feature = "clap", value(name("flipped-90")))]
1310 Flipped90,
1311 /// Flipped vertically.
1312 #[cfg_attr(feature = "clap", value(name("flipped-180")))]
1313 Flipped180,
1314 /// Rotated by 270° and flipped horizontally.
1315 #[cfg_attr(feature = "clap", value(name("flipped-270")))]
1316 Flipped270,
1317}
1318
1319/// Output maximum bits per channel.
1320#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
1321#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
1322#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1323pub enum MaxBpc {
1324 /// 6-bit.
1325 #[serde(rename = "6")]
1326 _6 = 6,
1327 /// 8-bit.
1328 #[default]
1329 #[serde(rename = "8")]
1330 _8 = 8,
1331 /// 10-bit.
1332 #[serde(rename = "10")]
1333 _10 = 10,
1334 /// 12-bit.
1335 #[serde(rename = "12")]
1336 _12 = 12,
1337 /// 14-bit.
1338 #[serde(rename = "14")]
1339 _14 = 14,
1340 /// 16-bit.
1341 #[serde(rename = "16")]
1342 _16 = 16,
1343}
1344
1345/// Toplevel window.
1346#[derive(Serialize, Deserialize, Debug, Clone)]
1347#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1348pub struct Window {
1349 /// Unique id of this window.
1350 ///
1351 /// This id remains constant while this window is open.
1352 ///
1353 /// Do not assume that window ids will always increase without wrapping, or start at 1. That is
1354 /// an implementation detail subject to change. For example, ids may change to be randomly
1355 /// generated for each new window.
1356 pub id: u64,
1357 /// Title, if set.
1358 pub title: Option<String>,
1359 /// Application ID, if set.
1360 pub app_id: Option<String>,
1361 /// Process ID that created the Wayland connection for this window, if known.
1362 ///
1363 /// Currently, windows created by xdg-desktop-portal-gnome will have a `None` PID, but this may
1364 /// change in the future.
1365 pub pid: Option<i32>,
1366 /// Id of the workspace this window is on, if any.
1367 pub workspace_id: Option<u64>,
1368 /// Whether this window is currently focused.
1369 ///
1370 /// There can be either one focused window or zero (e.g. when a layer-shell surface has focus).
1371 pub is_focused: bool,
1372 /// Whether this window is currently floating.
1373 ///
1374 /// If the window isn't floating then it is in the tiling layout.
1375 pub is_floating: bool,
1376 /// Whether this window requests your attention.
1377 pub is_urgent: bool,
1378 /// Position- and size-related properties of the window.
1379 pub layout: WindowLayout,
1380 /// Timestamp when the window was most recently focused.
1381 ///
1382 /// This timestamp is intended for most-recently-used window switchers, i.e. Alt-Tab. It only
1383 /// updates after some debounce time so that quick window switching doesn't mark intermediate
1384 /// windows as recently focused.
1385 ///
1386 /// The timestamp comes from the monotonic clock.
1387 pub focus_timestamp: Option<Timestamp>,
1388}
1389
1390/// A moment in time.
1391#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1392#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1393pub struct Timestamp {
1394 /// Number of whole seconds.
1395 pub secs: u64,
1396 /// Fractional part of the timestamp in nanoseconds (10<sup>-9</sup> seconds).
1397 pub nanos: u32,
1398}
1399
1400/// Position- and size-related properties of a [`Window`].
1401///
1402/// Optional properties will be unset for some windows, do not rely on them being present. Whether
1403/// some optional properties are present or absent for certain window types may change across niri
1404/// releases.
1405///
1406/// All sizes and positions are in *logical pixels* unless stated otherwise. Logical sizes may be
1407/// fractional. For example, at 1.25 monitor scale, a 2-physical-pixel-wide window border is 1.6
1408/// logical pixels wide.
1409///
1410/// This struct contains positions and sizes both for full tiles ([`Self::tile_size`],
1411/// [`Self::tile_pos_in_workspace_view`]) and the window geometry ([`Self::window_size`],
1412/// [`Self::window_offset_in_tile`]). For visual displays, use the tile properties, as they
1413/// correspond to what the user visually considers "window". The window properties on the other
1414/// hand are mainly useful when you need to know the underlying Wayland window sizes, e.g. for
1415/// application debugging.
1416#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1417#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1418pub struct WindowLayout {
1419 /// Location of a tiled window within a workspace: (column index, tile index in column).
1420 ///
1421 /// The indices are 1-based, i.e. the leftmost column is at index 1 and the topmost tile in a
1422 /// column is at index 1. This is consistent with [`Action::FocusColumn`] and
1423 /// [`Action::FocusWindowInColumn`].
1424 pub pos_in_scrolling_layout: Option<(usize, usize)>,
1425 /// Size of the tile this window is in, including decorations like borders.
1426 pub tile_size: (f64, f64),
1427 /// Size of the window's visual geometry itself.
1428 ///
1429 /// Does not include niri decorations like borders.
1430 ///
1431 /// Currently, Wayland toplevel windows can only be integer-sized in logical pixels, even
1432 /// though it doesn't necessarily align to physical pixels.
1433 pub window_size: (i32, i32),
1434 /// Tile position within the current view of the workspace.
1435 ///
1436 /// This is the same "workspace view" as in gradients' `relative-to` in the niri config.
1437 pub tile_pos_in_workspace_view: Option<(f64, f64)>,
1438 /// Location of the window's visual geometry within its tile.
1439 ///
1440 /// This includes things like border sizes. For fullscreened fixed-size windows this includes
1441 /// the distance from the corner of the black backdrop to the corner of the (centered) window
1442 /// contents.
1443 pub window_offset_in_tile: (f64, f64),
1444}
1445
1446/// Output configuration change result.
1447#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1448#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1449pub enum OutputConfigChanged {
1450 /// The target output was connected and the change was applied.
1451 Applied,
1452 /// The target output was not found, the change will be applied when it is connected.
1453 OutputWasMissing,
1454}
1455
1456/// A workspace.
1457#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1458#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1459pub struct Workspace {
1460 /// Unique id of this workspace.
1461 ///
1462 /// This id remains constant regardless of the workspace moving around and across monitors.
1463 ///
1464 /// Do not assume that workspace ids will always increase without wrapping, or start at 1. That
1465 /// is an implementation detail subject to change. For example, ids may change to be randomly
1466 /// generated for each new workspace.
1467 pub id: u64,
1468 /// Index of the workspace on its monitor.
1469 ///
1470 /// This is the same index you can use for requests like `niri msg action focus-workspace`.
1471 ///
1472 /// This index *will change* as you move and re-order workspace. It is merely the workspace's
1473 /// current position on its monitor. Workspaces on different monitors can have the same index.
1474 ///
1475 /// If you need a unique workspace id that doesn't change, see [`Self::id`].
1476 pub idx: u8,
1477 /// Optional name of the workspace.
1478 pub name: Option<String>,
1479 /// Name of the output that the workspace is on.
1480 ///
1481 /// Can be `None` if no outputs are currently connected.
1482 pub output: Option<String>,
1483 /// Whether the workspace currently has an urgent window in its output.
1484 pub is_urgent: bool,
1485 /// Whether the workspace is currently active on its output.
1486 ///
1487 /// Every output has one active workspace, the one that is currently visible on that output.
1488 pub is_active: bool,
1489 /// Whether the workspace is currently focused.
1490 ///
1491 /// There's only one focused workspace across all outputs.
1492 pub is_focused: bool,
1493 /// Id of the active window on this workspace, if any.
1494 pub active_window_id: Option<u64>,
1495}
1496
1497/// Configured keyboard layouts.
1498#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1499#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1500pub struct KeyboardLayouts {
1501 /// XKB names of the configured layouts.
1502 pub names: Vec<String>,
1503 /// Index of the currently active layout in `names`.
1504 pub current_idx: u8,
1505}
1506
1507/// A layer-shell layer.
1508#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1509#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1510pub enum Layer {
1511 /// The background layer.
1512 Background,
1513 /// The bottom layer.
1514 Bottom,
1515 /// The top layer.
1516 Top,
1517 /// The overlay layer.
1518 Overlay,
1519}
1520
1521/// Keyboard interactivity modes for a layer-shell surface.
1522#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1523#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1524pub enum LayerSurfaceKeyboardInteractivity {
1525 /// Surface cannot receive keyboard focus.
1526 None,
1527 /// Surface receives keyboard focus whenever possible.
1528 Exclusive,
1529 /// Surface receives keyboard focus on demand, e.g. when clicked.
1530 OnDemand,
1531}
1532
1533/// A layer-shell surface.
1534#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1535#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1536pub struct LayerSurface {
1537 /// Namespace provided by the layer-shell client.
1538 pub namespace: String,
1539 /// Name of the output the surface is on.
1540 pub output: String,
1541 /// Layer that the surface is on.
1542 pub layer: Layer,
1543 /// The surface's keyboard interactivity mode.
1544 pub keyboard_interactivity: LayerSurfaceKeyboardInteractivity,
1545}
1546
1547/// A screencast.
1548#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1549#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1550pub struct Cast {
1551 /// Stream ID of the screencast that uniquely identifies it.
1552 pub stream_id: u64,
1553 /// Session ID of the screencast.
1554 ///
1555 /// A session can have multiple screencast streams. Then multiple `Cast`s will have the same
1556 /// `session_id`. Though, usually there's only one stream per session.
1557 ///
1558 /// Do not confuse `session_id` with [`stream_id`](Self::stream_id).
1559 pub session_id: u64,
1560 /// Kind of this screencast.
1561 pub kind: CastKind,
1562 /// Target being captured.
1563 pub target: CastTarget,
1564 /// Whether this is a Dynamic Cast Target screencast.
1565 ///
1566 /// Meaning that actions like `SetDynamicCastWindow` will act on this screencast.
1567 ///
1568 /// Keep in mind that the target can change even if this is `false`.
1569 pub is_dynamic_target: bool,
1570 /// Whether the cast is currently streaming frames.
1571 ///
1572 /// This can be `false` for example when switching away to a different scene in OBS, which
1573 /// pauses the stream.
1574 pub is_active: bool,
1575 /// Process ID of the screencast consumer, if known.
1576 ///
1577 /// Currently, only wlr-screencopy screencasts can have a pid.
1578 pub pid: Option<i32>,
1579 /// PipeWire node ID of the screencast stream.
1580 ///
1581 /// This is `None` for wlr-screencopy casts, and also for PipeWire casts before the node is
1582 /// created (when the cast is just starting up).
1583 pub pw_node_id: Option<u32>,
1584}
1585
1586/// Kind of screencast.
1587#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
1588#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1589pub enum CastKind {
1590 /// PipeWire screencast, typically via xdg-desktop-portal-gnome.
1591 PipeWire,
1592 /// wlr-screencopy protocol screencast.
1593 ///
1594 /// Tools like wf-recorder, and the xdg-desktop-portal-wlr portal.
1595 ///
1596 /// Only wlr-screencopy with damage tracking is reported here. Screencopy without damage is
1597 /// treated as a regular screenshot and not reported as a screencast.
1598 WlrScreencopy,
1599 /// ext-image-copy-capture protocol screencast.
1600 ///
1601 /// Tools like wayvnc, wl-mirror, and the xdg-desktop-portal-wlr portal.
1602 ///
1603 /// A client capturing both an output and the cursor creates two sessions, which are reported
1604 /// as two `Cast`s sharing one [`session_id`](Cast::session_id).
1605 ExtImageCopyCapture,
1606}
1607
1608/// Target of a screencast.
1609#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1610#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1611pub enum CastTarget {
1612 /// The target is not yet set, or was cleared.
1613 Nothing {},
1614 /// Casting an output.
1615 Output {
1616 /// Name of the screencasted output.
1617 name: String,
1618 },
1619 /// Casting a window.
1620 Window {
1621 /// ID of the screencasted window.
1622 id: u64,
1623 },
1624}
1625
1626/// A compositor event.
1627#[derive(Serialize, Deserialize, Debug, Clone)]
1628#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1629pub enum Event {
1630 /// The workspace configuration has changed.
1631 WorkspacesChanged {
1632 /// The new workspace configuration.
1633 ///
1634 /// This configuration completely replaces the previous configuration. I.e. if any
1635 /// workspaces are missing from here, then they were deleted.
1636 workspaces: Vec<Workspace>,
1637 },
1638 /// The workspace urgency changed.
1639 WorkspaceUrgencyChanged {
1640 /// Id of the workspace.
1641 id: u64,
1642 /// Whether this workspace has an urgent window.
1643 urgent: bool,
1644 },
1645 /// A workspace was activated on an output.
1646 ///
1647 /// This doesn't always mean the workspace became focused, just that it's now the active
1648 /// workspace on its output. All other workspaces on the same output become inactive.
1649 WorkspaceActivated {
1650 /// Id of the newly active workspace.
1651 id: u64,
1652 /// Whether this workspace also became focused.
1653 ///
1654 /// If `true`, this is now the single focused workspace. All other workspaces are no longer
1655 /// focused, but they may remain active on their respective outputs.
1656 focused: bool,
1657 },
1658 /// An active window changed on a workspace.
1659 WorkspaceActiveWindowChanged {
1660 /// Id of the workspace on which the active window changed.
1661 workspace_id: u64,
1662 /// Id of the new active window, if any.
1663 active_window_id: Option<u64>,
1664 },
1665 /// The window configuration has changed.
1666 WindowsChanged {
1667 /// The new window configuration.
1668 ///
1669 /// This configuration completely replaces the previous configuration. I.e. if any windows
1670 /// are missing from here, then they were closed.
1671 windows: Vec<Window>,
1672 },
1673 /// A new toplevel window was opened, or an existing toplevel window changed.
1674 WindowOpenedOrChanged {
1675 /// The new or updated window.
1676 ///
1677 /// If the window is focused, all other windows are no longer focused.
1678 window: Window,
1679 },
1680 /// A toplevel window was closed.
1681 WindowClosed {
1682 /// Id of the removed window.
1683 id: u64,
1684 },
1685 /// Window focus changed.
1686 ///
1687 /// All other windows are no longer focused.
1688 WindowFocusChanged {
1689 /// Id of the newly focused window, or `None` if no window is now focused.
1690 id: Option<u64>,
1691 },
1692 /// Window focus timestamp changed.
1693 ///
1694 /// This event is separate from [`Event::WindowFocusChanged`] because the focus timestamp only
1695 /// updates after some debounce time so that quick window switching doesn't mark intermediate
1696 /// windows as recently focused.
1697 WindowFocusTimestampChanged {
1698 /// Id of the window.
1699 id: u64,
1700 /// The new focus timestamp.
1701 focus_timestamp: Option<Timestamp>,
1702 },
1703 /// Window urgency changed.
1704 WindowUrgencyChanged {
1705 /// Id of the window.
1706 id: u64,
1707 /// The new urgency state of the window.
1708 urgent: bool,
1709 },
1710 /// The layout of one or more windows has changed.
1711 WindowLayoutsChanged {
1712 /// Pairs consisting of a window id and new layout information for the window.
1713 changes: Vec<(u64, WindowLayout)>,
1714 },
1715 /// The configured keyboard layouts have changed.
1716 KeyboardLayoutsChanged {
1717 /// The new keyboard layout configuration.
1718 keyboard_layouts: KeyboardLayouts,
1719 },
1720 /// The keyboard layout switched.
1721 KeyboardLayoutSwitched {
1722 /// Index of the newly active layout.
1723 idx: u8,
1724 },
1725 /// The overview was opened or closed.
1726 OverviewOpenedOrClosed {
1727 /// The new state of the overview.
1728 is_open: bool,
1729 },
1730 /// The configuration was reloaded.
1731 ///
1732 /// You will always receive this event when connecting to the event stream, indicating the last
1733 /// config load attempt.
1734 ConfigLoaded {
1735 /// Whether the loading failed.
1736 ///
1737 /// For example, the config file couldn't be parsed.
1738 failed: bool,
1739 },
1740 /// A screenshot was captured.
1741 ScreenshotCaptured {
1742 /// The file path where the screenshot was saved, if it was written to disk.
1743 ///
1744 /// If `None`, the screenshot was either only copied to the clipboard, or the path couldn't
1745 /// be converted to a `String` (e.g. contained invalid UTF-8 bytes).
1746 path: Option<String>,
1747 },
1748 /// The screencasts have changed.
1749 CastsChanged {
1750 /// The new screencast information.
1751 ///
1752 /// This configuration completely replaces the previous configuration. I.e. if any casts
1753 /// are missing from here, then they were stopped.
1754 casts: Vec<Cast>,
1755 },
1756 /// A screencast started, or an existing cast changed.
1757 CastStartedOrChanged {
1758 /// The cast that started or changed.
1759 cast: Cast,
1760 },
1761 /// A screencast stopped.
1762 CastStopped {
1763 /// Stream ID of the stopped screencast.
1764 stream_id: u64,
1765 },
1766 /// Touchpad toggled on/off via [`Action::ToggleTouchpad`].
1767 TouchpadToggled {
1768 /// Whether the touchpad is now enabled.
1769 ///
1770 /// Note that this only indicates the [`Action::ToggleTouchpad`] state. The touchpad can be
1771 /// disabled in hardware, or via `input { touchpad { off; } }`—this is not reflected here.
1772 on: bool,
1773 },
1774}
1775
1776impl From<Duration> for Timestamp {
1777 fn from(value: Duration) -> Self {
1778 Timestamp {
1779 secs: value.as_secs(),
1780 nanos: value.subsec_nanos(),
1781 }
1782 }
1783}
1784
1785impl From<Timestamp> for Duration {
1786 fn from(value: Timestamp) -> Self {
1787 Duration::new(value.secs, value.nanos)
1788 }
1789}
1790
1791impl FromStr for WorkspaceReferenceArg {
1792 type Err = &'static str;
1793
1794 fn from_str(s: &str) -> Result<Self, Self::Err> {
1795 let reference = if let Ok(index) = s.parse::<i32>() {
1796 if let Ok(idx) = u8::try_from(index) {
1797 Self::Index(idx)
1798 } else {
1799 return Err("workspace index must be between 0 and 255");
1800 }
1801 } else {
1802 Self::Name(s.to_string())
1803 };
1804
1805 Ok(reference)
1806 }
1807}
1808
1809impl FromStr for SizeChange {
1810 type Err = &'static str;
1811
1812 fn from_str(s: &str) -> Result<Self, Self::Err> {
1813 match s.split_once('%') {
1814 Some((value, empty)) => {
1815 if !empty.is_empty() {
1816 return Err("trailing characters after '%' are not allowed");
1817 }
1818
1819 match value.bytes().next() {
1820 Some(b'-' | b'+') => {
1821 let value = value.parse().map_err(|_| "error parsing value")?;
1822 Ok(Self::AdjustProportion(value))
1823 }
1824 Some(_) => {
1825 let value = value.parse().map_err(|_| "error parsing value")?;
1826 Ok(Self::SetProportion(value))
1827 }
1828 None => Err("value is missing"),
1829 }
1830 }
1831 None => {
1832 let value = s;
1833 match value.bytes().next() {
1834 Some(b'-' | b'+') => {
1835 let value = value.parse().map_err(|_| "error parsing value")?;
1836 Ok(Self::AdjustFixed(value))
1837 }
1838 Some(_) => {
1839 let value = value.parse().map_err(|_| "error parsing value")?;
1840 Ok(Self::SetFixed(value))
1841 }
1842 None => Err("value is missing"),
1843 }
1844 }
1845 }
1846 }
1847}
1848
1849impl FromStr for PositionChange {
1850 type Err = &'static str;
1851
1852 fn from_str(s: &str) -> Result<Self, Self::Err> {
1853 match s.split_once('%') {
1854 Some((value, empty)) => {
1855 if !empty.is_empty() {
1856 return Err("trailing characters after '%' are not allowed");
1857 }
1858
1859 match value.bytes().next() {
1860 Some(b'-' | b'+') => {
1861 let value = value.parse().map_err(|_| "error parsing value")?;
1862 Ok(Self::AdjustProportion(value))
1863 }
1864 Some(_) => {
1865 let value = value.parse().map_err(|_| "error parsing value")?;
1866 Ok(Self::SetProportion(value))
1867 }
1868 None => Err("value is missing"),
1869 }
1870 }
1871 None => {
1872 let value = s;
1873 match value.bytes().next() {
1874 Some(b'-' | b'+') => {
1875 let value = value.parse().map_err(|_| "error parsing value")?;
1876 Ok(Self::AdjustFixed(value))
1877 }
1878 Some(_) => {
1879 let value = value.parse().map_err(|_| "error parsing value")?;
1880 Ok(Self::SetFixed(value))
1881 }
1882 None => Err("value is missing"),
1883 }
1884 }
1885 }
1886 }
1887}
1888
1889impl FromStr for LayoutSwitchTarget {
1890 type Err = &'static str;
1891
1892 fn from_str(s: &str) -> Result<Self, Self::Err> {
1893 match s {
1894 "next" => Ok(Self::Next),
1895 "prev" => Ok(Self::Prev),
1896 other => match other.parse() {
1897 Ok(layout) => Ok(Self::Index(layout)),
1898 _ => Err(r#"invalid layout action, can be "next", "prev" or a layout index"#),
1899 },
1900 }
1901 }
1902}
1903
1904impl FromStr for ColumnDisplay {
1905 type Err = &'static str;
1906
1907 fn from_str(s: &str) -> Result<Self, Self::Err> {
1908 match s {
1909 "normal" => Ok(Self::Normal),
1910 "tabbed" => Ok(Self::Tabbed),
1911 _ => Err(r#"invalid column display, can be "normal" or "tabbed""#),
1912 }
1913 }
1914}
1915
1916impl FromStr for Transform {
1917 type Err = &'static str;
1918
1919 fn from_str(s: &str) -> Result<Self, Self::Err> {
1920 match s {
1921 "normal" => Ok(Self::Normal),
1922 "90" => Ok(Self::_90),
1923 "180" => Ok(Self::_180),
1924 "270" => Ok(Self::_270),
1925 "flipped" => Ok(Self::Flipped),
1926 "flipped-90" => Ok(Self::Flipped90),
1927 "flipped-180" => Ok(Self::Flipped180),
1928 "flipped-270" => Ok(Self::Flipped270),
1929 _ => Err(concat!(
1930 r#"invalid transform, can be "90", "180", "270", "#,
1931 r#""flipped", "flipped-90", "flipped-180" or "flipped-270""#
1932 )),
1933 }
1934 }
1935}
1936
1937impl TryFrom<u8> for MaxBpc {
1938 type Error = &'static str;
1939
1940 fn try_from(value: u8) -> Result<Self, Self::Error> {
1941 match value {
1942 6 => Ok(MaxBpc::_6),
1943 8 => Ok(MaxBpc::_8),
1944 10 => Ok(MaxBpc::_10),
1945 12 => Ok(MaxBpc::_12),
1946 14 => Ok(MaxBpc::_14),
1947 16 => Ok(MaxBpc::_16),
1948 _ => Err("invalid max-bpc, can be 6, 8, 10, 12, 14, 16"),
1949 }
1950 }
1951}
1952
1953impl FromStr for MaxBpc {
1954 type Err = &'static str;
1955
1956 fn from_str(s: &str) -> Result<Self, Self::Err> {
1957 Self::try_from(s.parse::<u8>().unwrap_or_default())
1958 }
1959}
1960
1961impl FromStr for Layer {
1962 type Err = &'static str;
1963
1964 fn from_str(s: &str) -> Result<Self, Self::Err> {
1965 match s {
1966 "background" => Ok(Self::Background),
1967 "bottom" => Ok(Self::Bottom),
1968 "top" => Ok(Self::Top),
1969 "overlay" => Ok(Self::Overlay),
1970 _ => Err("invalid layer, can be \"background\", \"bottom\", \"top\" or \"overlay\""),
1971 }
1972 }
1973}
1974
1975impl FromStr for ModeToSet {
1976 type Err = &'static str;
1977
1978 fn from_str(s: &str) -> Result<Self, Self::Err> {
1979 if s.eq_ignore_ascii_case("auto") {
1980 return Ok(Self::Automatic);
1981 }
1982
1983 let mode = s.parse()?;
1984 Ok(Self::Specific(mode))
1985 }
1986}
1987
1988impl FromStr for ConfiguredMode {
1989 type Err = &'static str;
1990
1991 fn from_str(s: &str) -> Result<Self, Self::Err> {
1992 let Some((width, rest)) = s.split_once('x') else {
1993 return Err("no 'x' separator found");
1994 };
1995
1996 let (height, refresh) = match rest.split_once('@') {
1997 Some((height, refresh)) => (height, Some(refresh)),
1998 None => (rest, None),
1999 };
2000
2001 let width = width.parse().map_err(|_| "error parsing width")?;
2002 let height = height.parse().map_err(|_| "error parsing height")?;
2003 let refresh = refresh
2004 .map(str::parse)
2005 .transpose()
2006 .map_err(|_| "error parsing refresh rate")?;
2007
2008 Ok(Self {
2009 width,
2010 height,
2011 refresh,
2012 })
2013 }
2014}
2015
2016impl FromStr for HSyncPolarity {
2017 type Err = &'static str;
2018
2019 fn from_str(s: &str) -> Result<Self, Self::Err> {
2020 match s {
2021 "+hsync" => Ok(Self::PHSync),
2022 "-hsync" => Ok(Self::NHSync),
2023 _ => Err(r#"invalid horizontal sync polarity, can be "+hsync" or "-hsync"#),
2024 }
2025 }
2026}
2027
2028impl FromStr for VSyncPolarity {
2029 type Err = &'static str;
2030
2031 fn from_str(s: &str) -> Result<Self, Self::Err> {
2032 match s {
2033 "+vsync" => Ok(Self::PVSync),
2034 "-vsync" => Ok(Self::NVSync),
2035 _ => Err(r#"invalid vertical sync polarity, can be "+vsync" or "-vsync"#),
2036 }
2037 }
2038}
2039
2040impl FromStr for ScaleToSet {
2041 type Err = &'static str;
2042
2043 fn from_str(s: &str) -> Result<Self, Self::Err> {
2044 if s.eq_ignore_ascii_case("auto") {
2045 return Ok(Self::Automatic);
2046 }
2047
2048 let scale = s.parse().map_err(|_| "error parsing scale")?;
2049 Ok(Self::Specific(scale))
2050 }
2051}
2052
2053macro_rules! ensure {
2054 ($cond:expr, $fmt:literal $($arg:tt)* ) => {
2055 if !$cond {
2056 return Err(format!($fmt $($arg)*));
2057 }
2058 };
2059}
2060
2061impl OutputAction {
2062 /// Validates some required constraints on the modeline and custom mode.
2063 pub fn validate(&self) -> Result<(), String> {
2064 match self {
2065 OutputAction::Modeline {
2066 hdisplay,
2067 hsync_start,
2068 hsync_end,
2069 htotal,
2070 vdisplay,
2071 vsync_start,
2072 vsync_end,
2073 vtotal,
2074 ..
2075 } => {
2076 ensure!(
2077 hdisplay < hsync_start,
2078 "hdisplay {} must be < hsync_start {}",
2079 hdisplay,
2080 hsync_start
2081 );
2082 ensure!(
2083 hsync_start < hsync_end,
2084 "hsync_start {} must be < hsync_end {}",
2085 hsync_start,
2086 hsync_end
2087 );
2088 ensure!(
2089 hsync_end < htotal,
2090 "hsync_end {} must be < htotal {}",
2091 hsync_end,
2092 htotal
2093 );
2094 ensure!(0 < *htotal, "htotal {} must be > 0", htotal);
2095 ensure!(
2096 vdisplay < vsync_start,
2097 "vdisplay {} must be < vsync_start {}",
2098 vdisplay,
2099 vsync_start
2100 );
2101 ensure!(
2102 vsync_start < vsync_end,
2103 "vsync_start {} must be < vsync_end {}",
2104 vsync_start,
2105 vsync_end
2106 );
2107 ensure!(
2108 vsync_end < vtotal,
2109 "vsync_end {} must be < vtotal {}",
2110 vsync_end,
2111 vtotal
2112 );
2113 ensure!(0 < *vtotal, "vtotal {} must be > 0", vtotal);
2114 Ok(())
2115 }
2116 OutputAction::CustomMode {
2117 mode: ConfiguredMode { refresh, .. },
2118 } => {
2119 if refresh.is_none() {
2120 return Err("refresh rate is required for custom modes".to_string());
2121 }
2122 if let Some(refresh) = refresh {
2123 if *refresh <= 0. {
2124 return Err(format!("custom mode refresh rate {refresh} must be > 0"));
2125 }
2126 }
2127 Ok(())
2128 }
2129 _ => Ok(()),
2130 }
2131 }
2132}
2133
2134fn default_true() -> bool {
2135 true
2136}
2137
2138fn default_position_change() -> PositionChange {
2139 PositionChange::AdjustFixed(0.)
2140}
2141
2142#[cfg(test)]
2143mod tests {
2144 use super::*;
2145
2146 #[test]
2147 fn parse_size_change() {
2148 assert_eq!(
2149 "10".parse::<SizeChange>().unwrap(),
2150 SizeChange::SetFixed(10),
2151 );
2152 assert_eq!(
2153 "+10".parse::<SizeChange>().unwrap(),
2154 SizeChange::AdjustFixed(10),
2155 );
2156 assert_eq!(
2157 "-10".parse::<SizeChange>().unwrap(),
2158 SizeChange::AdjustFixed(-10),
2159 );
2160 assert_eq!(
2161 "10%".parse::<SizeChange>().unwrap(),
2162 SizeChange::SetProportion(10.),
2163 );
2164 assert_eq!(
2165 "+10%".parse::<SizeChange>().unwrap(),
2166 SizeChange::AdjustProportion(10.),
2167 );
2168 assert_eq!(
2169 "-10%".parse::<SizeChange>().unwrap(),
2170 SizeChange::AdjustProportion(-10.),
2171 );
2172
2173 assert!("-".parse::<SizeChange>().is_err());
2174 assert!("10% ".parse::<SizeChange>().is_err());
2175 }
2176
2177 #[test]
2178 fn parse_position_change() {
2179 assert_eq!(
2180 "10".parse::<PositionChange>().unwrap(),
2181 PositionChange::SetFixed(10.),
2182 );
2183 assert_eq!(
2184 "+10".parse::<PositionChange>().unwrap(),
2185 PositionChange::AdjustFixed(10.),
2186 );
2187 assert_eq!(
2188 "-10".parse::<PositionChange>().unwrap(),
2189 PositionChange::AdjustFixed(-10.),
2190 );
2191
2192 assert_eq!(
2193 "10%".parse::<PositionChange>().unwrap(),
2194 PositionChange::SetProportion(10.)
2195 );
2196 assert_eq!(
2197 "+10%".parse::<PositionChange>().unwrap(),
2198 PositionChange::AdjustProportion(10.)
2199 );
2200 assert_eq!(
2201 "-10%".parse::<PositionChange>().unwrap(),
2202 PositionChange::AdjustProportion(-10.)
2203 );
2204 assert!("-".parse::<PositionChange>().is_err());
2205 assert!("10% ".parse::<PositionChange>().is_err());
2206 }
2207}