forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB64a9351Ivan Molodetskikh2 years ago1319 commits

server.rs591 lines, 19.9 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_ipc::state::{EventStreamState, EventStreamStatePart as _};
17use niri_ipc::{Event, KeyboardLayouts, OutputConfigChanged, Reply, Request, Response, Workspace};
18use smithay::input::keyboard::XkbContextHandler;
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 pub fn keyboard_layout_switched(&self, new_idx: u8) {
120 let mut state = self.event_stream_state.borrow_mut();
121 let state = &mut state.keyboard_layouts;
122
123 let event = Event::KeyboardLayoutSwitched { idx: new_idx };
124 state.apply(event.clone());
125 self.send_event(event);
126 }
127}
128
129impl Drop for IpcServer {
130 fn drop(&mut self) {
131 let _ = unlink(&self.socket_path);
132 }
133}
134
135fn socket_dir() -> PathBuf {
136 BaseDirs::new()
137 .as_ref()
138 .and_then(|x| x.runtime_dir())
139 .map(|x| x.to_owned())
140 .unwrap_or_else(env::temp_dir)
141}
142
143fn on_new_ipc_client(state: &mut State, stream: UnixStream) {
144 let _span = tracy_client::span!("on_new_ipc_client");
145 trace!("new IPC client connected");
146
147 let stream = match state.niri.event_loop.adapt_io(stream) {
148 Ok(stream) => stream,
149 Err(err) => {
150 warn!("error making IPC stream async: {err:?}");
151 return;
152 }
153 };
154
155 let ipc_server = state.niri.ipc_server.as_ref().unwrap();
156
157 let ctx = ClientCtx {
158 event_loop: state.niri.event_loop.clone(),
159 scheduler: state.niri.scheduler.clone(),
160 ipc_outputs: state.backend.ipc_outputs(),
161 event_streams: ipc_server.event_streams.clone(),
162 event_stream_state: ipc_server.event_stream_state.clone(),
163 };
164
165 let future = async move {
166 if let Err(err) = handle_client(ctx, stream).await {
167 warn!("error handling IPC client: {err:?}");
168 }
169 };
170 if let Err(err) = state.niri.scheduler.schedule(future) {
171 warn!("error scheduling IPC stream future: {err:?}");
172 }
173}
174
175async fn handle_client(ctx: ClientCtx, stream: Async<'static, UnixStream>) -> anyhow::Result<()> {
176 let (read, mut write) = stream.split();
177 let mut buf = String::new();
178
179 // Read a single line to allow extensibility in the future to keep reading.
180 BufReader::new(read)
181 .read_line(&mut buf)
182 .await
183 .context("error reading request")?;
184
185 let request = serde_json::from_str(&buf)
186 .context("error parsing request")
187 .map_err(|err| err.to_string());
188 let requested_error = matches!(request, Ok(Request::ReturnError));
189 let requested_event_stream = matches!(request, Ok(Request::EventStream));
190
191 let reply = match request {
192 Ok(request) => process(&ctx, request).await,
193 Err(err) => Err(err),
194 };
195
196 if let Err(err) = &reply {
197 if !requested_error {
198 warn!("error processing IPC request: {err:?}");
199 }
200 }
201
202 let mut buf = serde_json::to_vec(&reply).context("error formatting reply")?;
203 buf.push(b'\n');
204 write.write_all(&buf).await.context("error writing reply")?;
205
206 if requested_event_stream {
207 let (events_tx, events_rx) = async_channel::bounded(EVENT_STREAM_BUFFER_SIZE);
208 let (disconnect_tx, disconnect_rx) = async_channel::bounded(1);
209
210 // Spawn a task for the client.
211 let client = EventStreamClient {
212 events: events_rx,
213 disconnect: disconnect_rx,
214 write: Box::new(write) as _,
215 };
216 let future = async move {
217 if let Err(err) = handle_event_stream_client(client).await {
218 warn!("error handling IPC event stream client: {err:?}");
219 }
220 };
221 if let Err(err) = ctx.scheduler.schedule(future) {
222 warn!("error scheduling IPC event stream future: {err:?}");
223 }
224
225 // Send the initial state.
226 {
227 let state = ctx.event_stream_state.borrow();
228 for event in state.replicate() {
229 events_tx
230 .try_send(event)
231 .expect("initial event burst had more events than buffer size");
232 }
233 }
234
235 // Add it to the list.
236 {
237 let mut streams = ctx.event_streams.borrow_mut();
238 let sender = EventStreamSender {
239 events: events_tx,
240 disconnect: disconnect_tx,
241 };
242 streams.push(sender);
243 }
244 }
245
246 Ok(())
247}
248
249async fn process(ctx: &ClientCtx, request: Request) -> Reply {
250 let response = match request {
251 Request::ReturnError => return Err(String::from("example compositor error")),
252 Request::Version => Response::Version(version()),
253 Request::Outputs => {
254 let ipc_outputs = ctx.ipc_outputs.lock().unwrap().clone();
255 let outputs = ipc_outputs.values().cloned().map(|o| (o.name.clone(), o));
256 Response::Outputs(outputs.collect())
257 }
258 Request::Workspaces => {
259 let state = ctx.event_stream_state.borrow();
260 let workspaces = state.workspaces.workspaces.values().cloned().collect();
261 Response::Workspaces(workspaces)
262 }
263 Request::Windows => {
264 let state = ctx.event_stream_state.borrow();
265 let windows = state.windows.windows.values().cloned().collect();
266 Response::Windows(windows)
267 }
268 Request::KeyboardLayouts => {
269 let state = ctx.event_stream_state.borrow();
270 let layout = state.keyboard_layouts.keyboard_layouts.clone();
271 let layout = layout.expect("keyboard layouts should be set at startup");
272 Response::KeyboardLayouts(layout)
273 }
274 Request::FocusedWindow => {
275 let state = ctx.event_stream_state.borrow();
276 let windows = &state.windows.windows;
277 let window = windows.values().find(|win| win.is_focused).cloned();
278 Response::FocusedWindow(window)
279 }
280 Request::Action(action) => {
281 let (tx, rx) = async_channel::bounded(1);
282
283 let action = niri_config::Action::from(action);
284 ctx.event_loop.insert_idle(move |state| {
285 state.do_action(action, false);
286 let _ = tx.send_blocking(());
287 });
288
289 // Wait until the action has been processed before returning. This is important for a
290 // few actions, for instance for DoScreenTransition this wait ensures that the screen
291 // contents were sampled into the texture.
292 let _ = rx.recv().await;
293 Response::Handled
294 }
295 Request::Output { output, action } => {
296 let ipc_outputs = ctx.ipc_outputs.lock().unwrap();
297 let found = ipc_outputs
298 .values()
299 .any(|o| o.name.eq_ignore_ascii_case(&output));
300 let response = if found {
301 OutputConfigChanged::Applied
302 } else {
303 OutputConfigChanged::OutputWasMissing
304 };
305 drop(ipc_outputs);
306
307 ctx.event_loop.insert_idle(move |state| {
308 state.apply_transient_output_config(&output, action);
309 });
310
311 Response::OutputConfigChanged(response)
312 }
313 Request::FocusedOutput => {
314 let (tx, rx) = async_channel::bounded(1);
315 ctx.event_loop.insert_idle(move |state| {
316 let active_output = state
317 .niri
318 .layout
319 .active_output()
320 .map(|output| output.name());
321
322 let output = active_output.and_then(|active_output| {
323 state
324 .backend
325 .ipc_outputs()
326 .lock()
327 .unwrap()
328 .values()
329 .find(|o| o.name == active_output)
330 .cloned()
331 });
332
333 let _ = tx.send_blocking(output);
334 });
335 let result = rx.recv().await;
336 let output = result.map_err(|_| String::from("error getting active output info"))?;
337 Response::FocusedOutput(output)
338 }
339 Request::EventStream => Response::Handled,
340 };
341
342 Ok(response)
343}
344
345async fn handle_event_stream_client(client: EventStreamClient) -> anyhow::Result<()> {
346 let EventStreamClient {
347 events,
348 disconnect,
349 mut write,
350 } = client;
351
352 while let Ok(event) = events.recv().await {
353 let mut buf = serde_json::to_vec(&event).context("error formatting event")?;
354 buf.push(b'\n');
355
356 let res = select_biased! {
357 _ = disconnect.recv().fuse() => return Ok(()),
358 res = write.write_all(&buf).fuse() => res,
359 };
360
361 match res {
362 Ok(()) => (),
363 // Normal client disconnection.
364 Err(err) if err.kind() == io::ErrorKind::BrokenPipe => return Ok(()),
365 res @ Err(_) => res.context("error writing event")?,
366 }
367 }
368
369 Ok(())
370}
371
372fn make_ipc_window(mapped: &Mapped, workspace_id: Option<WorkspaceId>) -> niri_ipc::Window {
373 let wl_surface = mapped.toplevel().wl_surface();
374 with_states(wl_surface, |states| {
375 let role = states
376 .data_map
377 .get::<XdgToplevelSurfaceData>()
378 .unwrap()
379 .lock()
380 .unwrap();
381
382 niri_ipc::Window {
383 id: mapped.id().get(),
384 title: role.title.clone(),
385 app_id: role.app_id.clone(),
386 workspace_id: workspace_id.map(|id| id.get()),
387 is_focused: mapped.is_focused(),
388 }
389 })
390}
391
392impl State {
393 pub fn ipc_keyboard_layouts_changed(&mut self) {
394 let keyboard = self.niri.seat.get_keyboard().unwrap();
395 let keyboard_layouts = keyboard.with_xkb_state(self, |context| {
396 let layouts = context.keymap().layouts();
397 KeyboardLayouts {
398 names: layouts.map(str::to_owned).collect(),
399 current_idx: context.active_layout().0 as u8,
400 }
401 });
402
403 let Some(server) = &self.niri.ipc_server else {
404 return;
405 };
406
407 let mut state = server.event_stream_state.borrow_mut();
408 let state = &mut state.keyboard_layouts;
409
410 let event = Event::KeyboardLayoutsChanged { keyboard_layouts };
411 state.apply(event.clone());
412 server.send_event(event);
413 }
414
415 pub fn ipc_refresh_layout(&mut self) {
416 self.ipc_refresh_workspaces();
417 self.ipc_refresh_windows();
418 }
419
420 fn ipc_refresh_workspaces(&mut self) {
421 let Some(server) = &self.niri.ipc_server else {
422 return;
423 };
424
425 let _span = tracy_client::span!("State::ipc_refresh_workspaces");
426
427 let mut state = server.event_stream_state.borrow_mut();
428 let state = &mut state.workspaces;
429
430 let mut events = Vec::new();
431 let layout = &self.niri.layout;
432 let focused_ws_id = layout.active_workspace().map(|ws| ws.id().get());
433
434 // Check for workspace changes.
435 let mut seen = HashSet::new();
436 let mut need_workspaces_changed = false;
437 for (mon, ws_idx, ws) in layout.workspaces() {
438 let id = ws.id().get();
439 seen.insert(id);
440
441 let Some(ipc_ws) = state.workspaces.get(&id) else {
442 // A new workspace was added.
443 need_workspaces_changed = true;
444 break;
445 };
446
447 // Check for any changes that we can't signal as individual events.
448 let output_name = mon.map(|mon| mon.output_name());
449 if ipc_ws.idx != u8::try_from(ws_idx + 1).unwrap_or(u8::MAX)
450 || ipc_ws.name != ws.name
451 || ipc_ws.output.as_ref() != output_name
452 {
453 need_workspaces_changed = true;
454 break;
455 }
456
457 let active_window_id = ws.active_window().map(|win| win.id().get());
458 if ipc_ws.active_window_id != active_window_id {
459 events.push(Event::WorkspaceActiveWindowChanged {
460 workspace_id: id,
461 active_window_id,
462 });
463 }
464
465 // Check if this workspace became focused.
466 let is_focused = Some(id) == focused_ws_id;
467 if is_focused && !ipc_ws.is_focused {
468 events.push(Event::WorkspaceActivated { id, focused: true });
469 continue;
470 }
471
472 // Check if this workspace became active.
473 let is_active = mon.map_or(false, |mon| mon.active_workspace_idx == ws_idx);
474 if is_active && !ipc_ws.is_active {
475 events.push(Event::WorkspaceActivated { id, focused: false });
476 }
477 }
478
479 // Check if any workspaces were removed.
480 if !need_workspaces_changed && state.workspaces.keys().any(|id| !seen.contains(id)) {
481 need_workspaces_changed = true;
482 }
483
484 if need_workspaces_changed {
485 events.clear();
486
487 let workspaces = layout
488 .workspaces()
489 .map(|(mon, ws_idx, ws)| {
490 let id = ws.id().get();
491 Workspace {
492 id,
493 idx: u8::try_from(ws_idx + 1).unwrap_or(u8::MAX),
494 name: ws.name.clone(),
495 output: mon.map(|mon| mon.output_name().clone()),
496 is_active: mon.map_or(false, |mon| mon.active_workspace_idx == ws_idx),
497 is_focused: Some(id) == focused_ws_id,
498 active_window_id: ws.active_window().map(|win| win.id().get()),
499 }
500 })
501 .collect();
502
503 events.push(Event::WorkspacesChanged { workspaces });
504 }
505
506 for event in events {
507 state.apply(event.clone());
508 server.send_event(event);
509 }
510 }
511
512 fn ipc_refresh_windows(&mut self) {
513 let Some(server) = &self.niri.ipc_server else {
514 return;
515 };
516
517 let _span = tracy_client::span!("State::ipc_refresh_windows");
518
519 let mut state = server.event_stream_state.borrow_mut();
520 let state = &mut state.windows;
521
522 let mut events = Vec::new();
523 let layout = &self.niri.layout;
524
525 // Check for window changes.
526 let mut seen = HashSet::new();
527 let mut focused_id = None;
528 layout.with_windows(|mapped, _, ws_id| {
529 let id = mapped.id().get();
530 seen.insert(id);
531
532 if mapped.is_focused() {
533 focused_id = Some(id);
534 }
535
536 let Some(ipc_win) = state.windows.get(&id) else {
537 let window = make_ipc_window(mapped, Some(ws_id));
538 events.push(Event::WindowOpenedOrChanged { window });
539 return;
540 };
541
542 let workspace_id = Some(ws_id.get());
543 let mut changed = ipc_win.workspace_id != workspace_id;
544
545 let wl_surface = mapped.toplevel().wl_surface();
546 changed |= with_states(wl_surface, |states| {
547 let role = states
548 .data_map
549 .get::<XdgToplevelSurfaceData>()
550 .unwrap()
551 .lock()
552 .unwrap();
553
554 ipc_win.title != role.title || ipc_win.app_id != role.app_id
555 });
556
557 if changed {
558 let window = make_ipc_window(mapped, Some(ws_id));
559 events.push(Event::WindowOpenedOrChanged { window });
560 return;
561 }
562
563 if mapped.is_focused() && !ipc_win.is_focused {
564 events.push(Event::WindowFocusChanged { id: Some(id) });
565 }
566 });
567
568 // Check for closed windows.
569 let mut ipc_focused_id = None;
570 for (id, ipc_win) in &state.windows {
571 if !seen.contains(id) {
572 events.push(Event::WindowClosed { id: *id });
573 }
574
575 if ipc_win.is_focused {
576 ipc_focused_id = Some(id);
577 }
578 }
579
580 // Extra check for focus becoming None, since the checks above only work for focus becoming
581 // a different window.
582 if focused_id.is_none() && ipc_focused_id.is_some() {
583 events.push(Event::WindowFocusChanged { id: None });
584 }
585
586 for event in events {
587 state.apply(event.clone());
588 server.send_event(event);
589 }
590 }
591}