Skip to main content

niri_ipc/
lib.rs

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