niri
Clone
https://git.tahinli.com/Tahinli/niri.git
0 watching·0 forks·Rust·GPL-3.0·12.1 MiB·f51dd67·Ivan Molodetskikh·2 years ago·981 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::{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 | |
| 22 | pub struct IpcServer { |
| 23 | pub socket_path: PathBuf, |
| 24 | } |
| 25 | |
| 26 | struct ClientCtx { |
| 27 | event_loop: LoopHandle<'static, State>, |
| 28 | ipc_outputs: Arc<Mutex<IpcOutputMap>>, |
| 29 | ipc_focused_window: Arc<Mutex<Option<Window>>>, |
| 30 | } |
| 31 | |
| 32 | impl IpcServer { |
| 33 | pub fn start( |
| 34 | event_loop: &LoopHandle<'static, State>, |
| 35 | wayland_socket_name: &str, |
| 36 | ) -> anyhow::Result<Self> { |
| 37 | let _span = tracy_client::span!("Ipc::start"); |
| 38 | |
| 39 | let socket_name = format!("niri.{wayland_socket_name}.{}.sock", process::id()); |
| 40 | let mut socket_path = socket_dir(); |
| 41 | socket_path.push(socket_name); |
| 42 | |
| 43 | let listener = UnixListener::bind(&socket_path).context("error binding socket")?; |
| 44 | listener |
| 45 | .set_nonblocking(true) |
| 46 | .context("error setting socket to non-blocking")?; |
| 47 | |
| 48 | let source = Generic::new(listener, Interest::READ, Mode::Level); |
| 49 | event_loop |
| 50 | .insert_source(source, |_, socket, state| { |
| 51 | match socket.accept() { |
| 52 | Ok((stream, _)) => on_new_ipc_client(state, stream), |
| 53 | Err(e) if e.kind() == io::ErrorKind::WouldBlock => (), |
| 54 | Err(e) => return Err(e), |
| 55 | } |
| 56 | |
| 57 | Ok(PostAction::Continue) |
| 58 | }) |
| 59 | .unwrap(); |
| 60 | |
| 61 | Ok(Self { socket_path }) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | impl Drop for IpcServer { |
| 66 | fn drop(&mut self) { |
| 67 | let _ = unlink(&self.socket_path); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | fn socket_dir() -> PathBuf { |
| 72 | BaseDirs::new() |
| 73 | .as_ref() |
| 74 | .and_then(|x| x.runtime_dir()) |
| 75 | .map(|x| x.to_owned()) |
| 76 | .unwrap_or_else(env::temp_dir) |
| 77 | } |
| 78 | |
| 79 | fn on_new_ipc_client(state: &mut State, stream: UnixStream) { |
| 80 | let _span = tracy_client::span!("on_new_ipc_client"); |
| 81 | trace!("new IPC client connected"); |
| 82 | |
| 83 | let stream = match state.niri.event_loop.adapt_io(stream) { |
| 84 | Ok(stream) => stream, |
| 85 | Err(err) => { |
| 86 | warn!("error making IPC stream async: {err:?}"); |
| 87 | return; |
| 88 | } |
| 89 | }; |
| 90 | |
| 91 | let ctx = ClientCtx { |
| 92 | event_loop: state.niri.event_loop.clone(), |
| 93 | ipc_outputs: state.backend.ipc_outputs(), |
| 94 | ipc_focused_window: state.niri.ipc_focused_window.clone(), |
| 95 | }; |
| 96 | |
| 97 | let future = async move { |
| 98 | if let Err(err) = handle_client(ctx, stream).await { |
| 99 | warn!("error handling IPC client: {err:?}"); |
| 100 | } |
| 101 | }; |
| 102 | if let Err(err) = state.niri.scheduler.schedule(future) { |
| 103 | warn!("error scheduling IPC stream future: {err:?}"); |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | async fn handle_client(ctx: ClientCtx, stream: Async<'_, UnixStream>) -> anyhow::Result<()> { |
| 108 | let (read, mut write) = stream.split(); |
| 109 | let mut buf = String::new(); |
| 110 | |
| 111 | // Read a single line to allow extensibility in the future to keep reading. |
| 112 | BufReader::new(read) |
| 113 | .read_line(&mut buf) |
| 114 | .await |
| 115 | .context("error reading request")?; |
| 116 | |
| 117 | let reply = process(&ctx, &buf).map_err(|err| { |
| 118 | warn!("error processing IPC request: {err:?}"); |
| 119 | err.to_string() |
| 120 | }); |
| 121 | |
| 122 | let buf = serde_json::to_vec(&reply).context("error formatting reply")?; |
| 123 | write.write_all(&buf).await.context("error writing reply")?; |
| 124 | |
| 125 | Ok(()) |
| 126 | } |
| 127 | |
| 128 | fn process(ctx: &ClientCtx, buf: &str) -> anyhow::Result<Response> { |
| 129 | let request: Request = serde_json::from_str(buf).context("error parsing request")?; |
| 130 | |
| 131 | let response = match request { |
| 132 | Request::Outputs => { |
| 133 | let ipc_outputs = ctx.ipc_outputs.lock().unwrap().clone(); |
| 134 | Response::Outputs(ipc_outputs) |
| 135 | } |
| 136 | Request::FocusedWindow => { |
| 137 | let window = ctx.ipc_focused_window.lock().unwrap().clone(); |
| 138 | let window = window.map(|window| { |
| 139 | let wl_surface = window.toplevel().expect("no X11 support").wl_surface(); |
| 140 | with_states(wl_surface, |states| { |
| 141 | let role = states |
| 142 | .data_map |
| 143 | .get::<XdgToplevelSurfaceData>() |
| 144 | .unwrap() |
| 145 | .lock() |
| 146 | .unwrap(); |
| 147 | |
| 148 | niri_ipc::Window { |
| 149 | title: role.title.clone(), |
| 150 | app_id: role.app_id.clone(), |
| 151 | } |
| 152 | }) |
| 153 | }); |
| 154 | Response::FocusedWindow(window) |
| 155 | } |
| 156 | Request::Action(action) => { |
| 157 | let action = niri_config::Action::from(action); |
| 158 | ctx.event_loop.insert_idle(move |state| { |
| 159 | state.do_action(action, false); |
| 160 | }); |
| 161 | Response::Handled |
| 162 | } |
| 163 | }; |
| 164 | |
| 165 | Ok(response) |
| 166 | } |