forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBdde9214Ivan Molodetskikh1 year ago1835 commits

server.rs650 lines, 22.8 KiBHistoryRawDownload
1use std::cell::RefCell;
2use std::collections::HashSet;
3use std::ffi::OsStr;
4use std::os::unix::net::{UnixListener, UnixStream};
5use std::path::PathBuf;
6use std::rc::Rc;
7use std::sync::{Arc, Mutex};
8use std::{env, io, process};
9
10use anyhow::Context;
11use async_channel::{Receiver, Sender, TrySendError};
12use calloop::futures::Scheduler;
13use calloop::io::Async;
14use directories::BaseDirs;
15use futures_util::io::{AsyncReadExt, BufReader};
16use futures_util::{select_biased, AsyncBufReadExt, AsyncWrite, AsyncWriteExt, FutureExt as _};
17use niri_config::OutputName;
18use niri_ipc::state::{EventStreamState, EventStreamStatePart as _};
19use niri_ipc::{Event, KeyboardLayouts, OutputConfigChanged, Reply, Request, Response, Workspace};
20use smithay::desktop::layer_map_for_output;
21use smithay::reexports::calloop::generic::Generic;
22use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};
23use smithay::reexports::rustix::fs::unlink;
24use smithay::wayland::shell::wlr_layer::{KeyboardInteractivity, Layer};
25
26use crate::backend::IpcOutputMap;
27use crate::layout::workspace::WorkspaceId;
28use crate::niri::State;
29use crate::utils::{version, with_toplevel_role};
30use crate::window::Mapped;
31
32// If an event stream client fails to read events fast enough that we accumulate more than this
33// number in our buffer, we drop that event stream client.
34const EVENT_STREAM_BUFFER_SIZE: usize = 64;
35
36pub struct IpcServer {
37 /// Path to the IPC socket.
38 ///
39 /// This is `None` when creating `IpcServer` without a socket.
40 pub socket_path: Option<PathBuf>,
41 event_streams: Rc<RefCell<Vec<EventStreamSender>>>,
42 event_stream_state: Rc<RefCell<EventStreamState>>,
43}
44
45struct ClientCtx {
46 event_loop: LoopHandle<'static, State>,
47 scheduler: Scheduler<()>,
48 ipc_outputs: Arc<Mutex<IpcOutputMap>>,
49 event_streams: Rc<RefCell<Vec<EventStreamSender>>>,
50 event_stream_state: Rc<RefCell<EventStreamState>>,
51}
52
53struct EventStreamClient {
54 events: Receiver<Event>,
55 disconnect: Receiver<()>,
56 write: Box<dyn AsyncWrite + Unpin>,
57}
58
59struct EventStreamSender {
60 events: Sender<Event>,
61 disconnect: Sender<()>,
62}
63
64impl IpcServer {
65 pub fn start(
66 event_loop: &LoopHandle<'static, State>,
67 wayland_socket_name: Option<&OsStr>,
68 ) -> anyhow::Result<Self> {
69 let _span = tracy_client::span!("Ipc::start");
70
71 let socket_path = if let Some(wayland_socket_name) = wayland_socket_name {
72 let wayland_socket_name = wayland_socket_name.to_string_lossy();
73 let socket_name = format!("niri.{wayland_socket_name}.{}.sock", process::id());
74 let mut socket_path = socket_dir();
75 socket_path.push(socket_name);
76
77 let listener = UnixListener::bind(&socket_path).context("error binding socket")?;
78 listener
79 .set_nonblocking(true)
80 .context("error setting socket to non-blocking")?;
81
82 let source = Generic::new(listener, Interest::READ, Mode::Level);
83 event_loop
84 .insert_source(source, |_, socket, state| {
85 match socket.accept() {
86 Ok((stream, _)) => on_new_ipc_client(state, stream),
87 Err(e) if e.kind() == io::ErrorKind::WouldBlock => (),
88 Err(e) => return Err(e),
89 }
90
91 Ok(PostAction::Continue)
92 })
93 .unwrap();
94
95 Some(socket_path)
96 } else {
97 None
98 };
99
100 Ok(Self {
101 socket_path,
102 event_streams: Rc::new(RefCell::new(Vec::new())),
103 event_stream_state: Rc::new(RefCell::new(EventStreamState::default())),
104 })
105 }
106
107 fn send_event(&self, event: Event) {
108 let mut streams = self.event_streams.borrow_mut();
109 let mut to_remove = Vec::new();
110 for (idx, stream) in streams.iter_mut().enumerate() {
111 match stream.events.try_send(event.clone()) {
112 Ok(()) => (),
113 Err(TrySendError::Closed(_)) => to_remove.push(idx),
114 Err(TrySendError::Full(_)) => {
115 warn!(
116 "disconnecting IPC event stream client \
117 because it is reading events too slowly"
118 );
119 to_remove.push(idx);
120 }
121 }
122 }
123
124 for idx in to_remove.into_iter().rev() {
125 let stream = streams.swap_remove(idx);
126 let _ = stream.disconnect.send_blocking(());
127 }
128 }
129}
130
131impl Drop for IpcServer {
132 fn drop(&mut self) {
133 if let Some(socket_path) = &self.socket_path {
134 let _ = unlink(socket_path);
135 }
136 }
137}
138
139fn socket_dir() -> PathBuf {
140 BaseDirs::new()
141 .as_ref()
142 .and_then(|x| x.runtime_dir())
143 .map(|x| x.to_owned())
144 .unwrap_or_else(env::temp_dir)
145}
146
147fn on_new_ipc_client(state: &mut State, stream: UnixStream) {
148 let _span = tracy_client::span!("on_new_ipc_client");
149 trace!("new IPC client connected");
150
151 let stream = match state.niri.event_loop.adapt_io(stream) {
152 Ok(stream) => stream,
153 Err(err) => {
154 warn!("error making IPC stream async: {err:?}");
155 return;
156 }
157 };
158
159 let ipc_server = state.niri.ipc_server.as_ref().unwrap();
160
161 let ctx = ClientCtx {
162 event_loop: state.niri.event_loop.clone(),
163 scheduler: state.niri.scheduler.clone(),
164 ipc_outputs: state.backend.ipc_outputs(),
165 event_streams: ipc_server.event_streams.clone(),
166 event_stream_state: ipc_server.event_stream_state.clone(),
167 };
168
169 let future = async move {
170 if let Err(err) = handle_client(ctx, stream).await {
171 warn!("error handling IPC client: {err:?}");
172 }
173 };
174 if let Err(err) = state.niri.scheduler.schedule(future) {
175 warn!("error scheduling IPC stream future: {err:?}");
176 }
177}
178
179async fn handle_client(ctx: ClientCtx, stream: Async<'static, UnixStream>) -> anyhow::Result<()> {
180 let (read, mut write) = stream.split();
181 let mut buf = String::new();
182
183 // Read a single line to allow extensibility in the future to keep reading.
184 BufReader::new(read)
185 .read_line(&mut buf)
186 .await
187 .context("error reading request")?;
188
189 let request = serde_json::from_str(&buf)
190 .context("error parsing request")
191 .map_err(|err| err.to_string());
192 let requested_error = matches!(request, Ok(Request::ReturnError));
193 let requested_event_stream = matches!(request, Ok(Request::EventStream));
194
195 let reply = match request {
196 Ok(request) => process(&ctx, request).await,
197 Err(err) => Err(err),
198 };
199
200 if let Err(err) = &reply {
201 if !requested_error {
202 warn!("error processing IPC request: {err:?}");
203 }
204 }
205
206 let mut buf = serde_json::to_vec(&reply).context("error formatting reply")?;
207 buf.push(b'\n');
208 write.write_all(&buf).await.context("error writing reply")?;
209
210 if requested_event_stream {
211 let (events_tx, events_rx) = async_channel::bounded(EVENT_STREAM_BUFFER_SIZE);
212 let (disconnect_tx, disconnect_rx) = async_channel::bounded(1);
213
214 // Spawn a task for the client.
215 let client = EventStreamClient {
216 events: events_rx,
217 disconnect: disconnect_rx,
218 write: Box::new(write) as _,
219 };
220 let future = async move {
221 if let Err(err) = handle_event_stream_client(client).await {
222 warn!("error handling IPC event stream client: {err:?}");
223 }
224 };
225 if let Err(err) = ctx.scheduler.schedule(future) {
226 warn!("error scheduling IPC event stream future: {err:?}");
227 }
228
229 // Send the initial state.
230 {
231 let state = ctx.event_stream_state.borrow();
232 for event in state.replicate() {
233 events_tx
234 .try_send(event)
235 .expect("initial event burst had more events than buffer size");
236 }
237 }
238
239 // Add it to the list.
240 {
241 let mut streams = ctx.event_streams.borrow_mut();
242 let sender = EventStreamSender {
243 events: events_tx,
244 disconnect: disconnect_tx,
245 };
246 streams.push(sender);
247 }
248 }
249
250 Ok(())
251}
252
253async fn process(ctx: &ClientCtx, request: Request) -> Reply {
254 let response = match request {
255 Request::ReturnError => return Err(String::from("example compositor error")),
256 Request::Version => Response::Version(version()),
257 Request::Outputs => {
258 let ipc_outputs = ctx.ipc_outputs.lock().unwrap().clone();
259 let outputs = ipc_outputs.values().cloned().map(|o| (o.name.clone(), o));
260 Response::Outputs(outputs.collect())
261 }
262 Request::Workspaces => {
263 let state = ctx.event_stream_state.borrow();
264 let workspaces = state.workspaces.workspaces.values().cloned().collect();
265 Response::Workspaces(workspaces)
266 }
267 Request::Windows => {
268 let state = ctx.event_stream_state.borrow();
269 let windows = state.windows.windows.values().cloned().collect();
270 Response::Windows(windows)
271 }
272 Request::Layers => {
273 let (tx, rx) = async_channel::bounded(1);
274 ctx.event_loop.insert_idle(move |state| {
275 let mut layers = Vec::new();
276 for output in state.niri.global_space.outputs() {
277 let name = output.name();
278 for surface in layer_map_for_output(output).layers() {
279 let layer = match surface.layer() {
280 Layer::Background => niri_ipc::Layer::Background,
281 Layer::Bottom => niri_ipc::Layer::Bottom,
282 Layer::Top => niri_ipc::Layer::Top,
283 Layer::Overlay => niri_ipc::Layer::Overlay,
284 };
285 let keyboard_interactivity =
286 match surface.cached_state().keyboard_interactivity {
287 KeyboardInteractivity::None => {
288 niri_ipc::LayerSurfaceKeyboardInteractivity::None
289 }
290 KeyboardInteractivity::Exclusive => {
291 niri_ipc::LayerSurfaceKeyboardInteractivity::Exclusive
292 }
293 KeyboardInteractivity::OnDemand => {
294 niri_ipc::LayerSurfaceKeyboardInteractivity::OnDemand
295 }
296 };
297
298 layers.push(niri_ipc::LayerSurface {
299 namespace: surface.namespace().to_owned(),
300 output: name.clone(),
301 layer,
302 keyboard_interactivity,
303 });
304 }
305 }
306
307 let _ = tx.send_blocking(layers);
308 });
309 let result = rx.recv().await;
310 let layers = result.map_err(|_| String::from("error getting layers info"))?;
311 Response::Layers(layers)
312 }
313 Request::KeyboardLayouts => {
314 let state = ctx.event_stream_state.borrow();
315 let layout = state.keyboard_layouts.keyboard_layouts.clone();
316 let layout = layout.expect("keyboard layouts should be set at startup");
317 Response::KeyboardLayouts(layout)
318 }
319 Request::FocusedWindow => {
320 let state = ctx.event_stream_state.borrow();
321 let windows = &state.windows.windows;
322 let window = windows.values().find(|win| win.is_focused).cloned();
323 Response::FocusedWindow(window)
324 }
325 Request::Action(action) => {
326 let (tx, rx) = async_channel::bounded(1);
327
328 let action = niri_config::Action::from(action);
329 ctx.event_loop.insert_idle(move |state| {
330 // Make sure some logic like workspace clean-up has a chance to run before doing
331 // actions.
332 state.niri.advance_animations();
333 state.do_action(action, false);
334 let _ = tx.send_blocking(());
335 });
336
337 // Wait until the action has been processed before returning. This is important for a
338 // few actions, for instance for DoScreenTransition this wait ensures that the screen
339 // contents were sampled into the texture.
340 let _ = rx.recv().await;
341 Response::Handled
342 }
343 Request::Output { output, action } => {
344 let ipc_outputs = ctx.ipc_outputs.lock().unwrap();
345 let found = ipc_outputs
346 .values()
347 .any(|o| OutputName::from_ipc_output(o).matches(&output));
348 let response = if found {
349 OutputConfigChanged::Applied
350 } else {
351 OutputConfigChanged::OutputWasMissing
352 };
353 drop(ipc_outputs);
354
355 ctx.event_loop.insert_idle(move |state| {
356 state.apply_transient_output_config(&output, action);
357 });
358
359 Response::OutputConfigChanged(response)
360 }
361 Request::FocusedOutput => {
362 let (tx, rx) = async_channel::bounded(1);
363 ctx.event_loop.insert_idle(move |state| {
364 let active_output = state
365 .niri
366 .layout
367 .active_output()
368 .map(|output| output.name());
369
370 let output = active_output.and_then(|active_output| {
371 state
372 .backend
373 .ipc_outputs()
374 .lock()
375 .unwrap()
376 .values()
377 .find(|o| o.name == active_output)
378 .cloned()
379 });
380
381 let _ = tx.send_blocking(output);
382 });
383 let result = rx.recv().await;
384 let output = result.map_err(|_| String::from("error getting active output info"))?;
385 Response::FocusedOutput(output)
386 }
387 Request::EventStream => Response::Handled,
388 };
389
390 Ok(response)
391}
392
393async fn handle_event_stream_client(client: EventStreamClient) -> anyhow::Result<()> {
394 let EventStreamClient {
395 events,
396 disconnect,
397 mut write,
398 } = client;
399
400 while let Ok(event) = events.recv().await {
401 let mut buf = serde_json::to_vec(&event).context("error formatting event")?;
402 buf.push(b'\n');
403
404 let res = select_biased! {
405 _ = disconnect.recv().fuse() => return Ok(()),
406 res = write.write_all(&buf).fuse() => res,
407 };
408
409 match res {
410 Ok(()) => (),
411 // Normal client disconnection.
412 Err(err) if err.kind() == io::ErrorKind::BrokenPipe => return Ok(()),
413 res @ Err(_) => res.context("error writing event")?,
414 }
415 }
416
417 Ok(())
418}
419
420fn make_ipc_window(mapped: &Mapped, workspace_id: Option<WorkspaceId>) -> niri_ipc::Window {
421 with_toplevel_role(mapped.toplevel(), |role| niri_ipc::Window {
422 id: mapped.id().get(),
423 title: role.title.clone(),
424 app_id: role.app_id.clone(),
425 pid: mapped.credentials().map(|c| c.pid),
426 workspace_id: workspace_id.map(|id| id.get()),
427 is_focused: mapped.is_focused(),
428 is_floating: mapped.is_floating(),
429 })
430}
431
432impl State {
433 pub fn ipc_keyboard_layouts_changed(&mut self) {
434 let keyboard = self.niri.seat.get_keyboard().unwrap();
435 let keyboard_layouts = keyboard.with_xkb_state(self, |context| {
436 let xkb = context.xkb().lock().unwrap();
437 let layouts = xkb.layouts();
438 KeyboardLayouts {
439 names: layouts
440 .map(|layout| xkb.layout_name(layout).to_owned())
441 .collect(),
442 current_idx: xkb.active_layout().0 as u8,
443 }
444 });
445
446 let Some(server) = &self.niri.ipc_server else {
447 return;
448 };
449
450 let mut state = server.event_stream_state.borrow_mut();
451 let state = &mut state.keyboard_layouts;
452
453 let event = Event::KeyboardLayoutsChanged { keyboard_layouts };
454 state.apply(event.clone());
455 server.send_event(event);
456 }
457
458 pub fn ipc_refresh_keyboard_layout_index(&mut self) {
459 let keyboard = self.niri.seat.get_keyboard().unwrap();
460 let idx = keyboard.with_xkb_state(self, |context| {
461 let xkb = context.xkb().lock().unwrap();
462 xkb.active_layout().0 as u8
463 });
464
465 let Some(server) = &self.niri.ipc_server else {
466 return;
467 };
468
469 let mut state = server.event_stream_state.borrow_mut();
470 let state = &mut state.keyboard_layouts;
471
472 if state.keyboard_layouts.as_ref().unwrap().current_idx == idx {
473 return;
474 }
475
476 let event = Event::KeyboardLayoutSwitched { idx };
477 state.apply(event.clone());
478 server.send_event(event);
479 }
480
481 pub fn ipc_refresh_layout(&mut self) {
482 self.ipc_refresh_workspaces();
483 self.ipc_refresh_windows();
484 }
485
486 fn ipc_refresh_workspaces(&mut self) {
487 let Some(server) = &self.niri.ipc_server else {
488 return;
489 };
490
491 let _span = tracy_client::span!("State::ipc_refresh_workspaces");
492
493 let mut state = server.event_stream_state.borrow_mut();
494 let state = &mut state.workspaces;
495
496 let mut events = Vec::new();
497 let layout = &self.niri.layout;
498 let focused_ws_id = layout.active_workspace().map(|ws| ws.id().get());
499
500 // Check for workspace changes.
501 let mut seen = HashSet::new();
502 let mut need_workspaces_changed = false;
503 for (mon, ws_idx, ws) in layout.workspaces() {
504 let id = ws.id().get();
505 seen.insert(id);
506
507 let Some(ipc_ws) = state.workspaces.get(&id) else {
508 // A new workspace was added.
509 need_workspaces_changed = true;
510 break;
511 };
512
513 // Check for any changes that we can't signal as individual events.
514 let output_name = mon.map(|mon| mon.output_name());
515 if ipc_ws.idx != u8::try_from(ws_idx + 1).unwrap_or(u8::MAX)
516 || ipc_ws.name.as_ref() != ws.name()
517 || ipc_ws.output.as_ref() != output_name
518 {
519 need_workspaces_changed = true;
520 break;
521 }
522
523 let active_window_id = ws.active_window().map(|win| win.id().get());
524 if ipc_ws.active_window_id != active_window_id {
525 events.push(Event::WorkspaceActiveWindowChanged {
526 workspace_id: id,
527 active_window_id,
528 });
529 }
530
531 // Check if this workspace became focused.
532 let is_focused = Some(id) == focused_ws_id;
533 if is_focused && !ipc_ws.is_focused {
534 events.push(Event::WorkspaceActivated { id, focused: true });
535 continue;
536 }
537
538 // Check if this workspace became active.
539 let is_active = mon.is_some_and(|mon| mon.active_workspace_idx() == ws_idx);
540 if is_active && !ipc_ws.is_active {
541 events.push(Event::WorkspaceActivated { id, focused: false });
542 }
543 }
544
545 // Check if any workspaces were removed.
546 if !need_workspaces_changed && state.workspaces.keys().any(|id| !seen.contains(id)) {
547 need_workspaces_changed = true;
548 }
549
550 if need_workspaces_changed {
551 events.clear();
552
553 let workspaces = layout
554 .workspaces()
555 .map(|(mon, ws_idx, ws)| {
556 let id = ws.id().get();
557 Workspace {
558 id,
559 idx: u8::try_from(ws_idx + 1).unwrap_or(u8::MAX),
560 name: ws.name().cloned(),
561 output: mon.map(|mon| mon.output_name().clone()),
562 is_active: mon.is_some_and(|mon| mon.active_workspace_idx() == ws_idx),
563 is_focused: Some(id) == focused_ws_id,
564 active_window_id: ws.active_window().map(|win| win.id().get()),
565 }
566 })
567 .collect();
568
569 events.push(Event::WorkspacesChanged { workspaces });
570 }
571
572 for event in events {
573 state.apply(event.clone());
574 server.send_event(event);
575 }
576 }
577
578 fn ipc_refresh_windows(&mut self) {
579 let Some(server) = &self.niri.ipc_server else {
580 return;
581 };
582
583 let _span = tracy_client::span!("State::ipc_refresh_windows");
584
585 let mut state = server.event_stream_state.borrow_mut();
586 let state = &mut state.windows;
587
588 let mut events = Vec::new();
589 let layout = &self.niri.layout;
590
591 // Check for window changes.
592 let mut seen = HashSet::new();
593 let mut focused_id = None;
594 layout.with_windows(|mapped, _, ws_id| {
595 let id = mapped.id().get();
596 seen.insert(id);
597
598 if mapped.is_focused() {
599 focused_id = Some(id);
600 }
601
602 let Some(ipc_win) = state.windows.get(&id) else {
603 let window = make_ipc_window(mapped, ws_id);
604 events.push(Event::WindowOpenedOrChanged { window });
605 return;
606 };
607
608 let workspace_id = ws_id.map(|id| id.get());
609 let mut changed =
610 ipc_win.workspace_id != workspace_id || ipc_win.is_floating != mapped.is_floating();
611
612 changed |= with_toplevel_role(mapped.toplevel(), |role| {
613 ipc_win.title != role.title || ipc_win.app_id != role.app_id
614 });
615
616 if changed {
617 let window = make_ipc_window(mapped, ws_id);
618 events.push(Event::WindowOpenedOrChanged { window });
619 return;
620 }
621
622 if mapped.is_focused() && !ipc_win.is_focused {
623 events.push(Event::WindowFocusChanged { id: Some(id) });
624 }
625 });
626
627 // Check for closed windows.
628 let mut ipc_focused_id = None;
629 for (id, ipc_win) in &state.windows {
630 if !seen.contains(id) {
631 events.push(Event::WindowClosed { id: *id });
632 }
633
634 if ipc_win.is_focused {
635 ipc_focused_id = Some(id);
636 }
637 }
638
639 // Extra check for focus becoming None, since the checks above only work for focus becoming
640 // a different window.
641 if focused_id.is_none() && ipc_focused_id.is_some() {
642 events.push(Event::WindowFocusChanged { id: None });
643 }
644
645 for event in events {
646 state.apply(event.clone());
647 server.send_event(event);
648 }
649 }
650}