From f1bfef9a36337696b57efa3e4e41ca04dece1f5b Mon Sep 17 00:00:00 2001 From: sodiboo Date: Wed, 17 Apr 2024 22:43:17 +0200 Subject: [PATCH] ipc: implement Request trait with statically-guaranteed Response type --- niri-ipc/src/lib.rs | 221 +++++++++++++-- niri-ipc/src/socket.rs | 12 +- src/ipc/client.rs | 618 ++++++++++++++++++++++++++++------------- src/ipc/server.rs | 115 ++++++-- 4 files changed, 710 insertions(+), 256 deletions(-) diff --git a/niri-ipc/src/lib.rs b/niri-ipc/src/lib.rs index 8911e76c0..bbf3a6621 100644 --- a/niri-ipc/src/lib.rs +++ b/niri-ipc/src/lib.rs @@ -1,7 +1,7 @@ //! Types for communicating with niri via IPC. #![warn(missing_docs)] -use std::collections::HashMap; +use std::collections::BTreeMap; use std::str::FromStr; use serde::{Deserialize, Serialize}; @@ -10,21 +10,199 @@ mod socket; pub use socket::{NiriSocket, SOCKET_PATH_ENV}; -/// Request from client to niri. +mod private { + pub trait Sealed {} +} + +// TODO: remove ResponseDecoder and AnyRequest? + +#[allow(missing_docs)] +pub trait ResponseDecoder { + type Output: for<'de> Deserialize<'de>; + fn decode(&self, value: serde_json::Value) -> serde_json::Result; +} + +#[derive(Debug, Clone, Copy)] +#[allow(missing_docs)] +pub struct TrivialDecoder Deserialize<'de>>(std::marker::PhantomData); + +impl Deserialize<'de>> Default for TrivialDecoder { + fn default() -> Self { + Self(std::marker::PhantomData) + } +} + +impl Deserialize<'de>> ResponseDecoder for TrivialDecoder { + type Output = T; + + fn decode(&self, value: serde_json::Value) -> serde_json::Result { + serde_json::from_value(value) + } +} + +/// A request that can be sent to niri. +pub trait Request: + Serialize + for<'de> Deserialize<'de> + private::Sealed + Into +{ + /// The type of the response that niri sends for this request. + type Response: Serialize + for<'de> Deserialize<'de>; + + #[allow(missing_docs)] + fn decoder(&self) -> impl ResponseDecoder> + 'static; + + /// Convert the request into a RequestMessage (for serialization). + fn into_message(self) -> RequestMessage; +} + +macro_rules! requests { + (@$item:item$(;)?) => { $item }; + ($($(#[$m:meta])*$variant:ident($v:vis struct $request:ident$($p:tt)?) -> $response:ty;)*) => { + #[derive(Debug, Serialize, Deserialize, Clone)] + /// A plain tag for each request type. + pub enum RequestType { + $( + $(#[$m])* + $variant, + )* + } + + #[derive(Debug, Serialize, Deserialize, Clone)] + enum AnyRequest { + $( + $(#[$m])* + $variant($request), + )* + } + + #[derive(Debug, Serialize, Deserialize, Clone)] + enum AnyResponse { + $( + $(#[$m])* + $variant($response), + )* + } + + impl private::Sealed for AnyRequest {} + + struct AnyResponseDecoder(RequestType); + + impl ResponseDecoder for AnyResponseDecoder { + type Output = Reply; + + fn decode(&self, value: serde_json::Value) -> serde_json::Result { + match self.0 { + $( + RequestType::$variant => TrivialDecoder::>::default().decode(value).map(|r| r.map(AnyResponse::$variant)), + )* + } + } + } + + impl TryFrom for AnyRequest { + type Error = serde_json::Error; + + fn try_from(message: RequestMessage) -> serde_json::Result { + match message.request_type { + $( + RequestType::$variant => serde_json::from_value(message.request_body).map(AnyRequest::$variant), + )* + } + } + } + + impl Request for AnyRequest { + type Response = AnyResponse; + + fn decoder(&self) -> impl ResponseDecoder> + 'static { + match self { + $( + AnyRequest::$variant(_) => AnyResponseDecoder(RequestType::$variant), + )* + } + } + + fn into_message(self) -> RequestMessage { + match self { + $( + AnyRequest::$variant(request) => request.into_message(), + )* + } + } + } + + + $( + requests!(@ + $(#[$m])* + #[derive(Debug, Serialize, Deserialize, Clone)] + $v struct $request $($p)?; + ); + + impl From<$request> for AnyRequest { + fn from(request: $request) -> Self { + AnyRequest::$variant(request) + } + } + + impl crate::private::Sealed for $request {} + + impl crate::Request for $request { + type Response = $response; + + fn decoder(&self) -> impl crate::ResponseDecoder> + 'static { + TrivialDecoder::>::default() + } + + fn into_message(self) -> RequestMessage { + RequestMessage { + request_type: RequestType::$variant, + request_body: serde_json::to_value(self).unwrap(), + } + } + } + )* + } +} + +/// The message format for IPC communication. +/// +/// This is mainly to avoid using sum types in IPC communication, which are more annoying to use +/// with non-Rust tooling. #[derive(Debug, Serialize, Deserialize, Clone)] -pub enum Request { - /// Always responds with an error. (For testing error handling) - ReturnError, - /// Request the version string for the running niri instance. - Version, - /// Request information about connected outputs. - Outputs, - /// Request information about the focused window. - FocusedWindow, - /// Perform an action. - Action(Action), +pub struct RequestMessage { + /// The type of the request. + pub request_type: RequestType, + /// The raw JSON body of the request. + pub request_body: serde_json::Value, } +impl From for RequestMessage { + fn from(value: R) -> Self { + value.into_message() + } +} + +/// Uninstantiable +#[derive(Debug, Serialize, Deserialize, Clone)] +pub enum Never {} + +requests!( + /// Always responds with an error (for testing error handling). + ReturnError(pub struct ErrorRequest) -> Never; + + /// Requests the version string for the running niri instance. + Version(pub struct VersionRequest) -> String; + + /// Requests information about connected outputs. + Outputs(pub struct OutputRequest) -> BTreeMap; + + /// Requests information about the focused window. + FocusedWindow(pub struct FocusedWindowRequest) -> Option; + + /// Requests that the compositor perform an action. + Action(pub struct ActionRequest(pub Action)) -> (); +); + /// Reply from niri to client. /// /// Every request gets one reply. @@ -33,22 +211,7 @@ pub enum Request { /// * If the request does not need any particular response, it will be /// `Reply::Ok(Response::Handled)`. Kind of like an `Ok(())`. /// * Otherwise, it will be `Reply::Ok(response)` with one of the other [`Response`] variants. -pub type Reply = Result; - -/// Successful response from niri to client. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub enum Response { - /// A request that does not need a response was handled successfully. - Handled, - /// The version string for the running niri instance. - Version(String), - /// Information about connected outputs. - /// - /// Map from connector name to output info. - Outputs(HashMap), - /// Information about the focused window. - FocusedWindow(Option), -} +pub type Reply = Result; /// Actions that niri can perform. // Variants in this enum should match the spelling of the ones in niri-config. Most, but not all, diff --git a/niri-ipc/src/socket.rs b/niri-ipc/src/socket.rs index 60abd3f9d..650d8e3d6 100644 --- a/niri-ipc/src/socket.rs +++ b/niri-ipc/src/socket.rs @@ -5,7 +5,7 @@ use std::path::Path; use serde_json::de::IoRead; use serde_json::StreamDeserializer; -use crate::{Reply, Request}; +use crate::{Reply, Request, ResponseDecoder}; /// Name of the environment variable containing the niri IPC socket path. pub const SOCKET_PATH_ENV: &str = "NIRI_SOCKET"; @@ -16,7 +16,7 @@ pub const SOCKET_PATH_ENV: &str = "NIRI_SOCKET"; /// and serialization/deserialization of messages. pub struct NiriSocket { stream: UnixStream, - responses: StreamDeserializer<'static, IoRead, Reply>, + responses: StreamDeserializer<'static, IoRead, serde_json::Value>, } impl TryFrom for NiriSocket { @@ -55,14 +55,16 @@ impl NiriSocket { /// Ok(Ok([Response](crate::Response))) corresponds to a successful response from the running /// niri instance. Ok(Err([String])) corresponds to an error received from the running niri /// instance. Err([std::io::Error]) corresponds to an error in the IPC communication. - pub fn send(mut self, request: Request) -> io::Result { - let mut buf = serde_json::to_vec(&request).unwrap(); + pub fn send_request(mut self, request: R) -> io::Result> { + let decoder = request.decoder(); + let mut buf = serde_json::to_vec(&request.into_message()).unwrap(); writeln!(buf).unwrap(); self.stream.write_all(&buf)?; // .context("error writing IPC request")?; self.stream.flush()?; if let Some(next) = self.responses.next() { - next.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)) + next.and_then(|v| decoder.decode(v)) + .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)) } else { Err(io::Error::new( io::ErrorKind::UnexpectedEof, diff --git a/src/ipc/client.rs b/src/ipc/client.rs index bf0f0dad4..60779047d 100644 --- a/src/ipc/client.rs +++ b/src/ipc/client.rs @@ -1,242 +1,470 @@ -use anyhow::{bail, Context}; -use niri_ipc::{LogicalOutput, Mode, NiriSocket, Output, Request, Response}; +use anyhow::Context; +use niri_ipc::{ + ActionRequest, ErrorRequest, FocusedWindowRequest, LogicalOutput, Mode, NiriSocket, Output, + OutputRequest, Request, VersionRequest, +}; use serde_json::json; use crate::cli::Msg; use crate::utils::version; +struct CompositorError { + message: String, + version: Option, +} + +type MsgResult = Result; + +trait MsgRequest: Request { + fn json(response: Self::Response) -> serde_json::Value { + json!(response) + } + + fn show_to_human(response: Self::Response); + + fn check_version() -> Option { + if let Ok(Ok(version)) = VersionRequest.send() { + Some(version) + } else { + None + } + } + + fn send(self) -> anyhow::Result> { + let socket = NiriSocket::new().context("trying to initialize the socket")?; + let reply = socket + .send_request(self) + .context("while sending request to niri")?; + Ok(reply.map_err(|message| CompositorError { + message, + version: Self::check_version(), + })) + } +} + pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> { - let client = NiriSocket::new() - .context("a communication error occured while trying to initialize the socket")?; + match &msg { + Msg::Error => run(json, ErrorRequest), + Msg::Version => run(json, VersionRequest), + Msg::Outputs => run(json, OutputRequest), + Msg::FocusedWindow => run(json, FocusedWindowRequest), + Msg::Action { action } => run(json, ActionRequest(action.clone())), + } +} + +fn run(json: bool, request: R) -> anyhow::Result<()> { + let reply = request.send().context("a communication error occurred")?; // Default SIGPIPE so that our prints don't panic on stdout closing. unsafe { libc::signal(libc::SIGPIPE, libc::SIG_DFL); } - let request = match &msg { - Msg::Error => Request::ReturnError, - Msg::Version => Request::Version, - Msg::Outputs => Request::Outputs, - Msg::FocusedWindow => Request::FocusedWindow, - Msg::Action { action } => Request::Action(action.clone()), - }; - - let reply = client - .send(request) - .context("a communication error occurred while sending request to niri")?; - - let response = match reply { - Ok(r) => r, - Err(err_msg) => { + match reply { + Ok(response) => { + if json { + println!("{}", R::json(response)); + } else { + R::show_to_human(response); + } + } + Err(CompositorError { + message, + version: server_version, + }) => { eprintln!("The compositor returned an error:"); eprintln!(); - eprintln!("{err_msg}"); + eprintln!("{message}"); - if matches!(msg, Msg::Version) { + if let Some(server_version) = server_version { + let my_version = version(); + if my_version != server_version { + eprintln!(); + eprintln!("Note: niri msg was invoked with a different version of niri than the running compositor."); + eprintln!("niri msg: {my_version}"); + eprintln!("compositor: {server_version}"); + eprintln!("Did you forget to restart niri after an update?"); + } + } else { eprintln!(); eprintln!("Note: unable to get the compositor's version."); eprintln!("Did you forget to restart niri after an update?"); - } else { - match NiriSocket::new().and_then(|client| client.send(Request::Version)) { - Ok(Ok(Response::Version(server_version))) => { - let my_version = version(); - if my_version != server_version { - eprintln!(); - eprintln!("Note: niri msg was invoked with a different version of niri than the running compositor."); - eprintln!("niri msg: {my_version}"); - eprintln!("compositor: {server_version}"); - eprintln!("Did you forget to restart niri after an update?"); - } - } - Ok(Ok(_)) => { - // nonsensical response, do not add confusing context - } - Ok(Err(_)) => { - eprintln!(); - eprintln!("Note: unable to get the compositor's version."); - eprintln!("Did you forget to restart niri after an update?"); - } - Err(_) => { - // communication error, do not add irrelevant context - } - } } - - return Ok(()); } - }; + } - match msg { - Msg::Error => { - bail!("unexpected response: expected an error, got {response:?}"); - } - Msg::Version => { - let Response::Version(server_version) = response else { - bail!("unexpected response: expected Version, got {response:?}"); - }; + Ok(()) +} - if json { - println!( - "{}", - json!({ - "cli": version(), - "compositor": server_version, - }) - ); - return Ok(()); - } +// fn _a() { - let client_version = version(); +// let reply = client +// .send(request) +// .context("a communication error occurred while sending request to niri")?; - println!("niri msg is {client_version}"); - println!("the compositor is {server_version}"); - if client_version != server_version { - eprintln!(); - eprintln!("These are different"); - eprintln!("Did you forget to restart niri after an update?"); - } - println!(); +// let response = match reply { +// Ok(r) => r, +// Err(err_msg) => { +// eprintln!("The compositor returned an error:"); +// eprintln!(); +// eprintln!("{err_msg}"); + +// if matches!(msg, Msg::Version) { +// eprintln!(); +// eprintln!("Note: unable to get the compositor's version."); +// eprintln!("Did you forget to restart niri after an update?"); +// } else { +// match NiriSocket::new().and_then(|client| client.send(RequestEnum::Version)) { +// Ok(Ok(Response::Version(server_version))) => { +// let my_version = version(); +// if my_version != server_version { +// eprintln!(); +// eprintln!("Note: niri msg was invoked with a different version of +// niri than the running compositor."); eprintln!("niri msg: +// {my_version}"); eprintln!("compositor: {server_version}"); +// eprintln!("Did you forget to restart niri after an update?"); +// } +// } +// Ok(Ok(_)) => { +// // nonsensical response, do not add confusing context +// } +// Ok(Err(_)) => { +// eprintln!(); +// eprintln!("Note: unable to get the compositor's version."); +// eprintln!("Did you forget to restart niri after an update?"); +// } +// Err(_) => { +// // communication error, do not add irrelevant context +// } +// } +// } + +// return Ok(()); +// } +// }; + +// match msg { +// Msg::Error => { +// bail!("unexpected response: expected an error, got {response:?}"); +// } +// Msg::Version => { +// let Response::Version(server_version) = response else { +// bail!("unexpected response: expected Version, got {response:?}"); +// }; + +// if json { +// println!( +// "{}", +// json!({ +// "cli": version(), +// "compositor": server_version, +// }) +// ); +// return Ok(()); +// } + +// let client_version = version(); + +// println!("niri msg is {client_version}"); +// println!("the compositor is {server_version}"); +// if client_version != server_version { +// eprintln!(); +// eprintln!("These are different"); +// eprintln!("Did you forget to restart niri after an update?"); +// } +// println!(); +// } +// Msg::Outputs => { +// let Response::Outputs(outputs) = response else { +// bail!("unexpected response: expected Outputs, got {response:?}"); +// }; + +// if json { +// let output = +// serde_json::to_string(&outputs).context("error formatting response")?; +// println!("{output}"); +// return Ok(()); +// } + +// let mut outputs = outputs.into_iter().collect::>(); +// outputs.sort_unstable_by(|a, b| a.0.cmp(&b.0)); + +// for (connector, output) in outputs.into_iter() { +// let Output { +// name, +// make, +// model, +// physical_size, +// modes, +// current_mode, +// logical, +// } = output; + +// println!(r#"Output "{connector}" ({make} - {model} - {name})"#); + +// if let Some(current) = current_mode { +// let mode = *modes +// .get(current) +// .context("invalid response: current mode does not exist")?; +// let Mode { +// width, +// height, +// refresh_rate, +// is_preferred, +// } = mode; +// let refresh = refresh_rate as f64 / 1000.; +// let preferred = if is_preferred { " (preferred)" } else { "" }; +// println!(" Current mode: {width}x{height} @ {refresh:.3} Hz{preferred}"); +// } else { +// println!(" Disabled"); +// } + +// if let Some((width, height)) = physical_size { +// println!(" Physical size: {width}x{height} mm"); +// } else { +// println!(" Physical size: unknown"); +// } + +// if let Some(logical) = logical { +// let LogicalOutput { +// x, +// y, +// width, +// height, +// scale, +// transform, +// } = logical; +// println!(" Logical position: {x}, {y}"); +// println!(" Logical size: {width}x{height}"); +// println!(" Scale: {scale}"); + +// let transform = match transform { +// niri_ipc::Transform::Normal => "normal", +// niri_ipc::Transform::_90 => "90° counter-clockwise", +// niri_ipc::Transform::_180 => "180°", +// niri_ipc::Transform::_270 => "270° counter-clockwise", +// niri_ipc::Transform::Flipped => "flipped horizontally", +// niri_ipc::Transform::Flipped90 => { +// "90° counter-clockwise, flipped horizontally" +// } +// niri_ipc::Transform::Flipped180 => "flipped vertically", +// niri_ipc::Transform::Flipped270 => { +// "270° counter-clockwise, flipped horizontally" +// } +// }; +// println!(" Transform: {transform}"); +// } + +// println!(" Available modes:"); +// for (idx, mode) in modes.into_iter().enumerate() { +// let Mode { +// width, +// height, +// refresh_rate, +// is_preferred, +// } = mode; +// let refresh = refresh_rate as f64 / 1000.; + +// let is_current = Some(idx) == current_mode; +// let qualifier = match (is_current, is_preferred) { +// (true, true) => " (current, preferred)", +// (true, false) => " (current)", +// (false, true) => " (preferred)", +// (false, false) => "", +// }; + +// println!(" {width}x{height}@{refresh:.3}{qualifier}"); +// } +// println!(); +// } +// } +// Msg::FocusedWindow => { +// let Response::FocusedWindow(window) = response else { +// bail!("unexpected response: expected FocusedWindow, got {response:?}"); +// }; + +// if json { +// let window = serde_json::to_string(&window).context("error formatting +// response")?; println!("{window}"); +// return Ok(()); +// } + +// if let Some(window) = window { +// println!("Focused window:"); + +// if let Some(title) = window.title { +// println!(" Title: \"{title}\""); +// } else { +// println!(" Title: (unset)"); +// } + +// if let Some(app_id) = window.app_id { +// println!(" App ID: \"{app_id}\""); +// } else { +// println!(" App ID: (unset)"); +// } +// } else { +// println!("No window is focused."); +// } +// } +// Msg::Action { .. } => { +// let Response::Handled = response else { +// bail!("unexpected response: expected Handled, got {response:?}"); +// }; +// } +// } + +// Ok(()) +// } + +impl MsgRequest for ErrorRequest { + fn json(response: Self::Response) -> serde_json::Value { + match response {} + } + + fn show_to_human(response: Self::Response) { + match response {} + } +} + +impl MsgRequest for VersionRequest { + fn check_version() -> Option { + // If the version request fails, we can't exactly try again. + None + } + fn json(response: Self::Response) -> serde_json::Value { + json!({ + "cli": version(), + "compositor": response, + }) + } + fn show_to_human(response: Self::Response) { + let client_version = version(); + let server_version = response; + println!("niri msg is {client_version}"); + println!("the compositor is {server_version}"); + if client_version != server_version { + eprintln!(); + eprintln!("These are different"); + eprintln!("Did you forget to restart niri after an update?"); } - Msg::Outputs => { - let Response::Outputs(outputs) = response else { - bail!("unexpected response: expected Outputs, got {response:?}"); - }; + println!(); + } +} - if json { - let output = - serde_json::to_string(&outputs).context("error formatting response")?; - println!("{output}"); - return Ok(()); - } +impl MsgRequest for OutputRequest { + fn show_to_human(response: Self::Response) { + for (connector, output) in response { + let Output { + name, + make, + model, + physical_size, + modes, + current_mode, + logical, + } = output; + + println!(r#"Output "{connector}" ({make} - {model} - {name})"#); - let mut outputs = outputs.into_iter().collect::>(); - outputs.sort_unstable_by(|a, b| a.0.cmp(&b.0)); - - for (connector, output) in outputs.into_iter() { - let Output { - name, - make, - model, - physical_size, - modes, - current_mode, - logical, - } = output; - - println!(r#"Output "{connector}" ({make} - {model} - {name})"#); - - if let Some(current) = current_mode { - let mode = *modes - .get(current) - .context("invalid response: current mode does not exist")?; - let Mode { - width, - height, - refresh_rate, - is_preferred, - } = mode; + match current_mode.map(|idx| modes.get(idx)) { + None => println!(" Disabled"), + Some(None) => println!(" Current mode: (invalid index)"), + Some(Some(&Mode { + width, + height, + refresh_rate, + is_preferred, + })) => { let refresh = refresh_rate as f64 / 1000.; let preferred = if is_preferred { " (preferred)" } else { "" }; println!(" Current mode: {width}x{height} @ {refresh:.3} Hz{preferred}"); - } else { - println!(" Disabled"); } + } - if let Some((width, height)) = physical_size { - println!(" Physical size: {width}x{height} mm"); - } else { - println!(" Physical size: unknown"); - } + if let Some((width, height)) = physical_size { + println!(" Physical size: {width}x{height} mm"); + } else { + println!(" Physical size: unknown"); + } - if let Some(logical) = logical { - let LogicalOutput { - x, - y, - width, - height, - scale, - transform, - } = logical; - println!(" Logical position: {x}, {y}"); - println!(" Logical size: {width}x{height}"); - println!(" Scale: {scale}"); - - let transform = match transform { - niri_ipc::Transform::Normal => "normal", - niri_ipc::Transform::_90 => "90° counter-clockwise", - niri_ipc::Transform::_180 => "180°", - niri_ipc::Transform::_270 => "270° counter-clockwise", - niri_ipc::Transform::Flipped => "flipped horizontally", - niri_ipc::Transform::Flipped90 => { - "90° counter-clockwise, flipped horizontally" - } - niri_ipc::Transform::Flipped180 => "flipped vertically", - niri_ipc::Transform::Flipped270 => { - "270° counter-clockwise, flipped horizontally" - } - }; - println!(" Transform: {transform}"); - } + if let Some(logical) = logical { + let LogicalOutput { + x, + y, + width, + height, + scale, + transform, + } = logical; + println!(" Logical position: {x}, {y}"); + println!(" Logical size: {width}x{height}"); + println!(" Scale: {scale}"); - println!(" Available modes:"); - for (idx, mode) in modes.into_iter().enumerate() { - let Mode { - width, - height, - refresh_rate, - is_preferred, - } = mode; - let refresh = refresh_rate as f64 / 1000.; + let transform = match transform { + niri_ipc::Transform::Normal => "normal", + niri_ipc::Transform::_90 => "90° counter-clockwise", + niri_ipc::Transform::_180 => "180°", + niri_ipc::Transform::_270 => "270° counter-clockwise", + niri_ipc::Transform::Flipped => "flipped horizontally", + niri_ipc::Transform::Flipped90 => "90° counter-clockwise, flipped horizontally", + niri_ipc::Transform::Flipped180 => "flipped vertically", + niri_ipc::Transform::Flipped270 => { + "270° counter-clockwise, flipped horizontally" + } + }; + println!(" Transform: {transform}"); + } - let is_current = Some(idx) == current_mode; - let qualifier = match (is_current, is_preferred) { - (true, true) => " (current, preferred)", - (true, false) => " (current)", - (false, true) => " (preferred)", - (false, false) => "", - }; + println!(" Available modes:"); + for (idx, mode) in modes.into_iter().enumerate() { + let Mode { + width, + height, + refresh_rate, + is_preferred, + } = mode; + let refresh = refresh_rate as f64 / 1000.; - println!(" {width}x{height}@{refresh:.3}{qualifier}"); - } - println!(); - } - } - Msg::FocusedWindow => { - let Response::FocusedWindow(window) = response else { - bail!("unexpected response: expected FocusedWindow, got {response:?}"); - }; + let is_current = Some(idx) == current_mode; + let qualifier = match (is_current, is_preferred) { + (true, true) => " (current, preferred)", + (true, false) => " (current)", + (false, true) => " (preferred)", + (false, false) => "", + }; - if json { - let window = serde_json::to_string(&window).context("error formatting response")?; - println!("{window}"); - return Ok(()); + println!(" {width}x{height}@{refresh:.3}{qualifier}"); } + println!(); + } + } +} - if let Some(window) = window { - println!("Focused window:"); +impl MsgRequest for FocusedWindowRequest { + fn show_to_human(response: Self::Response) { + if let Some(window) = response { + println!("Focused window:"); - if let Some(title) = window.title { - println!(" Title: \"{title}\""); - } else { - println!(" Title: (unset)"); - } + if let Some(title) = window.title { + println!(" Title: \"{title}\""); + } else { + println!(" Title: (unset)"); + } - if let Some(app_id) = window.app_id { - println!(" App ID: \"{app_id}\""); - } else { - println!(" App ID: (unset)"); - } + if let Some(app_id) = window.app_id { + println!(" App ID: \"{app_id}\""); } else { - println!("No window is focused."); + println!(" App ID: (unset)"); } - } - Msg::Action { .. } => { - let Response::Handled = response else { - bail!("unexpected response: expected Handled, got {response:?}"); - }; + } else { + println!("No window is focused."); } } +} - Ok(()) +impl MsgRequest for ActionRequest { + fn show_to_human(response: Self::Response) { + response + } } diff --git a/src/ipc/server.rs b/src/ipc/server.rs index d3c2de600..e10a001ea 100644 --- a/src/ipc/server.rs +++ b/src/ipc/server.rs @@ -9,7 +9,10 @@ use calloop::io::Async; use directories::BaseDirs; use futures_util::io::{AsyncReadExt, BufReader}; use futures_util::{AsyncBufReadExt, AsyncWriteExt, StreamExt}; -use niri_ipc::{Reply, Request, Response}; +use niri_ipc::{ + ActionRequest, ErrorRequest, FocusedWindowRequest, OutputRequest, Reply, Request, + RequestMessage, RequestType, VersionRequest, +}; use smithay::desktop::Window; use smithay::reexports::calloop::generic::Generic; use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction}; @@ -121,9 +124,7 @@ async fn handle_client(ctx: ClientCtx, stream: Async<'_, UnixStream>) -> anyhow: Err(err) => return Err(err).context("error reading line"), }; - let reply: Reply = serde_json::from_str(&line) - .map_err(|err| format!("error parsing request: {err}")) - .and_then(|req| process(&ctx, req)); + let reply = process(&ctx, line); if let Err(err) = &reply { warn!("error processing IPC request: {err:?}"); @@ -141,17 +142,79 @@ async fn handle_client(ctx: ClientCtx, stream: Async<'_, UnixStream>) -> anyhow: Ok(()) } -fn process(ctx: &ClientCtx, request: Request) -> Reply { - let response = match request { - Request::ReturnError => return Err("client wanted an error".into()), - Request::Version => Response::Version(version()), - Request::Outputs => { - let ipc_outputs = ctx.ipc_outputs.lock().unwrap().clone(); - Response::Outputs(ipc_outputs) - } - Request::FocusedWindow => { - let window = ctx.ipc_focused_window.lock().unwrap().clone(); - let window = window.map(|window| { +trait HandleRequest: Request { + fn handle(self, ctx: &ClientCtx) -> Reply; +} + +fn process(ctx: &ClientCtx, line: String) -> Reply { + let request: RequestMessage = serde_json::from_str(&line).map_err(|err| { + warn!("error parsing IPC request: {err:?}"); + "error parsing request" + })?; + + macro_rules! handle { + ($($variant:ident => $type:ty,)*) => { + match request.request_type { + $( + RequestType::$variant => { + let request = serde_json::from_value::<$type>(request.request_body).map_err(|err| + { + warn!("error parsing IPC request: {err:?}"); + "error parsing request" + })?; + HandleRequest::handle(request, ctx).and_then(|v| { + serde_json::to_value(v).map_err(|err| { + warn!("error serializing response to IPC request: {err:?}"); + "error serializing response".into() + }) + }) + } + )* + } + }; + } + + handle!( + ReturnError => ErrorRequest, + Version => VersionRequest, + Outputs => OutputRequest, + FocusedWindow => FocusedWindowRequest, + Action => ActionRequest, + ) +} + +impl HandleRequest for ErrorRequest { + fn handle(self, _ctx: &ClientCtx) -> Reply { + Err("client wanted an error".into()) + } +} + +impl HandleRequest for VersionRequest { + fn handle(self, _ctx: &ClientCtx) -> Reply { + Ok(version()) + } +} + +impl HandleRequest for OutputRequest { + fn handle(self, ctx: &ClientCtx) -> Reply { + Ok(ctx + .ipc_outputs + .lock() + .unwrap() + .clone() + .into_iter() + .collect()) + } +} + +impl HandleRequest for FocusedWindowRequest { + fn handle(self, ctx: &ClientCtx) -> Reply { + Ok(ctx + .ipc_focused_window + .lock() + .unwrap() + .clone() + .map(|window| { let wl_surface = window.toplevel().expect("no X11 support").wl_surface(); with_states(wl_surface, |states| { let role = states @@ -166,17 +229,15 @@ fn process(ctx: &ClientCtx, request: Request) -> Reply { app_id: role.app_id.clone(), } }) - }); - Response::FocusedWindow(window) - } - Request::Action(action) => { - let action = niri_config::Action::from(action); - ctx.event_loop.insert_idle(move |state| { - state.do_action(action); - }); - Response::Handled - } - }; + })) + } +} - Ok(response) +impl HandleRequest for ActionRequest { + fn handle(self, ctx: &ClientCtx) -> Reply { + ctx.event_loop.insert_idle(move |state| { + state.do_action(self.0.into()); + }); + Ok(()) + } }