Add an IPC socket and a niri msg outputs subcommand
Browse files at this commit40c85da102054caeb86b7905cd27c69e392c8f92Parent: 768b32615 changed files +499 -12
- Cargo.lock +33 -0
- Cargo.toml +5 -1
- README.md +11 -0
- flake.nix +1 -0
- niri-ipc/Cargo.toml +11 -0
- niri-ipc/src/lib.rs +55 -0
- resources/default-config.kdl +3 -2
- src/backend/mod.rs +9 -0
- src/backend/tty.rs +68 -9
- src/backend/winit.rs +29 -0
- src/ipc/client.rs +106 -0
- src/ipc/mod.rs +2 -0
- src/ipc/server.rs +127 -0
- src/main.rs +26 -0
- src/niri.rs +13 -0
Cargo.lockmodified+33 -0
| @@ -1308,6 +1308,12 @@ version = "2.0.3" | |||
| 1308 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1308 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1309 | checksum = "5a611371471e98973dbcab4e0ec66c31a10bc356eeb4d54a0e05eac8158fe38c" | 1309 | checksum = "5a611371471e98973dbcab4e0ec66c31a10bc356eeb4d54a0e05eac8158fe38c" |
| 1310 | 1310 | ||
| 1311 | +[[package]] | ||
| 1312 | +name = "itoa" | ||
| 1313 | +version = "1.0.10" | ||
| 1314 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1315 | +checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" | ||
| 1316 | + | ||
| 1311 | [[package]] | 1317 | [[package]] |
| 1312 | name = "jni" | 1318 | name = "jni" |
| 1313 | version = "0.21.1" | 1319 | version = "0.21.1" |
| @@ -1705,12 +1711,14 @@ dependencies = [ | |||
| 1705 | "calloop", | 1711 | "calloop", |
| 1706 | "clap", | 1712 | "clap", |
| 1707 | "directories", | 1713 | "directories", |
| 1714 | + "futures-util", | ||
| 1708 | "git-version", | 1715 | "git-version", |
| 1709 | "keyframe", | 1716 | "keyframe", |
| 1710 | "libc", | 1717 | "libc", |
| 1711 | "log", | 1718 | "log", |
| 1712 | "logind-zbus", | 1719 | "logind-zbus", |
| 1713 | "niri-config", | 1720 | "niri-config", |
| 1721 | + "niri-ipc", | ||
| 1714 | "notify-rust", | 1722 | "notify-rust", |
| 1715 | "pipewire", | 1723 | "pipewire", |
| 1716 | "png", | 1724 | "png", |
| @@ -1720,6 +1728,7 @@ dependencies = [ | |||
| 1720 | "proptest-derive", | 1728 | "proptest-derive", |
| 1721 | "sd-notify", | 1729 | "sd-notify", |
| 1722 | "serde", | 1730 | "serde", |
| 1731 | + "serde_json", | ||
| 1723 | "smithay", | 1732 | "smithay", |
| 1724 | "smithay-drm-extras", | 1733 | "smithay-drm-extras", |
| 1725 | "tracing", | 1734 | "tracing", |
| @@ -1743,6 +1752,13 @@ dependencies = [ | |||
| 1743 | "tracy-client", | 1752 | "tracy-client", |
| 1744 | ] | 1753 | ] |
| 1745 | 1754 | ||
| 1755 | +[[package]] | ||
| 1756 | +name = "niri-ipc" | ||
| 1757 | +version = "0.1.0-alpha.3" | ||
| 1758 | +dependencies = [ | ||
| 1759 | + "serde", | ||
| 1760 | +] | ||
| 1761 | + | ||
| 1746 | [[package]] | 1762 | [[package]] |
| 1747 | name = "nix" | 1763 | name = "nix" |
| 1748 | version = "0.26.4" | 1764 | version = "0.26.4" |
| @@ -2331,6 +2347,12 @@ dependencies = [ | |||
| 2331 | "wait-timeout", | 2347 | "wait-timeout", |
| 2332 | ] | 2348 | ] |
| 2333 | 2349 | ||
| 2350 | +[[package]] | ||
| 2351 | +name = "ryu" | ||
| 2352 | +version = "1.0.16" | ||
| 2353 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2354 | +checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c" | ||
| 2355 | + | ||
| 2334 | [[package]] | 2356 | [[package]] |
| 2335 | name = "same-file" | 2357 | name = "same-file" |
| 2336 | version = "1.0.6" | 2358 | version = "1.0.6" |
| @@ -2378,6 +2400,17 @@ dependencies = [ | |||
| 2378 | "syn 2.0.48", | 2400 | "syn 2.0.48", |
| 2379 | ] | 2401 | ] |
| 2380 | 2402 | ||
| 2403 | +[[package]] | ||
| 2404 | +name = "serde_json" | ||
| 2405 | +version = "1.0.111" | ||
| 2406 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2407 | +checksum = "176e46fa42316f18edd598015a5166857fc835ec732f5215eac6b7bdbf0a84f4" | ||
| 2408 | +dependencies = [ | ||
| 2409 | + "itoa", | ||
| 2410 | + "ryu", | ||
| 2411 | + "serde", | ||
| 2412 | +] | ||
| 2413 | + | ||
| 2381 | [[package]] | 2414 | [[package]] |
| 2382 | name = "serde_repr" | 2415 | name = "serde_repr" |
| 2383 | version = "0.1.18" | 2416 | version = "0.1.18" |
Cargo.tomlmodified+5 -1
| @@ -9,6 +9,7 @@ repository = "https://github.com/YaLTeR/niri" | |||
| 9 | [workspace.dependencies] | 9 | [workspace.dependencies] |
| 10 | bitflags = "2.4.1" | 10 | bitflags = "2.4.1" |
| 11 | directories = "5.0.1" | 11 | directories = "5.0.1" |
| 12 | +serde = { version = "1.0.195", features = ["derive"] } | ||
| 12 | tracing = { version = "0.1.40", features = ["max_level_trace", "release_max_level_debug"] } | 13 | tracing = { version = "0.1.40", features = ["max_level_trace", "release_max_level_debug"] } |
| 13 | tracy-client = { version = "0.16.5", default-features = false } | 14 | tracy-client = { version = "0.16.5", default-features = false } |
| 14 | 15 | ||
| @@ -42,20 +43,23 @@ bitflags = "2.4.1" | |||
| 42 | calloop = { version = "0.12.3", features = ["executor", "futures-io"] } | 43 | calloop = { version = "0.12.3", features = ["executor", "futures-io"] } |
| 43 | clap = { version = "4.4.13", features = ["derive"] } | 44 | clap = { version = "4.4.13", features = ["derive"] } |
| 44 | directories = "5.0.1" | 45 | directories = "5.0.1" |
| 46 | +futures-util = { version = "0.3.30", default-features = false, features = ["std", "io"] } | ||
| 45 | git-version = "0.3.9" | 47 | git-version = "0.3.9" |
| 46 | keyframe = { version = "1.1.1", default-features = false } | 48 | keyframe = { version = "1.1.1", default-features = false } |
| 47 | libc = "0.2.151" | 49 | libc = "0.2.151" |
| 48 | logind-zbus = { version = "3.1.2", optional = true } | 50 | logind-zbus = { version = "3.1.2", optional = true } |
| 49 | log = { version = "0.4.20", features = ["max_level_trace", "release_max_level_debug"] } | 51 | log = { version = "0.4.20", features = ["max_level_trace", "release_max_level_debug"] } |
| 50 | niri-config = { version = "0.1.0-alpha.3", path = "niri-config" } | 52 | niri-config = { version = "0.1.0-alpha.3", path = "niri-config" } |
| 53 | +niri-ipc = { version = "0.1.0-alpha.3", path = "niri-ipc" } | ||
| 51 | notify-rust = { version = "4.10.0", optional = true } | 54 | notify-rust = { version = "4.10.0", optional = true } |
| 52 | pipewire = { version = "0.7.2", optional = true } | 55 | pipewire = { version = "0.7.2", optional = true } |
| 53 | png = "0.17.10" | 56 | png = "0.17.10" |
| 54 | portable-atomic = { version = "1.6.0", default-features = false, features = ["float"] } | 57 | portable-atomic = { version = "1.6.0", default-features = false, features = ["float"] } |
| 55 | profiling = "1.0.13" | 58 | profiling = "1.0.13" |
| 56 | sd-notify = "0.4.1" | 59 | sd-notify = "0.4.1" |
| 60 | +serde.workspace = true | ||
| 61 | +serde_json = "1.0.111" | ||
| 57 | smithay-drm-extras.workspace = true | 62 | smithay-drm-extras.workspace = true |
| 58 | -serde = { version = "1.0.195", features = ["derive"] } | ||
| 59 | tracing-subscriber = { version = "0.3.18", features = ["env-filter"] } | 63 | tracing-subscriber = { version = "0.3.18", features = ["env-filter"] } |
| 60 | tracing.workspace = true | 64 | tracing.workspace = true |
| 61 | tracy-client.workspace = true | 65 | tracy-client.workspace = true |
README.mdmodified+11 -0
| @@ -108,6 +108,17 @@ In particular, it supports file choosers and monitor screencasting (e.g. to [OBS | |||
| 108 | 108 | ||
| 109 | See [the wiki page](https://github.com/YaLTeR/niri/wiki/Xwayland) to learn how to use Xwayland with niri. | 109 | See [the wiki page](https://github.com/YaLTeR/niri/wiki/Xwayland) to learn how to use Xwayland with niri. |
| 110 | 110 | ||
| 111 | +### IPC | ||
| 112 | + | ||
| 113 | +You can communicate with the running niri instance over an IPC socket. | ||
| 114 | +Check `niri msg --help` for available commands. | ||
| 115 | + | ||
| 116 | +The `--json` flag prints the response in JSON, rather than formatted. | ||
| 117 | +For example, `niri msg --json outputs`. | ||
| 118 | + | ||
| 119 | +For programmatic access, check the [niri-ipc sub-crate](./niri-ipc/) which defines the types. | ||
| 120 | +The communication over the IPC socket happens in JSON. | ||
| 121 | + | ||
| 111 | ## Default Hotkeys | 122 | ## Default Hotkeys |
| 112 | 123 | ||
| 113 | When running on a TTY, the Mod key is <kbd>Super</kbd>. | 124 | When running on a TTY, the Mod key is <kbd>Super</kbd>. |
flake.nixmodified+1 -0
| @@ -44,6 +44,7 @@ | |||
| 44 | include = [ | 44 | include = [ |
| 45 | ./src | 45 | ./src |
| 46 | ./niri-config | 46 | ./niri-config |
| 47 | + ./niri-ipc | ||
| 47 | ./Cargo.toml | 48 | ./Cargo.toml |
| 48 | ./Cargo.lock | 49 | ./Cargo.lock |
| 49 | ./resources | 50 | ./resources |
niri-ipc/Cargo.tomladded+11 -0
| @@ -0,0 +1,11 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "niri-ipc" | ||
| 3 | +version.workspace = true | ||
| 4 | +description.workspace = true | ||
| 5 | +authors.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +edition.workspace = true | ||
| 8 | +repository.workspace = true | ||
| 9 | + | ||
| 10 | +[dependencies] | ||
| 11 | +serde.workspace = true | ||
niri-ipc/src/lib.rsadded+55 -0
| @@ -0,0 +1,55 @@ | |||
| 1 | +//! Types for communicating with niri via IPC. | ||
| 2 | +#![warn(missing_docs)] | ||
| 3 | + | ||
| 4 | +use std::collections::HashMap; | ||
| 5 | + | ||
| 6 | +use serde::{Deserialize, Serialize}; | ||
| 7 | + | ||
| 8 | +/// Name of the environment variable containing the niri IPC socket path. | ||
| 9 | +pub const SOCKET_PATH_ENV: &str = "NIRI_SOCKET"; | ||
| 10 | + | ||
| 11 | +/// Request from client to niri. | ||
| 12 | +#[derive(Debug, Serialize, Deserialize)] | ||
| 13 | +pub enum Request { | ||
| 14 | + /// Request information about connected outputs. | ||
| 15 | + Outputs, | ||
| 16 | +} | ||
| 17 | + | ||
| 18 | +/// Response from niri to client. | ||
| 19 | +#[derive(Debug, Serialize, Deserialize)] | ||
| 20 | +pub enum Response { | ||
| 21 | + /// Information about connected outputs. | ||
| 22 | + /// | ||
| 23 | + /// Map from connector name to output info. | ||
| 24 | + Outputs(HashMap<String, Output>), | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +/// Connected output. | ||
| 28 | +#[derive(Debug, Serialize, Deserialize, Clone)] | ||
| 29 | +pub struct Output { | ||
| 30 | + /// Name of the output. | ||
| 31 | + pub name: String, | ||
| 32 | + /// Textual description of the manufacturer. | ||
| 33 | + pub make: String, | ||
| 34 | + /// Textual description of the model. | ||
| 35 | + pub model: String, | ||
| 36 | + /// Physical width and height of the output in millimeters, if known. | ||
| 37 | + pub physical_size: Option<(u32, u32)>, | ||
| 38 | + /// Available modes for the output. | ||
| 39 | + pub modes: Vec<Mode>, | ||
| 40 | + /// Index of the current mode in [`Self::modes`]. | ||
| 41 | + /// | ||
| 42 | + /// `None` if the output is disabled. | ||
| 43 | + pub current_mode: Option<usize>, | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +/// Output mode. | ||
| 47 | +#[derive(Debug, Serialize, Deserialize, Clone, Copy)] | ||
| 48 | +pub struct Mode { | ||
| 49 | + /// Width in physical pixels. | ||
| 50 | + pub width: u16, | ||
| 51 | + /// Height in physical pixels. | ||
| 52 | + pub height: u16, | ||
| 53 | + /// Refresh rate in millihertz. | ||
| 54 | + pub refresh_rate: u32, | ||
| 55 | +} | ||
resources/default-config.kdlmodified+3 -2
| @@ -54,7 +54,8 @@ input { | |||
| 54 | // disable-power-key-handling | 54 | // disable-power-key-handling |
| 55 | } | 55 | } |
| 56 | 56 | ||
| 57 | -// You can configure outputs by their name, which you can find with wayland-info(1). | 57 | +// You can configure outputs by their name, which you can find |
| 58 | +// by running `niri msg outputs` while inside a niri instance. | ||
| 58 | // The built-in laptop monitor is usually called "eDP-1". | 59 | // The built-in laptop monitor is usually called "eDP-1". |
| 59 | // Remember to uncommend the node by removing "/-"! | 60 | // Remember to uncommend the node by removing "/-"! |
| 60 | /-output "eDP-1" { | 61 | /-output "eDP-1" { |
| @@ -69,7 +70,7 @@ input { | |||
| 69 | // If the refresh rate is omitted, niri will pick the highest refresh rate | 70 | // If the refresh rate is omitted, niri will pick the highest refresh rate |
| 70 | // for the resolution. | 71 | // for the resolution. |
| 71 | // If the mode is omitted altogether or is invalid, niri will pick one automatically. | 72 | // If the mode is omitted altogether or is invalid, niri will pick one automatically. |
| 72 | - // All valid modes are listed in niri's debug output when an output is connected. | 73 | + // Run `niri msg outputs` while inside a niri instance to list all outputs and their modes. |
| 73 | mode "1920x1080@144" | 74 | mode "1920x1080@144" |
| 74 | 75 | ||
| 75 | // Position of the output in the global coordinate space. | 76 | // Position of the output in the global coordinate space. |
src/backend/mod.rsmodified+9 -0
| @@ -1,4 +1,6 @@ | |||
| 1 | +use std::cell::RefCell; | ||
| 1 | use std::collections::HashMap; | 2 | use std::collections::HashMap; |
| 3 | +use std::rc::Rc; | ||
| 2 | use std::sync::{Arc, Mutex}; | 4 | use std::sync::{Arc, Mutex}; |
| 3 | use std::time::Duration; | 5 | use std::time::Duration; |
| 4 | 6 | ||
| @@ -110,6 +112,13 @@ impl Backend { | |||
| 110 | } | 112 | } |
| 111 | } | 113 | } |
| 112 | 114 | ||
| 115 | + pub fn ipc_outputs(&self) -> Rc<RefCell<HashMap<String, niri_ipc::Output>>> { | ||
| 116 | + match self { | ||
| 117 | + Backend::Tty(tty) => tty.ipc_outputs(), | ||
| 118 | + Backend::Winit(winit) => winit.ipc_outputs(), | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + | ||
| 113 | #[cfg_attr(not(feature = "dbus"), allow(unused))] | 122 | #[cfg_attr(not(feature = "dbus"), allow(unused))] |
| 114 | pub fn enabled_outputs(&self) -> Arc<Mutex<HashMap<String, Output>>> { | 123 | pub fn enabled_outputs(&self) -> Arc<Mutex<HashMap<String, Output>>> { |
| 115 | match self { | 124 | match self { |
src/backend/tty.rsmodified+68 -9
| @@ -74,6 +74,7 @@ pub struct Tty { | |||
| 74 | // The allocator for the primary GPU. It is only `Some()` if we have a device corresponding to | 74 | // The allocator for the primary GPU. It is only `Some()` if we have a device corresponding to |
| 75 | // the primary GPU. | 75 | // the primary GPU. |
| 76 | primary_allocator: Option<DmabufAllocator<GbmAllocator<DrmDeviceFd>>>, | 76 | primary_allocator: Option<DmabufAllocator<GbmAllocator<DrmDeviceFd>>>, |
| 77 | + ipc_outputs: Rc<RefCell<HashMap<String, niri_ipc::Output>>>, | ||
| 77 | enabled_outputs: Arc<Mutex<HashMap<String, Output>>>, | 78 | enabled_outputs: Arc<Mutex<HashMap<String, Output>>>, |
| 78 | } | 79 | } |
| 79 | 80 | ||
| @@ -221,6 +222,7 @@ impl Tty { | |||
| 221 | devices: HashMap::new(), | 222 | devices: HashMap::new(), |
| 222 | dmabuf_global: None, | 223 | dmabuf_global: None, |
| 223 | primary_allocator: None, | 224 | primary_allocator: None, |
| 225 | + ipc_outputs: Rc::new(RefCell::new(HashMap::new())), | ||
| 224 | enabled_outputs: Arc::new(Mutex::new(HashMap::new())), | 226 | enabled_outputs: Arc::new(Mutex::new(HashMap::new())), |
| 225 | } | 227 | } |
| 226 | } | 228 | } |
| @@ -367,6 +369,8 @@ impl Tty { | |||
| 367 | warn!("error adding device: {err:?}"); | 369 | warn!("error adding device: {err:?}"); |
| 368 | } | 370 | } |
| 369 | } | 371 | } |
| 372 | + | ||
| 373 | + self.refresh_ipc_outputs(); | ||
| 370 | } | 374 | } |
| 371 | } | 375 | } |
| 372 | } | 376 | } |
| @@ -512,6 +516,8 @@ impl Tty { | |||
| 512 | _ => (), | 516 | _ => (), |
| 513 | } | 517 | } |
| 514 | } | 518 | } |
| 519 | + | ||
| 520 | + self.refresh_ipc_outputs(); | ||
| 515 | } | 521 | } |
| 516 | 522 | ||
| 517 | fn device_removed(&mut self, device_id: dev_t, niri: &mut Niri) { | 523 | fn device_removed(&mut self, device_id: dev_t, niri: &mut Niri) { |
| @@ -576,6 +582,8 @@ impl Tty { | |||
| 576 | 582 | ||
| 577 | self.gpu_manager.as_mut().remove_node(&device.render_node); | 583 | self.gpu_manager.as_mut().remove_node(&device.render_node); |
| 578 | niri.event_loop.remove(device.token); | 584 | niri.event_loop.remove(device.token); |
| 585 | + | ||
| 586 | + self.refresh_ipc_outputs(); | ||
| 579 | } | 587 | } |
| 580 | 588 | ||
| 581 | fn connector_connected( | 589 | fn connector_connected( |
| @@ -608,16 +616,7 @@ impl Tty { | |||
| 608 | 616 | ||
| 609 | let device = self.devices.get_mut(&node).context("missing device")?; | 617 | let device = self.devices.get_mut(&node).context("missing device")?; |
| 610 | 618 | ||
| 611 | - // FIXME: print modes here until we have a better way to list all modes. | ||
| 612 | for m in connector.modes() { | 619 | for m in connector.modes() { |
| 613 | - let wl_mode = Mode::from(*m); | ||
| 614 | - debug!( | ||
| 615 | - "mode: {}x{}@{:.3}", | ||
| 616 | - m.size().0, | ||
| 617 | - m.size().1, | ||
| 618 | - wl_mode.refresh as f64 / 1000., | ||
| 619 | - ); | ||
| 620 | - | ||
| 621 | trace!("{m:?}"); | 620 | trace!("{m:?}"); |
| 622 | } | 621 | } |
| 623 | 622 | ||
| @@ -1157,6 +1156,64 @@ impl Tty { | |||
| 1157 | } | 1156 | } |
| 1158 | } | 1157 | } |
| 1159 | 1158 | ||
| 1159 | + fn refresh_ipc_outputs(&self) { | ||
| 1160 | + let _span = tracy_client::span!("Tty::refresh_ipc_outputs"); | ||
| 1161 | + | ||
| 1162 | + let mut ipc_outputs = HashMap::new(); | ||
| 1163 | + | ||
| 1164 | + for device in self.devices.values() { | ||
| 1165 | + for (connector, crtc) in device.drm_scanner.crtcs() { | ||
| 1166 | + let connector_name = format!( | ||
| 1167 | + "{}-{}", | ||
| 1168 | + connector.interface().as_str(), | ||
| 1169 | + connector.interface_id(), | ||
| 1170 | + ); | ||
| 1171 | + | ||
| 1172 | + let physical_size = connector.size(); | ||
| 1173 | + | ||
| 1174 | + let (make, model) = EdidInfo::for_connector(&device.drm, connector.handle()) | ||
| 1175 | + .map(|info| (info.manufacturer, info.model)) | ||
| 1176 | + .unwrap_or_else(|| ("Unknown".into(), "Unknown".into())); | ||
| 1177 | + | ||
| 1178 | + let modes = connector | ||
| 1179 | + .modes() | ||
| 1180 | + .iter() | ||
| 1181 | + .map(|m| niri_ipc::Mode { | ||
| 1182 | + width: m.size().0, | ||
| 1183 | + height: m.size().1, | ||
| 1184 | + refresh_rate: Mode::from(*m).refresh as u32, | ||
| 1185 | + }) | ||
| 1186 | + .collect(); | ||
| 1187 | + | ||
| 1188 | + let mut output = niri_ipc::Output { | ||
| 1189 | + name: connector_name.clone(), | ||
| 1190 | + make, | ||
| 1191 | + model, | ||
| 1192 | + physical_size, | ||
| 1193 | + modes, | ||
| 1194 | + current_mode: None, | ||
| 1195 | + }; | ||
| 1196 | + | ||
| 1197 | + if let Some(surface) = device.surfaces.get(&crtc) { | ||
| 1198 | + let current = surface.compositor.pending_mode(); | ||
| 1199 | + if let Some(current) = connector.modes().iter().position(|m| *m == current) { | ||
| 1200 | + output.current_mode = Some(current); | ||
| 1201 | + } else { | ||
| 1202 | + error!("connector mode list missing current mode"); | ||
| 1203 | + } | ||
| 1204 | + } | ||
| 1205 | + | ||
| 1206 | + ipc_outputs.insert(connector_name, output); | ||
| 1207 | + } | ||
| 1208 | + } | ||
| 1209 | + | ||
| 1210 | + self.ipc_outputs.replace(ipc_outputs); | ||
| 1211 | + } | ||
| 1212 | + | ||
| 1213 | + pub fn ipc_outputs(&self) -> Rc<RefCell<HashMap<String, niri_ipc::Output>>> { | ||
| 1214 | + self.ipc_outputs.clone() | ||
| 1215 | + } | ||
| 1216 | + | ||
| 1160 | pub fn enabled_outputs(&self) -> Arc<Mutex<HashMap<String, Output>>> { | 1217 | pub fn enabled_outputs(&self) -> Arc<Mutex<HashMap<String, Output>>> { |
| 1161 | self.enabled_outputs.clone() | 1218 | self.enabled_outputs.clone() |
| 1162 | } | 1219 | } |
| @@ -1305,6 +1362,8 @@ impl Tty { | |||
| 1305 | warn!("error connecting connector: {err:?}"); | 1362 | warn!("error connecting connector: {err:?}"); |
| 1306 | } | 1363 | } |
| 1307 | } | 1364 | } |
| 1365 | + | ||
| 1366 | + self.refresh_ipc_outputs(); | ||
| 1308 | } | 1367 | } |
| 1309 | } | 1368 | } |
| 1310 | 1369 | ||
src/backend/winit.rsmodified+29 -0
| @@ -28,6 +28,7 @@ pub struct Winit { | |||
| 28 | output: Output, | 28 | output: Output, |
| 29 | backend: WinitGraphicsBackend<GlesRenderer>, | 29 | backend: WinitGraphicsBackend<GlesRenderer>, |
| 30 | damage_tracker: OutputDamageTracker, | 30 | damage_tracker: OutputDamageTracker, |
| 31 | + ipc_outputs: Rc<RefCell<HashMap<String, niri_ipc::Output>>>, | ||
| 31 | enabled_outputs: Arc<Mutex<HashMap<String, Output>>>, | 32 | enabled_outputs: Arc<Mutex<HashMap<String, Output>>>, |
| 32 | } | 33 | } |
| 33 | 34 | ||
| @@ -56,6 +57,23 @@ impl Winit { | |||
| 56 | output.change_current_state(Some(mode), Some(Transform::Flipped180), None, None); | 57 | output.change_current_state(Some(mode), Some(Transform::Flipped180), None, None); |
| 57 | output.set_preferred(mode); | 58 | output.set_preferred(mode); |
| 58 | 59 | ||
| 60 | + let physical_properties = output.physical_properties(); | ||
| 61 | + let ipc_outputs = Rc::new(RefCell::new(HashMap::from([( | ||
| 62 | + "winit".to_owned(), | ||
| 63 | + niri_ipc::Output { | ||
| 64 | + name: output.name(), | ||
| 65 | + make: physical_properties.make, | ||
| 66 | + model: physical_properties.model, | ||
| 67 | + physical_size: None, | ||
| 68 | + modes: vec![niri_ipc::Mode { | ||
| 69 | + width: backend.window_size().w.clamp(0, u16::MAX as i32) as u16, | ||
| 70 | + height: backend.window_size().h.clamp(0, u16::MAX as i32) as u16, | ||
| 71 | + refresh_rate: 60_000, | ||
| 72 | + }], | ||
| 73 | + current_mode: Some(0), | ||
| 74 | + }, | ||
| 75 | + )]))); | ||
| 76 | + | ||
| 59 | let enabled_outputs = Arc::new(Mutex::new(HashMap::from([( | 77 | let enabled_outputs = Arc::new(Mutex::new(HashMap::from([( |
| 60 | "winit".to_owned(), | 78 | "winit".to_owned(), |
| 61 | output.clone(), | 79 | output.clone(), |
| @@ -76,6 +94,12 @@ impl Winit { | |||
| 76 | None, | 94 | None, |
| 77 | None, | 95 | None, |
| 78 | ); | 96 | ); |
| 97 | + | ||
| 98 | + let mut ipc_outputs = winit.ipc_outputs.borrow_mut(); | ||
| 99 | + let mode = &mut ipc_outputs.get_mut("winit").unwrap().modes[0]; | ||
| 100 | + mode.width = size.w.clamp(0, u16::MAX as i32) as u16; | ||
| 101 | + mode.height = size.h.clamp(0, u16::MAX as i32) as u16; | ||
| 102 | + | ||
| 79 | state.niri.output_resized(winit.output.clone()); | 103 | state.niri.output_resized(winit.output.clone()); |
| 80 | } | 104 | } |
| 81 | WinitEvent::Input(event) => state.process_input_event(event), | 105 | WinitEvent::Input(event) => state.process_input_event(event), |
| @@ -95,6 +119,7 @@ impl Winit { | |||
| 95 | output, | 119 | output, |
| 96 | backend, | 120 | backend, |
| 97 | damage_tracker, | 121 | damage_tracker, |
| 122 | + ipc_outputs, | ||
| 98 | enabled_outputs, | 123 | enabled_outputs, |
| 99 | } | 124 | } |
| 100 | } | 125 | } |
| @@ -198,6 +223,10 @@ impl Winit { | |||
| 198 | } | 223 | } |
| 199 | } | 224 | } |
| 200 | 225 | ||
| 226 | + pub fn ipc_outputs(&self) -> Rc<RefCell<HashMap<String, niri_ipc::Output>>> { | ||
| 227 | + self.ipc_outputs.clone() | ||
| 228 | + } | ||
| 229 | + | ||
| 201 | pub fn enabled_outputs(&self) -> Arc<Mutex<HashMap<String, Output>>> { | 230 | pub fn enabled_outputs(&self) -> Arc<Mutex<HashMap<String, Output>>> { |
| 202 | self.enabled_outputs.clone() | 231 | self.enabled_outputs.clone() |
| 203 | } | 232 | } |
src/ipc/client.rsadded+106 -0
| @@ -0,0 +1,106 @@ | |||
| 1 | +use std::env; | ||
| 2 | +use std::io::{Read, Write}; | ||
| 3 | +use std::net::Shutdown; | ||
| 4 | +use std::os::unix::net::UnixStream; | ||
| 5 | + | ||
| 6 | +use anyhow::{bail, Context}; | ||
| 7 | +use niri_ipc::{Mode, Output, Request, Response}; | ||
| 8 | + | ||
| 9 | +use crate::Msg; | ||
| 10 | + | ||
| 11 | +pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> { | ||
| 12 | + let socket_path = env::var_os(niri_ipc::SOCKET_PATH_ENV).with_context(|| { | ||
| 13 | + format!( | ||
| 14 | + "{} is not set, are you running this within niri?", | ||
| 15 | + niri_ipc::SOCKET_PATH_ENV | ||
| 16 | + ) | ||
| 17 | + })?; | ||
| 18 | + | ||
| 19 | + let mut stream = | ||
| 20 | + UnixStream::connect(socket_path).context("error connecting to {socket_path}")?; | ||
| 21 | + | ||
| 22 | + let request = match msg { | ||
| 23 | + Msg::Outputs => Request::Outputs, | ||
| 24 | + }; | ||
| 25 | + let mut buf = serde_json::to_vec(&request).unwrap(); | ||
| 26 | + stream | ||
| 27 | + .write_all(&buf) | ||
| 28 | + .context("error writing IPC request")?; | ||
| 29 | + stream | ||
| 30 | + .shutdown(Shutdown::Write) | ||
| 31 | + .context("error closing IPC stream for writing")?; | ||
| 32 | + | ||
| 33 | + buf.clear(); | ||
| 34 | + stream | ||
| 35 | + .read_to_end(&mut buf) | ||
| 36 | + .context("error reading IPC response")?; | ||
| 37 | + | ||
| 38 | + let response = serde_json::from_slice(&buf).context("error parsing IPC response")?; | ||
| 39 | + match msg { | ||
| 40 | + Msg::Outputs => { | ||
| 41 | + #[allow(irrefutable_let_patterns)] | ||
| 42 | + let Response::Outputs(outputs) = response | ||
| 43 | + else { | ||
| 44 | + bail!("unexpected response: expected Outputs, got {response:?}"); | ||
| 45 | + }; | ||
| 46 | + | ||
| 47 | + if json { | ||
| 48 | + let output = | ||
| 49 | + serde_json::to_string(&outputs).context("error formatting response")?; | ||
| 50 | + println!("{output}"); | ||
| 51 | + return Ok(()); | ||
| 52 | + } | ||
| 53 | + | ||
| 54 | + let mut outputs = outputs.into_iter().collect::<Vec<_>>(); | ||
| 55 | + outputs.sort_unstable_by(|a, b| a.0.cmp(&b.0)); | ||
| 56 | + | ||
| 57 | + for (connector, output) in outputs.into_iter() { | ||
| 58 | + let Output { | ||
| 59 | + name, | ||
| 60 | + make, | ||
| 61 | + model, | ||
| 62 | + physical_size, | ||
| 63 | + modes, | ||
| 64 | + current_mode, | ||
| 65 | + } = output; | ||
| 66 | + | ||
| 67 | + println!(r#"Output "{connector}" ({make} - {model} - {name})"#); | ||
| 68 | + | ||
| 69 | + if let Some(current) = current_mode { | ||
| 70 | + let mode = *modes | ||
| 71 | + .get(current) | ||
| 72 | + .context("invalid response: current mode does not exist")?; | ||
| 73 | + let Mode { | ||
| 74 | + width, | ||
| 75 | + height, | ||
| 76 | + refresh_rate, | ||
| 77 | + } = mode; | ||
| 78 | + let refresh = refresh_rate as f64 / 1000.; | ||
| 79 | + println!(" Current mode: {width}x{height} @ {refresh:.3} Hz"); | ||
| 80 | + } else { | ||
| 81 | + println!(" Disabled"); | ||
| 82 | + } | ||
| 83 | + | ||
| 84 | + if let Some((width, height)) = physical_size { | ||
| 85 | + println!(" Physical size: {width}x{height} mm"); | ||
| 86 | + } else { | ||
| 87 | + println!(" Physical size: unknown"); | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + println!(" Available modes:"); | ||
| 91 | + for mode in modes { | ||
| 92 | + let Mode { | ||
| 93 | + width, | ||
| 94 | + height, | ||
| 95 | + refresh_rate, | ||
| 96 | + } = mode; | ||
| 97 | + let refresh = refresh_rate as f64 / 1000.; | ||
| 98 | + println!(" {width}x{height}@{refresh:.3}"); | ||
| 99 | + } | ||
| 100 | + println!(); | ||
| 101 | + } | ||
| 102 | + } | ||
| 103 | + } | ||
| 104 | + | ||
| 105 | + Ok(()) | ||
| 106 | +} | ||
src/ipc/mod.rsadded+2 -0
| @@ -0,0 +1,2 @@ | |||
| 1 | +pub mod client; | ||
| 2 | +pub mod server; | ||
src/ipc/server.rsadded+127 -0
| @@ -0,0 +1,127 @@ | |||
| 1 | +use std::cell::RefCell; | ||
| 2 | +use std::collections::HashMap; | ||
| 3 | +use std::os::unix::net::{UnixListener, UnixStream}; | ||
| 4 | +use std::path::PathBuf; | ||
| 5 | +use std::rc::Rc; | ||
| 6 | +use std::{env, io, process}; | ||
| 7 | + | ||
| 8 | +use anyhow::Context; | ||
| 9 | +use calloop::io::Async; | ||
| 10 | +use directories::BaseDirs; | ||
| 11 | +use futures_util::io::{AsyncReadExt, BufReader}; | ||
| 12 | +use futures_util::{AsyncBufReadExt, AsyncWriteExt}; | ||
| 13 | +use niri_ipc::{Request, Response}; | ||
| 14 | +use smithay::reexports::calloop::generic::Generic; | ||
| 15 | +use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction}; | ||
| 16 | +use smithay::reexports::rustix::fs::unlink; | ||
| 17 | + | ||
| 18 | +use crate::niri::State; | ||
| 19 | + | ||
| 20 | +pub struct IpcServer { | ||
| 21 | + pub socket_path: PathBuf, | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +struct ClientCtx { | ||
| 25 | + ipc_outputs: Rc<RefCell<HashMap<String, niri_ipc::Output>>>, | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +impl IpcServer { | ||
| 29 | + pub fn start( | ||
| 30 | + event_loop: &LoopHandle<'static, State>, | ||
| 31 | + wayland_socket_name: &str, | ||
| 32 | + ) -> anyhow::Result<Self> { | ||
| 33 | + let _span = tracy_client::span!("Ipc::start"); | ||
| 34 | + | ||
| 35 | + let socket_name = format!("niri.{wayland_socket_name}.{}.sock", process::id()); | ||
| 36 | + let mut socket_path = socket_dir(); | ||
| 37 | + socket_path.push(socket_name); | ||
| 38 | + | ||
| 39 | + let listener = UnixListener::bind(&socket_path).context("error binding socket")?; | ||
| 40 | + listener | ||
| 41 | + .set_nonblocking(true) | ||
| 42 | + .context("error setting socket to non-blocking")?; | ||
| 43 | + | ||
| 44 | + let source = Generic::new(listener, Interest::READ, Mode::Level); | ||
| 45 | + event_loop | ||
| 46 | + .insert_source(source, |_, socket, state| { | ||
| 47 | + match socket.accept() { | ||
| 48 | + Ok((stream, _)) => on_new_ipc_client(state, stream), | ||
| 49 | + Err(e) if e.kind() == io::ErrorKind::WouldBlock => (), | ||
| 50 | + Err(e) => return Err(e), | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + Ok(PostAction::Continue) | ||
| 54 | + }) | ||
| 55 | + .unwrap(); | ||
| 56 | + | ||
| 57 | + Ok(Self { socket_path }) | ||
| 58 | + } | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +impl Drop for IpcServer { | ||
| 62 | + fn drop(&mut self) { | ||
| 63 | + let _ = unlink(&self.socket_path); | ||
| 64 | + } | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +fn socket_dir() -> PathBuf { | ||
| 68 | + BaseDirs::new() | ||
| 69 | + .as_ref() | ||
| 70 | + .and_then(|x| x.runtime_dir()) | ||
| 71 | + .map(|x| x.to_owned()) | ||
| 72 | + .unwrap_or_else(env::temp_dir) | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +fn on_new_ipc_client(state: &mut State, stream: UnixStream) { | ||
| 76 | + let _span = tracy_client::span!("on_new_ipc_client"); | ||
| 77 | + trace!("new IPC client connected"); | ||
| 78 | + | ||
| 79 | + let stream = match state.niri.event_loop.adapt_io(stream) { | ||
| 80 | + Ok(stream) => stream, | ||
| 81 | + Err(err) => { | ||
| 82 | + warn!("error making IPC stream async: {err:?}"); | ||
| 83 | + return; | ||
| 84 | + } | ||
| 85 | + }; | ||
| 86 | + | ||
| 87 | + let ctx = ClientCtx { | ||
| 88 | + ipc_outputs: state.backend.ipc_outputs(), | ||
| 89 | + }; | ||
| 90 | + | ||
| 91 | + let future = async move { | ||
| 92 | + if let Err(err) = handle_client(ctx, stream).await { | ||
| 93 | + warn!("error handling IPC client: {err:?}"); | ||
| 94 | + } | ||
| 95 | + }; | ||
| 96 | + if let Err(err) = state.niri.scheduler.schedule(future) { | ||
| 97 | + warn!("error scheduling IPC stream future: {err:?}"); | ||
| 98 | + } | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +async fn handle_client(ctx: ClientCtx, stream: Async<'_, UnixStream>) -> anyhow::Result<()> { | ||
| 102 | + let (read, mut write) = stream.split(); | ||
| 103 | + let mut buf = String::new(); | ||
| 104 | + | ||
| 105 | + // Read a single line to allow extensibility in the future to keep reading. | ||
| 106 | + BufReader::new(read) | ||
| 107 | + .read_line(&mut buf) | ||
| 108 | + .await | ||
| 109 | + .context("error reading request")?; | ||
| 110 | + | ||
| 111 | + let request: Request = serde_json::from_str(&buf).context("error parsing request")?; | ||
| 112 | + | ||
| 113 | + let response = match request { | ||
| 114 | + Request::Outputs => { | ||
| 115 | + let ipc_outputs = ctx.ipc_outputs.borrow().clone(); | ||
| 116 | + Response::Outputs(ipc_outputs) | ||
| 117 | + } | ||
| 118 | + }; | ||
| 119 | + | ||
| 120 | + let buf = serde_json::to_vec(&response).context("error formatting response")?; | ||
| 121 | + write | ||
| 122 | + .write_all(&buf) | ||
| 123 | + .await | ||
| 124 | + .context("error writing response")?; | ||
| 125 | + | ||
| 126 | + Ok(()) | ||
| 127 | +} | ||
src/main.rsmodified+26 -0
| @@ -9,6 +9,7 @@ mod dbus; | |||
| 9 | mod frame_clock; | 9 | mod frame_clock; |
| 10 | mod handlers; | 10 | mod handlers; |
| 11 | mod input; | 11 | mod input; |
| 12 | +mod ipc; | ||
| 12 | mod layout; | 13 | mod layout; |
| 13 | mod niri; | 14 | mod niri; |
| 14 | mod render_helpers; | 15 | mod render_helpers; |
| @@ -40,6 +41,7 @@ use tracing_subscriber::EnvFilter; | |||
| 40 | use utils::spawn; | 41 | use utils::spawn; |
| 41 | use watcher::Watcher; | 42 | use watcher::Watcher; |
| 42 | 43 | ||
| 44 | +use crate::ipc::client::handle_msg; | ||
| 43 | use crate::utils::{cause_panic, REMOVE_ENV_RUST_BACKTRACE, REMOVE_ENV_RUST_LIB_BACKTRACE}; | 45 | use crate::utils::{cause_panic, REMOVE_ENV_RUST_BACKTRACE, REMOVE_ENV_RUST_LIB_BACKTRACE}; |
| 44 | 46 | ||
| 45 | #[derive(Parser)] | 47 | #[derive(Parser)] |
| @@ -67,10 +69,24 @@ enum Sub { | |||
| 67 | #[arg(short, long)] | 69 | #[arg(short, long)] |
| 68 | config: Option<PathBuf>, | 70 | config: Option<PathBuf>, |
| 69 | }, | 71 | }, |
| 72 | + /// Communicate with the running niri instance. | ||
| 73 | + Msg { | ||
| 74 | + #[command(subcommand)] | ||
| 75 | + msg: Msg, | ||
| 76 | + /// Format output as JSON. | ||
| 77 | + #[arg(short, long)] | ||
| 78 | + json: bool, | ||
| 79 | + }, | ||
| 70 | /// Cause a panic to check if the backtraces are good. | 80 | /// Cause a panic to check if the backtraces are good. |
| 71 | Panic, | 81 | Panic, |
| 72 | } | 82 | } |
| 73 | 83 | ||
| 84 | +#[derive(Subcommand)] | ||
| 85 | +enum Msg { | ||
| 86 | + /// List connected outputs. | ||
| 87 | + Outputs, | ||
| 88 | +} | ||
| 89 | + | ||
| 74 | fn main() -> Result<(), Box<dyn std::error::Error>> { | 90 | fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 75 | // Set backtrace defaults if not set. | 91 | // Set backtrace defaults if not set. |
| 76 | if env::var_os("RUST_BACKTRACE").is_none() { | 92 | if env::var_os("RUST_BACKTRACE").is_none() { |
| @@ -120,6 +136,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { | |||
| 120 | info!("config is valid"); | 136 | info!("config is valid"); |
| 121 | return Ok(()); | 137 | return Ok(()); |
| 122 | } | 138 | } |
| 139 | + Sub::Msg { msg, json } => { | ||
| 140 | + handle_msg(msg, json)?; | ||
| 141 | + return Ok(()); | ||
| 142 | + } | ||
| 123 | Sub::Panic => cause_panic(), | 143 | Sub::Panic => cause_panic(), |
| 124 | } | 144 | } |
| 125 | } | 145 | } |
| @@ -159,6 +179,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { | |||
| 159 | socket_name.to_string_lossy() | 179 | socket_name.to_string_lossy() |
| 160 | ); | 180 | ); |
| 161 | 181 | ||
| 182 | + // Set NIRI_SOCKET for children. | ||
| 183 | + if let Some(ipc) = &state.niri.ipc_server { | ||
| 184 | + env::set_var(niri_ipc::SOCKET_PATH_ENV, &ipc.socket_path); | ||
| 185 | + info!("IPC listening on: {}", ipc.socket_path.to_string_lossy()); | ||
| 186 | + } | ||
| 187 | + | ||
| 162 | if is_systemd_service { | 188 | if is_systemd_service { |
| 163 | // We're starting as a systemd service. Export our variables. | 189 | // We're starting as a systemd service. Export our variables. |
| 164 | import_env_to_systemd(); | 190 | import_env_to_systemd(); |
src/niri.rsmodified+13 -0
| @@ -98,6 +98,7 @@ use crate::dbus::mutter_screen_cast::{self, ScreenCastToNiri}; | |||
| 98 | use crate::frame_clock::FrameClock; | 98 | use crate::frame_clock::FrameClock; |
| 99 | use crate::handlers::configure_lock_surface; | 99 | use crate::handlers::configure_lock_surface; |
| 100 | use crate::input::{apply_libinput_settings, TabletData}; | 100 | use crate::input::{apply_libinput_settings, TabletData}; |
| 101 | +use crate::ipc::server::IpcServer; | ||
| 101 | use crate::layout::{Layout, MonitorRenderElement}; | 102 | use crate::layout::{Layout, MonitorRenderElement}; |
| 102 | use crate::pw_utils::{Cast, PipeWire}; | 103 | use crate::pw_utils::{Cast, PipeWire}; |
| 103 | use crate::render_helpers::{NiriRenderer, PrimaryGpuTextureRenderElement}; | 104 | use crate::render_helpers::{NiriRenderer, PrimaryGpuTextureRenderElement}; |
| @@ -190,6 +191,8 @@ pub struct Niri { | |||
| 190 | #[cfg(feature = "dbus")] | 191 | #[cfg(feature = "dbus")] |
| 191 | pub inhibit_power_key_fd: Option<zbus::zvariant::OwnedFd>, | 192 | pub inhibit_power_key_fd: Option<zbus::zvariant::OwnedFd>, |
| 192 | 193 | ||
| 194 | + pub ipc_server: Option<IpcServer>, | ||
| 195 | + | ||
| 193 | // Casts are dropped before PipeWire to prevent a double-free (yay). | 196 | // Casts are dropped before PipeWire to prevent a double-free (yay). |
| 194 | pub casts: Vec<Cast>, | 197 | pub casts: Vec<Cast>, |
| 195 | pub pipewire: Option<PipeWire>, | 198 | pub pipewire: Option<PipeWire>, |
| @@ -865,6 +868,14 @@ impl Niri { | |||
| 865 | }) | 868 | }) |
| 866 | .unwrap(); | 869 | .unwrap(); |
| 867 | 870 | ||
| 871 | + let ipc_server = match IpcServer::start(&event_loop, &socket_name.to_string_lossy()) { | ||
| 872 | + Ok(server) => Some(server), | ||
| 873 | + Err(err) => { | ||
| 874 | + warn!("error starting IPC server: {err:?}"); | ||
| 875 | + None | ||
| 876 | + } | ||
| 877 | + }; | ||
| 878 | + | ||
| 868 | let pipewire = match PipeWire::new(&event_loop) { | 879 | let pipewire = match PipeWire::new(&event_loop) { |
| 869 | Ok(pipewire) => Some(pipewire), | 880 | Ok(pipewire) => Some(pipewire), |
| 870 | Err(err) => { | 881 | Err(err) => { |
| @@ -949,6 +960,8 @@ impl Niri { | |||
| 949 | #[cfg(feature = "dbus")] | 960 | #[cfg(feature = "dbus")] |
| 950 | inhibit_power_key_fd: None, | 961 | inhibit_power_key_fd: None, |
| 951 | 962 | ||
| 963 | + ipc_server, | ||
| 964 | + | ||
| 952 | pipewire, | 965 | pipewire, |
| 953 | casts: vec![], | 966 | casts: vec![], |
| 954 | } | 967 | } |