forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB289ae36Ivan Molodetskikh2 years ago1428 commits

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