niri
Clone
https://git.tahinli.com/Tahinli/niri.git
0 watching·0 forks·Rust·GPL-3.0·12.1 MiB·7b3bef1·Suyashtnt·2 years ago·1225 commits
| 1 | use std::os::unix::net::{UnixListener, UnixStream}; |
| 2 | use std::path::PathBuf; |
| 3 | use std::sync::{Arc, Mutex}; |
| 4 | use std::{env, io, process}; |
| 5 | |
| 6 | use anyhow::Context; |
| 7 | use calloop::io::Async; |
| 8 | use directories::BaseDirs; |
| 9 | use futures_util::io::{AsyncReadExt, BufReader}; |
| 10 | use futures_util::{AsyncBufReadExt, AsyncWriteExt}; |
| 11 | use niri_ipc::{OutputConfigChanged, Reply, Request, Response}; |
| 12 | use smithay::desktop::Window; |
| 13 | use smithay::reexports::calloop::generic::Generic; |
| 14 | use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction}; |
| 15 | use smithay::reexports::rustix::fs::unlink; |
| 16 | use smithay::wayland::compositor::with_states; |
| 17 | use smithay::wayland::shell::xdg::XdgToplevelSurfaceData; |
| 18 | |
| 19 | use crate::backend::IpcOutputMap; |
| 20 | use crate::niri::State; |
| 21 | use crate::utils::version; |
| 22 | |
| 23 | pub struct IpcServer { |
| 24 | pub socket_path: PathBuf, |
| 25 | } |
| 26 | |
| 27 | struct ClientCtx { |
| 28 | event_loop: LoopHandle<'static, State>, |
| 29 | ipc_outputs: Arc<Mutex<IpcOutputMap>>, |
| 30 | ipc_focused_window: Arc<Mutex<Option<Window>>>, |
| 31 | } |
| 32 | |
| 33 | impl IpcServer { |
| 34 | pub fn start( |
| 35 | event_loop: &LoopHandle<'static, State>, |
| 36 | wayland_socket_name: &str, |
| 37 | ) -> anyhow::Result<Self> { |
| 38 | let _span = tracy_client::span!("Ipc::start"); |
| 39 | |
| 40 | let socket_name = format!("niri.{wayland_socket_name}.{}.sock", process::id()); |
| 41 | let mut socket_path = socket_dir(); |
| 42 | socket_path.push(socket_name); |
| 43 | |
| 44 | let listener = UnixListener::bind(&socket_path).context("error binding socket")?; |
| 45 | listener |
| 46 | .set_nonblocking(true) |
| 47 | .context("error setting socket to non-blocking")?; |
| 48 | |
| 49 | let source = Generic::new(listener, Interest::READ, Mode::Level); |
| 50 | event_loop |
| 51 | .insert_source(source, |_, socket, state| { |
| 52 | match socket.accept() { |
| 53 | Ok((stream, _)) => on_new_ipc_client(state, stream), |
| 54 | Err(e) if e.kind() == io::ErrorKind::WouldBlock => (), |
| 55 | Err(e) => return Err(e), |
| 56 | } |
| 57 | |
| 58 | Ok(PostAction::Continue) |
| 59 | }) |
| 60 | .unwrap(); |
| 61 | |
| 62 | Ok(Self { socket_path }) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | impl Drop for IpcServer { |
| 67 | fn drop(&mut self) { |
| 68 | let _ = unlink(&self.socket_path); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | fn socket_dir() -> PathBuf { |
| 73 | BaseDirs::new() |
| 74 | .as_ref() |
| 75 | .and_then(|x| x.runtime_dir()) |
| 76 | .map(|x| x.to_owned()) |
| 77 | .unwrap_or_else(env::temp_dir) |
| 78 | } |
| 79 | |
| 80 | fn on_new_ipc_client(state: &mut State, stream: UnixStream) { |
| 81 | let _span = tracy_client::span!("on_new_ipc_client"); |
| 82 | trace!("new IPC client connected"); |
| 83 | |
| 84 | let stream = match state.niri.event_loop.adapt_io(stream) { |
| 85 | Ok(stream) => stream, |
| 86 | Err(err) => { |
| 87 | warn!("error making IPC stream async: {err:?}"); |
| 88 | return; |
| 89 | } |
| 90 | }; |
| 91 | |
| 92 | let ctx = ClientCtx { |
| 93 | event_loop: state.niri.event_loop.clone(), |
| 94 | ipc_outputs: state.backend.ipc_outputs(), |
| 95 | ipc_focused_window: state.niri.ipc_focused_window.clone(), |
| 96 | }; |
| 97 | |
| 98 | let future = async move { |
| 99 | if let Err(err) = handle_client(ctx, stream).await { |
| 100 | warn!("error handling IPC client: {err:?}"); |
| 101 | } |
| 102 | }; |
| 103 | if let Err(err) = state.niri.scheduler.schedule(future) { |
| 104 | warn!("error scheduling IPC stream future: {err:?}"); |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | async fn handle_client(ctx: ClientCtx, stream: Async<'_, UnixStream>) -> anyhow::Result<()> { |
| 109 | let (read, mut write) = stream.split(); |
| 110 | let mut buf = String::new(); |
| 111 | |
| 112 | // Read a single line to allow extensibility in the future to keep reading. |
| 113 | BufReader::new(read) |
| 114 | .read_line(&mut buf) |
| 115 | .await |
| 116 | .context("error reading request")?; |
| 117 | |
| 118 | let request = serde_json::from_str(&buf) |
| 119 | .context("error parsing request") |
| 120 | .map_err(|err| err.to_string()); |
| 121 | let requested_error = matches!(request, Ok(Request::ReturnError)); |
| 122 | |
| 123 | let reply = match request { |
| 124 | Ok(request) => process(&ctx, request).await, |
| 125 | Err(err) => Err(err), |
| 126 | }; |
| 127 | |
| 128 | if let Err(err) = &reply { |
| 129 | if !requested_error { |
| 130 | warn!("error processing IPC request: {err:?}"); |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | let buf = serde_json::to_vec(&reply).context("error formatting reply")?; |
| 135 | write.write_all(&buf).await.context("error writing reply")?; |
| 136 | |
| 137 | Ok(()) |
| 138 | } |
| 139 | |
| 140 | async fn process(ctx: &ClientCtx, request: Request) -> Reply { |
| 141 | let response = match request { |
| 142 | Request::ReturnError => return Err(String::from("example compositor error")), |
| 143 | Request::Version => Response::Version(version()), |
| 144 | Request::Outputs => { |
| 145 | let ipc_outputs = ctx.ipc_outputs.lock().unwrap().clone(); |
| 146 | let outputs = ipc_outputs.values().cloned().map(|o| (o.name.clone(), o)); |
| 147 | Response::Outputs(outputs.collect()) |
| 148 | } |
| 149 | Request::FocusedWindow => { |
| 150 | let window = ctx.ipc_focused_window.lock().unwrap().clone(); |
| 151 | let window = window.map(|window| { |
| 152 | let wl_surface = window.toplevel().expect("no X11 support").wl_surface(); |
| 153 | with_states(wl_surface, |states| { |
| 154 | let role = states |
| 155 | .data_map |
| 156 | .get::<XdgToplevelSurfaceData>() |
| 157 | .unwrap() |
| 158 | .lock() |
| 159 | .unwrap(); |
| 160 | |
| 161 | niri_ipc::Window { |
| 162 | title: role.title.clone(), |
| 163 | app_id: role.app_id.clone(), |
| 164 | } |
| 165 | }) |
| 166 | }); |
| 167 | Response::FocusedWindow(window) |
| 168 | } |
| 169 | Request::Action(action) => { |
| 170 | let (tx, rx) = async_channel::bounded(1); |
| 171 | |
| 172 | let action = niri_config::Action::from(action); |
| 173 | ctx.event_loop.insert_idle(move |state| { |
| 174 | state.do_action(action, false); |
| 175 | let _ = tx.send_blocking(()); |
| 176 | }); |
| 177 | |
| 178 | // Wait until the action has been processed before returning. This is important for a |
| 179 | // few actions, for instance for DoScreenTransition this wait ensures that the screen |
| 180 | // contents were sampled into the texture. |
| 181 | let _ = rx.recv().await; |
| 182 | Response::Handled |
| 183 | } |
| 184 | Request::Output { output, action } => { |
| 185 | let ipc_outputs = ctx.ipc_outputs.lock().unwrap(); |
| 186 | let found = ipc_outputs |
| 187 | .values() |
| 188 | .any(|o| o.name.eq_ignore_ascii_case(&output)); |
| 189 | let response = if found { |
| 190 | OutputConfigChanged::Applied |
| 191 | } else { |
| 192 | OutputConfigChanged::OutputWasMissing |
| 193 | }; |
| 194 | drop(ipc_outputs); |
| 195 | |
| 196 | ctx.event_loop.insert_idle(move |state| { |
| 197 | state.apply_transient_output_config(&output, action); |
| 198 | }); |
| 199 | |
| 200 | Response::OutputConfigChanged(response) |
| 201 | } |
| 202 | Request::Workspaces => { |
| 203 | let (tx, rx) = async_channel::bounded(1); |
| 204 | ctx.event_loop.insert_idle(move |state| { |
| 205 | let workspaces = state.niri.layout.ipc_workspaces(); |
| 206 | let _ = tx.send_blocking(workspaces); |
| 207 | }); |
| 208 | let result = rx.recv().await; |
| 209 | let workspaces = result.map_err(|_| String::from("error getting workspace info"))?; |
| 210 | Response::Workspaces(workspaces) |
| 211 | } |
| 212 | Request::FocusedOutput => { |
| 213 | let (tx, rx) = async_channel::bounded(1); |
| 214 | ctx.event_loop.insert_idle(move |state| { |
| 215 | let active_output = state |
| 216 | .niri |
| 217 | .layout |
| 218 | .active_output() |
| 219 | .map(|output| output.name()); |
| 220 | |
| 221 | let output = active_output.and_then(|active_output| { |
| 222 | state |
| 223 | .backend |
| 224 | .ipc_outputs() |
| 225 | .lock() |
| 226 | .unwrap() |
| 227 | .values() |
| 228 | .find(|o| o.name == active_output) |
| 229 | .cloned() |
| 230 | }); |
| 231 | |
| 232 | let _ = tx.send_blocking(output); |
| 233 | }); |
| 234 | let result = rx.recv().await; |
| 235 | let output = result.map_err(|_| String::from("error getting active output info"))?; |
| 236 | Response::FocusedOutput(output) |
| 237 | } |
| 238 | }; |
| 239 | |
| 240 | Ok(response) |
| 241 | } |