forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBb0eb8adIvan Molodetskikh3 months ago2857 commits

server.rs945 lines, 33.9 KiBHistoryRawDownload
1use std::cell::RefCell;
2use std::collections::HashSet;
3use std::ffi::OsStr;
4use std::os::unix::net::{UnixListener, UnixStream};
5use std::path::{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::{
20 Action, Event, KeyboardLayouts, OutputConfigChanged, Overview, Reply, Request, Response,
21 Timestamp, WindowLayout, Workspace,
22};
23use smithay::desktop::layer_map_for_output;
24use smithay::input::pointer::{
25 CursorIcon, CursorImageStatus, Focus, GrabStartData as PointerGrabStartData,
26};
27use smithay::reexports::calloop::generic::Generic;
28use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};
29use smithay::reexports::rustix::fs::unlink;
30use smithay::utils::SERIAL_COUNTER;
31use smithay::wayland::shell::wlr_layer::{KeyboardInteractivity, Layer};
32
33use crate::backend::IpcOutputMap;
34use crate::input::pick_window_grab::PickWindowGrab;
35use crate::layout::workspace::WorkspaceId;
36use crate::niri::State;
37use crate::utils::{version, with_toplevel_role};
38use crate::window::Mapped;
39
40// If an event stream client fails to read events fast enough that we accumulate more than this
41// number in our buffer, we drop that event stream client.
42const EVENT_STREAM_BUFFER_SIZE: usize = 64;
43
44pub struct IpcServer {
45 /// Path to the IPC socket.
46 ///
47 /// This is `None` when creating `IpcServer` without a socket.
48 pub socket_path: Option<PathBuf>,
49 event_streams: Rc<RefCell<Vec<EventStreamSender>>>,
50 event_stream_state: Rc<RefCell<EventStreamState>>,
51}
52
53struct ClientCtx {
54 event_loop: LoopHandle<'static, State>,
55 scheduler: Scheduler<()>,
56 ipc_outputs: Arc<Mutex<IpcOutputMap>>,
57 event_streams: Rc<RefCell<Vec<EventStreamSender>>>,
58 event_stream_state: Rc<RefCell<EventStreamState>>,
59}
60
61struct EventStreamClient {
62 events: Receiver<Event>,
63 disconnect: Receiver<()>,
64 write: Box<dyn AsyncWrite + Unpin>,
65}
66
67struct EventStreamSender {
68 events: Sender<Event>,
69 disconnect: Sender<()>,
70}
71
72impl IpcServer {
73 pub fn start(
74 event_loop: &LoopHandle<'static, State>,
75 wayland_socket_name: Option<&OsStr>,
76 ) -> anyhow::Result<Self> {
77 let _span = tracy_client::span!("Ipc::start");
78
79 let socket_path = if let Some(wayland_socket_name) = wayland_socket_name {
80 let wayland_socket_name = wayland_socket_name.to_string_lossy();
81 let socket_name = format!("niri.{wayland_socket_name}.{}.sock", process::id());
82 let mut socket_path = socket_dir();
83 socket_path.push(socket_name);
84
85 let listener = UnixListener::bind(&socket_path).context("error binding socket")?;
86 listener
87 .set_nonblocking(true)
88 .context("error setting socket to non-blocking")?;
89
90 let source = Generic::new(listener, Interest::READ, Mode::Level);
91 event_loop
92 .insert_source(source, |_, socket, state| {
93 match socket.accept() {
94 Ok((stream, _)) => on_new_ipc_client(state, stream),
95 Err(e) if e.kind() == io::ErrorKind::WouldBlock => (),
96 Err(e) => return Err(e),
97 }
98
99 Ok(PostAction::Continue)
100 })
101 .unwrap();
102
103 Some(socket_path)
104 } else {
105 None
106 };
107
108 Ok(Self {
109 socket_path,
110 event_streams: Rc::new(RefCell::new(Vec::new())),
111 event_stream_state: Rc::new(RefCell::new(EventStreamState::default())),
112 })
113 }
114
115 fn send_event(&self, event: Event) {
116 let mut streams = self.event_streams.borrow_mut();
117 let mut to_remove = Vec::new();
118 for (idx, stream) in streams.iter_mut().enumerate() {
119 match stream.events.try_send(event.clone()) {
120 Ok(()) => (),
121 Err(TrySendError::Closed(_)) => to_remove.push(idx),
122 Err(TrySendError::Full(_)) => {
123 warn!(
124 "disconnecting IPC event stream client \
125 because it is reading events too slowly"
126 );
127 to_remove.push(idx);
128 }
129 }
130 }
131
132 for idx in to_remove.into_iter().rev() {
133 let stream = streams.swap_remove(idx);
134 let _ = stream.disconnect.send_blocking(());
135 }
136 }
137}
138
139impl Drop for IpcServer {
140 fn drop(&mut self) {
141 if let Some(socket_path) = &self.socket_path {
142 let _ = unlink(socket_path);
143 }
144 }
145}
146
147fn socket_dir() -> PathBuf {
148 BaseDirs::new()
149 .as_ref()
150 .and_then(|x| x.runtime_dir())
151 .map(|x| x.to_owned())
152 .unwrap_or_else(env::temp_dir)
153}
154
155fn on_new_ipc_client(state: &mut State, stream: UnixStream) {
156 let _span = tracy_client::span!("on_new_ipc_client");
157 trace!("new IPC client connected");
158
159 let stream = match state.niri.event_loop.adapt_io(stream) {
160 Ok(stream) => stream,
161 Err(err) => {
162 warn!("error making IPC stream async: {err:?}");
163 return;
164 }
165 };
166
167 let ipc_server = state.niri.ipc_server.as_ref().unwrap();
168
169 let ctx = ClientCtx {
170 event_loop: state.niri.event_loop.clone(),
171 scheduler: state.niri.scheduler.clone(),
172 ipc_outputs: state.backend.ipc_outputs(),
173 event_streams: ipc_server.event_streams.clone(),
174 event_stream_state: ipc_server.event_stream_state.clone(),
175 };
176
177 let future = async move {
178 if let Err(err) = handle_client(ctx, stream).await {
179 warn!("error handling IPC client: {err:?}");
180 }
181 };
182 if let Err(err) = state.niri.scheduler.schedule(future) {
183 warn!("error scheduling IPC stream future: {err:?}");
184 }
185}
186
187async fn handle_client(ctx: ClientCtx, stream: Async<'static, UnixStream>) -> anyhow::Result<()> {
188 let (read, mut write) = stream.split();
189 let mut read = BufReader::new(read);
190
191 loop {
192 // Don't keep buf around to avoid clients wasting RAM by filling it with bogus data.
193 let mut buf = Vec::new();
194 let res = read.read_until(b'\n', &mut buf).await;
195 match res {
196 Ok(0) => return Ok(()),
197 Ok(_) => (),
198 // Normal client disconnection.
199 Err(err) if err.kind() == io::ErrorKind::BrokenPipe => return Ok(()),
200 Err(err) => {
201 return Err(err).context("error reading request");
202 }
203 }
204
205 let request = serde_json::from_slice(&buf)
206 .context("error parsing request")
207 .map_err(|err| err.to_string());
208 let requested_error = matches!(request, Ok(Request::ReturnError));
209 let requested_event_stream = matches!(request, Ok(Request::EventStream));
210
211 let reply = match request {
212 Ok(request) => process(&ctx, request).await,
213 Err(err) => Err(err),
214 };
215
216 if let Err(err) = &reply {
217 if !requested_error {
218 warn!("error processing IPC request: {err:?}");
219 }
220 }
221
222 buf.clear();
223 serde_json::to_writer(&mut buf, &reply).context("error formatting reply")?;
224 buf.push(b'\n');
225 write.write_all(&buf).await.context("error writing reply")?;
226
227 if requested_event_stream {
228 let (events_tx, events_rx) = async_channel::bounded(EVENT_STREAM_BUFFER_SIZE);
229 let (disconnect_tx, disconnect_rx) = async_channel::bounded(1);
230
231 // Spawn a task for the client.
232 let client = EventStreamClient {
233 events: events_rx,
234 disconnect: disconnect_rx,
235 write: Box::new(write) as _,
236 };
237 let future = async move {
238 if let Err(err) = handle_event_stream_client(client).await {
239 warn!("error handling IPC event stream client: {err:?}");
240 }
241 };
242 if let Err(err) = ctx.scheduler.schedule(future) {
243 warn!("error scheduling IPC event stream future: {err:?}");
244 }
245
246 // Send the initial state.
247 {
248 let state = ctx.event_stream_state.borrow();
249 for event in state.replicate() {
250 events_tx
251 .try_send(event)
252 .expect("initial event burst had more events than buffer size");
253 }
254 }
255
256 // Add it to the list.
257 {
258 let mut streams = ctx.event_streams.borrow_mut();
259 let sender = EventStreamSender {
260 events: events_tx,
261 disconnect: disconnect_tx,
262 };
263 streams.push(sender);
264 }
265
266 return Ok(());
267 }
268 }
269}
270
271async fn process(ctx: &ClientCtx, request: Request) -> Reply {
272 let response = match request {
273 Request::ReturnError => return Err(String::from("example compositor error")),
274 Request::Version => Response::Version(version()),
275 Request::Outputs => {
276 let ipc_outputs = ctx.ipc_outputs.lock().unwrap().clone();
277 let outputs = ipc_outputs.values().cloned().map(|o| (o.name.clone(), o));
278 Response::Outputs(outputs.collect())
279 }
280 Request::Workspaces => {
281 let state = ctx.event_stream_state.borrow();
282 let workspaces = state.workspaces.workspaces.values().cloned().collect();
283 Response::Workspaces(workspaces)
284 }
285 Request::Windows => {
286 let state = ctx.event_stream_state.borrow();
287 let windows = state.windows.windows.values().cloned().collect();
288 Response::Windows(windows)
289 }
290 Request::Layers => {
291 let (tx, rx) = async_channel::bounded(1);
292 ctx.event_loop.insert_idle(move |state| {
293 let mut layers = Vec::new();
294 for output in state.niri.global_space.outputs() {
295 let name = output.name();
296 for surface in layer_map_for_output(output).layers() {
297 let layer = match surface.layer() {
298 Layer::Background => niri_ipc::Layer::Background,
299 Layer::Bottom => niri_ipc::Layer::Bottom,
300 Layer::Top => niri_ipc::Layer::Top,
301 Layer::Overlay => niri_ipc::Layer::Overlay,
302 };
303 let keyboard_interactivity =
304 match surface.cached_state().keyboard_interactivity {
305 KeyboardInteractivity::None => {
306 niri_ipc::LayerSurfaceKeyboardInteractivity::None
307 }
308 KeyboardInteractivity::Exclusive => {
309 niri_ipc::LayerSurfaceKeyboardInteractivity::Exclusive
310 }
311 KeyboardInteractivity::OnDemand => {
312 niri_ipc::LayerSurfaceKeyboardInteractivity::OnDemand
313 }
314 };
315
316 layers.push(niri_ipc::LayerSurface {
317 namespace: surface.namespace().to_owned(),
318 output: name.clone(),
319 layer,
320 keyboard_interactivity,
321 });
322 }
323 }
324
325 let _ = tx.send_blocking(layers);
326 });
327 let result = rx.recv().await;
328 let layers = result.map_err(|_| String::from("error getting layers info"))?;
329 Response::Layers(layers)
330 }
331 Request::KeyboardLayouts => {
332 let state = ctx.event_stream_state.borrow();
333 let layout = state.keyboard_layouts.keyboard_layouts.clone();
334 let layout = layout.expect("keyboard layouts should be set at startup");
335 Response::KeyboardLayouts(layout)
336 }
337 Request::FocusedWindow => {
338 let state = ctx.event_stream_state.borrow();
339 let windows = &state.windows.windows;
340 let window = windows.values().find(|win| win.is_focused).cloned();
341 Response::FocusedWindow(window)
342 }
343 Request::PickWindow => {
344 let (tx, rx) = async_channel::bounded(1);
345 ctx.event_loop.insert_idle(move |state| {
346 let pointer = state.niri.seat.get_pointer().unwrap();
347 let start_data = PointerGrabStartData {
348 focus: None,
349 button: 0,
350 location: pointer.current_location(),
351 };
352 let grab = PickWindowGrab::new(start_data);
353 // The `WindowPickGrab` ungrab handler will cancel the previous ongoing pick, if
354 // any.
355 pointer.set_grab(state, grab, SERIAL_COUNTER.next_serial(), Focus::Clear);
356 state.niri.pick_window = Some(tx);
357 state
358 .niri
359 .cursor_manager
360 .set_cursor_image(CursorImageStatus::Named(CursorIcon::Crosshair));
361 // Redraw to update the cursor.
362 state.niri.queue_redraw_all();
363 });
364 let result = rx.recv().await;
365 let id = result.map_err(|_| String::from("error getting picked window info"))?;
366 let window = id.and_then(|id| {
367 let state = ctx.event_stream_state.borrow();
368 state.windows.windows.get(&id.get()).cloned()
369 });
370 Response::PickedWindow(window)
371 }
372 Request::PickColor => {
373 let (tx, rx) = async_channel::bounded(1);
374 ctx.event_loop.insert_idle(move |state| {
375 state.handle_pick_color(tx);
376 });
377 let result = rx.recv().await;
378 let color = result.map_err(|_| String::from("error getting picked color"))?;
379 Response::PickedColor(color)
380 }
381 Request::Action(action) => {
382 validate_action(&action)?;
383
384 let (tx, rx) = async_channel::bounded(1);
385
386 let action = niri_config::Action::from(action);
387 ctx.event_loop.insert_idle(move |state| {
388 // Make sure some logic like workspace clean-up has a chance to run before doing
389 // actions.
390 state.niri.advance_animations();
391 state.do_action(action, false);
392 let _ = tx.send_blocking(());
393 });
394
395 // Wait until the action has been processed before returning. This is important for a
396 // few actions, for instance for DoScreenTransition this wait ensures that the screen
397 // contents were sampled into the texture.
398 let _ = rx.recv().await;
399 Response::Handled
400 }
401 Request::Output { output, action } => {
402 action.validate()?;
403
404 let ipc_outputs = ctx.ipc_outputs.lock().unwrap();
405 let found = ipc_outputs
406 .values()
407 .any(|o| OutputName::from_ipc_output(o).matches(&output));
408 let response = if found {
409 OutputConfigChanged::Applied
410 } else {
411 OutputConfigChanged::OutputWasMissing
412 };
413 drop(ipc_outputs);
414
415 ctx.event_loop.insert_idle(move |state| {
416 state.apply_transient_output_config(&output, action);
417 });
418
419 Response::OutputConfigChanged(response)
420 }
421 Request::FocusedOutput => {
422 let (tx, rx) = async_channel::bounded(1);
423 ctx.event_loop.insert_idle(move |state| {
424 let active_output = state
425 .niri
426 .layout
427 .active_output()
428 .map(|output| output.name());
429
430 let output = active_output.and_then(|active_output| {
431 state
432 .backend
433 .ipc_outputs()
434 .lock()
435 .unwrap()
436 .values()
437 .find(|o| o.name == active_output)
438 .cloned()
439 });
440
441 let _ = tx.send_blocking(output);
442 });
443 let result = rx.recv().await;
444 let output = result.map_err(|_| String::from("error getting active output info"))?;
445 Response::FocusedOutput(output)
446 }
447 Request::EventStream => Response::Handled,
448 Request::OverviewState => {
449 let state = ctx.event_stream_state.borrow();
450 let is_open = state.overview.is_open;
451 Response::OverviewState(Overview { is_open })
452 }
453 Request::Casts => {
454 let state = ctx.event_stream_state.borrow();
455 let casts = state.casts.casts.values().cloned().collect();
456 Response::Casts(casts)
457 }
458 };
459
460 Ok(response)
461}
462
463fn validate_action(action: &Action) -> Result<(), String> {
464 if let Action::Screenshot { path, .. }
465 | Action::ScreenshotScreen { path, .. }
466 | Action::ScreenshotWindow { path, .. }
467 | Action::LoadConfigFile { path } = action
468 {
469 if let Some(path) = path {
470 // Relative paths are resolved against the niri compositor's working directory, which
471 // is almost certainly not what you want.
472 if !Path::new(path).is_absolute() {
473 return Err(format!("path must be absolute: {path}"));
474 }
475 }
476 }
477
478 if let Action::LoadConfigFile { path: Some(path) } = action {
479 let p = Path::new(path);
480 if !p.is_file() {
481 return Err(format!("path does not point to a file: {path}"));
482 }
483 }
484
485 Ok(())
486}
487
488async fn handle_event_stream_client(client: EventStreamClient) -> anyhow::Result<()> {
489 let EventStreamClient {
490 events,
491 disconnect,
492 mut write,
493 } = client;
494
495 while let Ok(event) = events.recv().await {
496 let mut buf = serde_json::to_vec(&event).context("error formatting event")?;
497 buf.push(b'\n');
498
499 let res = select_biased! {
500 _ = disconnect.recv().fuse() => return Ok(()),
501 res = write.write_all(&buf).fuse() => res,
502 };
503
504 match res {
505 Ok(()) => (),
506 // Normal client disconnection.
507 Err(err) if err.kind() == io::ErrorKind::BrokenPipe => return Ok(()),
508 res @ Err(_) => res.context("error writing event")?,
509 }
510 }
511
512 Ok(())
513}
514
515fn make_ipc_window(
516 mapped: &Mapped,
517 workspace_id: Option<WorkspaceId>,
518 layout: WindowLayout,
519) -> niri_ipc::Window {
520 with_toplevel_role(mapped.toplevel(), |role| niri_ipc::Window {
521 id: mapped.id().get(),
522 title: role.title.clone(),
523 app_id: role.app_id.clone(),
524 pid: mapped.credentials().map(|c| c.pid),
525 workspace_id: workspace_id.map(|id| id.get()),
526 is_focused: mapped.is_focused(),
527 is_floating: mapped.is_floating(),
528 is_urgent: mapped.is_urgent(),
529 layout,
530 focus_timestamp: mapped.get_focus_timestamp().map(Timestamp::from),
531 })
532}
533
534impl State {
535 pub fn ipc_keyboard_layouts_changed(&mut self) {
536 let keyboard = self.niri.seat.get_keyboard().unwrap();
537 let keyboard_layouts = keyboard.with_xkb_state(self, |context| {
538 let xkb = context.xkb().lock().unwrap();
539 let layouts = xkb.layouts();
540 KeyboardLayouts {
541 names: layouts
542 .map(|layout| xkb.layout_name(layout).to_owned())
543 .collect(),
544 current_idx: xkb.active_layout().0 as u8,
545 }
546 });
547
548 let Some(server) = &self.niri.ipc_server else {
549 return;
550 };
551
552 let mut state = server.event_stream_state.borrow_mut();
553 let state = &mut state.keyboard_layouts;
554
555 let event = Event::KeyboardLayoutsChanged { keyboard_layouts };
556 state.apply(event.clone());
557 server.send_event(event);
558 }
559
560 pub fn ipc_refresh_keyboard_layout_index(&mut self) {
561 let keyboard = self.niri.seat.get_keyboard().unwrap();
562 let idx = keyboard.with_xkb_state(self, |context| {
563 let xkb = context.xkb().lock().unwrap();
564 xkb.active_layout().0 as u8
565 });
566
567 let Some(server) = &self.niri.ipc_server else {
568 return;
569 };
570
571 let mut state = server.event_stream_state.borrow_mut();
572 let state = &mut state.keyboard_layouts;
573
574 if state.keyboard_layouts.as_ref().unwrap().current_idx == idx {
575 return;
576 }
577
578 let event = Event::KeyboardLayoutSwitched { idx };
579 state.apply(event.clone());
580 server.send_event(event);
581 }
582
583 pub fn ipc_refresh_layout(&mut self) {
584 self.ipc_refresh_workspaces();
585 self.ipc_refresh_windows();
586 self.ipc_refresh_overview();
587 }
588
589 fn ipc_refresh_workspaces(&mut self) {
590 let Some(server) = &self.niri.ipc_server else {
591 return;
592 };
593
594 let _span = tracy_client::span!("State::ipc_refresh_workspaces");
595
596 let mut state = server.event_stream_state.borrow_mut();
597 let state = &mut state.workspaces;
598
599 let mut events = Vec::new();
600 let layout = &self.niri.layout;
601 let focused_ws_id = layout.active_workspace().map(|ws| ws.id().get());
602
603 // Check for workspace changes.
604 let mut seen = HashSet::new();
605 let mut need_workspaces_changed = false;
606 for (mon, ws_idx, ws) in layout.workspaces() {
607 let id = ws.id().get();
608 seen.insert(id);
609
610 let Some(ipc_ws) = state.workspaces.get(&id) else {
611 // A new workspace was added.
612 need_workspaces_changed = true;
613 break;
614 };
615
616 // Check for any changes that we can't signal as individual events.
617 let output_name = mon.map(|mon| mon.output_name());
618 if ipc_ws.idx != u8::try_from(ws_idx + 1).unwrap_or(u8::MAX)
619 || ipc_ws.name.as_ref() != ws.name()
620 || ipc_ws.output.as_ref() != output_name
621 {
622 need_workspaces_changed = true;
623 break;
624 }
625
626 let active_window_id = ws.active_window().map(|win| win.id().get());
627 if ipc_ws.active_window_id != active_window_id {
628 events.push(Event::WorkspaceActiveWindowChanged {
629 workspace_id: id,
630 active_window_id,
631 });
632 }
633
634 // Check if this workspace urgent state changed.
635 let urgent = ws.is_urgent();
636 if urgent != ipc_ws.is_urgent {
637 events.push(Event::WorkspaceUrgencyChanged { id, urgent });
638 }
639
640 // Check if this workspace became focused.
641 let is_focused = Some(id) == focused_ws_id;
642 if is_focused && !ipc_ws.is_focused {
643 events.push(Event::WorkspaceActivated { id, focused: true });
644 continue;
645 }
646
647 // Check if this workspace became active.
648 let is_active = mon.is_some_and(|mon| mon.active_workspace_idx() == ws_idx);
649 if is_active && !ipc_ws.is_active {
650 events.push(Event::WorkspaceActivated { id, focused: false });
651 }
652 }
653
654 // Check if any workspaces were removed.
655 if !need_workspaces_changed && state.workspaces.keys().any(|id| !seen.contains(id)) {
656 need_workspaces_changed = true;
657 }
658
659 if need_workspaces_changed {
660 events.clear();
661
662 let workspaces = layout
663 .workspaces()
664 .map(|(mon, ws_idx, ws)| {
665 let id = ws.id().get();
666 Workspace {
667 id,
668 idx: u8::try_from(ws_idx + 1).unwrap_or(u8::MAX),
669 name: ws.name().cloned(),
670 output: mon.map(|mon| mon.output_name().clone()),
671 is_urgent: ws.is_urgent(),
672 is_active: mon.is_some_and(|mon| mon.active_workspace_idx() == ws_idx),
673 is_focused: Some(id) == focused_ws_id,
674 active_window_id: ws.active_window().map(|win| win.id().get()),
675 }
676 })
677 .collect();
678
679 events.push(Event::WorkspacesChanged { workspaces });
680 }
681
682 for event in events {
683 state.apply(event.clone());
684 server.send_event(event);
685 }
686 }
687
688 fn ipc_refresh_windows(&mut self) {
689 let Some(server) = &self.niri.ipc_server else {
690 return;
691 };
692
693 let _span = tracy_client::span!("State::ipc_refresh_windows");
694
695 let mut state = server.event_stream_state.borrow_mut();
696 let state = &mut state.windows;
697
698 let mut events = Vec::new();
699 let layout = &self.niri.layout;
700
701 let mut batch_change_layouts: Vec<(u64, WindowLayout)> = Vec::new();
702
703 // Check for window changes.
704 let mut seen = HashSet::new();
705 let mut focused_id = None;
706 layout.with_windows(|mapped, _, ws_id, window_layout| {
707 let id = mapped.id().get();
708 seen.insert(id);
709
710 if mapped.is_focused() {
711 focused_id = Some(id);
712 }
713
714 let Some(ipc_win) = state.windows.get(&id) else {
715 let window = make_ipc_window(mapped, ws_id, window_layout);
716 events.push(Event::WindowOpenedOrChanged { window });
717 return;
718 };
719
720 let workspace_id = ws_id.map(|id| id.get());
721 let mut changed =
722 ipc_win.workspace_id != workspace_id || ipc_win.is_floating != mapped.is_floating();
723
724 changed |= with_toplevel_role(mapped.toplevel(), |role| {
725 ipc_win.title != role.title || ipc_win.app_id != role.app_id
726 });
727
728 if changed {
729 let window = make_ipc_window(mapped, ws_id, window_layout);
730 events.push(Event::WindowOpenedOrChanged { window });
731 return;
732 }
733
734 if ipc_win.layout != window_layout {
735 batch_change_layouts.push((id, window_layout));
736 }
737
738 if mapped.is_focused() && !ipc_win.is_focused {
739 events.push(Event::WindowFocusChanged { id: Some(id) });
740 }
741
742 let focus_timestamp = mapped.get_focus_timestamp().map(Timestamp::from);
743 if focus_timestamp != ipc_win.focus_timestamp {
744 events.push(Event::WindowFocusTimestampChanged {
745 id,
746 focus_timestamp,
747 });
748 }
749
750 let urgent = mapped.is_urgent();
751 if urgent != ipc_win.is_urgent {
752 events.push(Event::WindowUrgencyChanged { id, urgent })
753 }
754 });
755
756 // It might make sense to push layout changes after closed windows (since windows about to
757 // be closed will occupy the same column/tile positions as the window that moved into this
758 // vacated space), but also we are already pushing some layout changes in
759 // WindowOpenedOrChanged above, meaning that the receiving end has to handle this case
760 // anyway.
761 if !batch_change_layouts.is_empty() {
762 events.push(Event::WindowLayoutsChanged {
763 changes: batch_change_layouts,
764 });
765 }
766
767 // Check for closed windows.
768 let mut ipc_focused_id = None;
769 for (id, ipc_win) in &state.windows {
770 if !seen.contains(id) {
771 events.push(Event::WindowClosed { id: *id });
772 }
773
774 if ipc_win.is_focused {
775 ipc_focused_id = Some(id);
776 }
777 }
778
779 // Extra check for focus becoming None, since the checks above only work for focus becoming
780 // a different window.
781 if focused_id.is_none() && ipc_focused_id.is_some() {
782 events.push(Event::WindowFocusChanged { id: None });
783 }
784
785 for event in events {
786 state.apply(event.clone());
787 server.send_event(event);
788 }
789 }
790
791 pub fn ipc_refresh_overview(&mut self) {
792 let Some(server) = &self.niri.ipc_server else {
793 return;
794 };
795
796 let mut state = server.event_stream_state.borrow_mut();
797 let state = &mut state.overview;
798 let is_open = self.niri.layout.is_overview_open();
799
800 if state.is_open == is_open {
801 return;
802 }
803
804 let event = Event::OverviewOpenedOrClosed { is_open };
805 state.apply(event.clone());
806 server.send_event(event);
807 }
808
809 pub fn ipc_refresh_casts(&mut self) {
810 let Some(server) = &self.niri.ipc_server else {
811 return;
812 };
813
814 let _span = tracy_client::span!("State::ipc_refresh_casts");
815
816 let mut state = server.event_stream_state.borrow_mut();
817 let state = &mut state.casts;
818
819 let mut events = Vec::new();
820 let mut seen = HashSet::new();
821
822 // Check PipeWire screencasts.
823 #[cfg(feature = "xdp-gnome-screencast")]
824 {
825 // Check pending dynamic casts.
826 for pending in &self.niri.casting.pending_dynamic_casts {
827 let stream_id = pending.stream_id.get();
828 seen.insert(stream_id);
829
830 // Pending dynamic casts don't change any properties, so we only need to check if
831 // it's missing from the state.
832 if !state.casts.contains_key(&stream_id) {
833 let cast = niri_ipc::Cast {
834 session_id: pending.session_id.get(),
835 stream_id,
836 kind: niri_ipc::CastKind::PipeWire,
837 target: niri_ipc::CastTarget::Nothing {},
838 is_dynamic_target: true,
839 is_active: false,
840 pid: None,
841 pw_node_id: None,
842 };
843 events.push(Event::CastStartedOrChanged { cast });
844 }
845 }
846
847 // Check active casts.
848 for cast in &self.niri.casting.casts {
849 let stream_id = cast.stream_id.get();
850 seen.insert(stream_id);
851
852 let pw_node_id = cast.node_id();
853 if state.casts.get(&stream_id).is_none_or(|existing| {
854 // Only these properties can change.
855 existing.is_active != cast.is_active()
856 || !cast.target.matches(&existing.target)
857 || existing.pw_node_id != pw_node_id
858 }) {
859 let cast = niri_ipc::Cast {
860 session_id: cast.session_id.get(),
861 stream_id,
862 kind: niri_ipc::CastKind::PipeWire,
863 target: cast.target.make_ipc(),
864 is_dynamic_target: cast.dynamic_target,
865 is_active: cast.is_active(),
866 pid: None,
867 pw_node_id,
868 };
869 events.push(Event::CastStartedOrChanged { cast });
870 }
871 }
872 }
873
874 // Check screencopy casts.
875 //
876 // First, clear expired casts. Ideally we'd have a deadline timer, but our 1 second frame
877 // callback timer calls refresh regularly, so that's fine as is.
878 self.niri.screencopy_state.clear_expired_casts();
879
880 for queue in self.niri.screencopy_state.queues() {
881 if let Some(cast_info) = queue.cast() {
882 let stream_id = cast_info.stream_id.get();
883 seen.insert(stream_id);
884
885 if state.casts.get(&stream_id).is_none_or(|existing| {
886 // Only this property can change.
887 match &existing.target {
888 niri_ipc::CastTarget::Output { name } => *name != cast_info.output_name,
889 _ => true,
890 }
891 }) {
892 let cast = niri_ipc::Cast {
893 session_id: cast_info.session_id.get(),
894 stream_id,
895 kind: niri_ipc::CastKind::WlrScreencopy,
896 target: niri_ipc::CastTarget::Output {
897 name: cast_info.output_name.clone(),
898 },
899 is_dynamic_target: false,
900 is_active: true,
901 pid: queue.credentials().map(|creds| creds.pid),
902 pw_node_id: None,
903 };
904 events.push(Event::CastStartedOrChanged { cast });
905 }
906 }
907 }
908
909 // Check for stopped casts.
910 for stream_id in state.casts.keys() {
911 if !seen.contains(stream_id) {
912 events.push(Event::CastStopped {
913 stream_id: *stream_id,
914 });
915 }
916 }
917
918 for event in events {
919 state.apply(event.clone());
920 server.send_event(event);
921 }
922 }
923
924 pub fn ipc_config_loaded(&mut self, failed: bool) {
925 let Some(server) = &self.niri.ipc_server else {
926 return;
927 };
928 let mut state = server.event_stream_state.borrow_mut();
929
930 let event = Event::ConfigLoaded { failed };
931 state.apply(event.clone());
932 server.send_event(event);
933 }
934
935 pub fn ipc_screenshot_taken(&mut self, path: Option<String>) {
936 let Some(server) = &self.niri.ipc_server else {
937 return;
938 };
939 let mut state = server.event_stream_state.borrow_mut();
940
941 let event = Event::ScreenshotCaptured { path };
942 state.apply(event.clone());
943 server.send_event(event);
944 }
945}