forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB2d82fddIvan Molodetskikh1 year ago2536 commits

server.rs817 lines, 29.1 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 };
454
455 Ok(response)
456}
457
458fn validate_action(action: &Action) -> Result<(), String> {
459 if let Action::Screenshot { path, .. }
460 | Action::ScreenshotScreen { path, .. }
461 | Action::ScreenshotWindow { path, .. } = action
462 {
463 if let Some(path) = path {
464 // Relative paths are resolved against the niri compositor's working directory, which
465 // is almost certainly not what you want.
466 if !Path::new(path).is_absolute() {
467 return Err(format!("path must be absolute: {path}"));
468 }
469 }
470 }
471
472 Ok(())
473}
474
475async fn handle_event_stream_client(client: EventStreamClient) -> anyhow::Result<()> {
476 let EventStreamClient {
477 events,
478 disconnect,
479 mut write,
480 } = client;
481
482 while let Ok(event) = events.recv().await {
483 let mut buf = serde_json::to_vec(&event).context("error formatting event")?;
484 buf.push(b'\n');
485
486 let res = select_biased! {
487 _ = disconnect.recv().fuse() => return Ok(()),
488 res = write.write_all(&buf).fuse() => res,
489 };
490
491 match res {
492 Ok(()) => (),
493 // Normal client disconnection.
494 Err(err) if err.kind() == io::ErrorKind::BrokenPipe => return Ok(()),
495 res @ Err(_) => res.context("error writing event")?,
496 }
497 }
498
499 Ok(())
500}
501
502fn make_ipc_window(
503 mapped: &Mapped,
504 workspace_id: Option<WorkspaceId>,
505 layout: WindowLayout,
506) -> niri_ipc::Window {
507 with_toplevel_role(mapped.toplevel(), |role| niri_ipc::Window {
508 id: mapped.id().get(),
509 title: role.title.clone(),
510 app_id: role.app_id.clone(),
511 pid: mapped.credentials().map(|c| c.pid),
512 workspace_id: workspace_id.map(|id| id.get()),
513 is_focused: mapped.is_focused(),
514 is_floating: mapped.is_floating(),
515 is_urgent: mapped.is_urgent(),
516 layout,
517 focus_timestamp: mapped.get_focus_timestamp().map(Timestamp::from),
518 })
519}
520
521impl State {
522 pub fn ipc_keyboard_layouts_changed(&mut self) {
523 let keyboard = self.niri.seat.get_keyboard().unwrap();
524 let keyboard_layouts = keyboard.with_xkb_state(self, |context| {
525 let xkb = context.xkb().lock().unwrap();
526 let layouts = xkb.layouts();
527 KeyboardLayouts {
528 names: layouts
529 .map(|layout| xkb.layout_name(layout).to_owned())
530 .collect(),
531 current_idx: xkb.active_layout().0 as u8,
532 }
533 });
534
535 let Some(server) = &self.niri.ipc_server else {
536 return;
537 };
538
539 let mut state = server.event_stream_state.borrow_mut();
540 let state = &mut state.keyboard_layouts;
541
542 let event = Event::KeyboardLayoutsChanged { keyboard_layouts };
543 state.apply(event.clone());
544 server.send_event(event);
545 }
546
547 pub fn ipc_refresh_keyboard_layout_index(&mut self) {
548 let keyboard = self.niri.seat.get_keyboard().unwrap();
549 let idx = keyboard.with_xkb_state(self, |context| {
550 let xkb = context.xkb().lock().unwrap();
551 xkb.active_layout().0 as u8
552 });
553
554 let Some(server) = &self.niri.ipc_server else {
555 return;
556 };
557
558 let mut state = server.event_stream_state.borrow_mut();
559 let state = &mut state.keyboard_layouts;
560
561 if state.keyboard_layouts.as_ref().unwrap().current_idx == idx {
562 return;
563 }
564
565 let event = Event::KeyboardLayoutSwitched { idx };
566 state.apply(event.clone());
567 server.send_event(event);
568 }
569
570 pub fn ipc_refresh_layout(&mut self) {
571 self.ipc_refresh_workspaces();
572 self.ipc_refresh_windows();
573 self.ipc_refresh_overview();
574 }
575
576 fn ipc_refresh_workspaces(&mut self) {
577 let Some(server) = &self.niri.ipc_server else {
578 return;
579 };
580
581 let _span = tracy_client::span!("State::ipc_refresh_workspaces");
582
583 let mut state = server.event_stream_state.borrow_mut();
584 let state = &mut state.workspaces;
585
586 let mut events = Vec::new();
587 let layout = &self.niri.layout;
588 let focused_ws_id = layout.active_workspace().map(|ws| ws.id().get());
589
590 // Check for workspace changes.
591 let mut seen = HashSet::new();
592 let mut need_workspaces_changed = false;
593 for (mon, ws_idx, ws) in layout.workspaces() {
594 let id = ws.id().get();
595 seen.insert(id);
596
597 let Some(ipc_ws) = state.workspaces.get(&id) else {
598 // A new workspace was added.
599 need_workspaces_changed = true;
600 break;
601 };
602
603 // Check for any changes that we can't signal as individual events.
604 let output_name = mon.map(|mon| mon.output_name());
605 if ipc_ws.idx != u8::try_from(ws_idx + 1).unwrap_or(u8::MAX)
606 || ipc_ws.name.as_ref() != ws.name()
607 || ipc_ws.output.as_ref() != output_name
608 {
609 need_workspaces_changed = true;
610 break;
611 }
612
613 let active_window_id = ws.active_window().map(|win| win.id().get());
614 if ipc_ws.active_window_id != active_window_id {
615 events.push(Event::WorkspaceActiveWindowChanged {
616 workspace_id: id,
617 active_window_id,
618 });
619 }
620
621 // Check if this workspace urgent state changed.
622 let urgent = ws.is_urgent();
623 if urgent != ipc_ws.is_urgent {
624 events.push(Event::WorkspaceUrgencyChanged { id, urgent });
625 }
626
627 // Check if this workspace became focused.
628 let is_focused = Some(id) == focused_ws_id;
629 if is_focused && !ipc_ws.is_focused {
630 events.push(Event::WorkspaceActivated { id, focused: true });
631 continue;
632 }
633
634 // Check if this workspace became active.
635 let is_active = mon.is_some_and(|mon| mon.active_workspace_idx() == ws_idx);
636 if is_active && !ipc_ws.is_active {
637 events.push(Event::WorkspaceActivated { id, focused: false });
638 }
639 }
640
641 // Check if any workspaces were removed.
642 if !need_workspaces_changed && state.workspaces.keys().any(|id| !seen.contains(id)) {
643 need_workspaces_changed = true;
644 }
645
646 if need_workspaces_changed {
647 events.clear();
648
649 let workspaces = layout
650 .workspaces()
651 .map(|(mon, ws_idx, ws)| {
652 let id = ws.id().get();
653 Workspace {
654 id,
655 idx: u8::try_from(ws_idx + 1).unwrap_or(u8::MAX),
656 name: ws.name().cloned(),
657 output: mon.map(|mon| mon.output_name().clone()),
658 is_urgent: ws.is_urgent(),
659 is_active: mon.is_some_and(|mon| mon.active_workspace_idx() == ws_idx),
660 is_focused: Some(id) == focused_ws_id,
661 active_window_id: ws.active_window().map(|win| win.id().get()),
662 }
663 })
664 .collect();
665
666 events.push(Event::WorkspacesChanged { workspaces });
667 }
668
669 for event in events {
670 state.apply(event.clone());
671 server.send_event(event);
672 }
673 }
674
675 fn ipc_refresh_windows(&mut self) {
676 let Some(server) = &self.niri.ipc_server else {
677 return;
678 };
679
680 let _span = tracy_client::span!("State::ipc_refresh_windows");
681
682 let mut state = server.event_stream_state.borrow_mut();
683 let state = &mut state.windows;
684
685 let mut events = Vec::new();
686 let layout = &self.niri.layout;
687
688 let mut batch_change_layouts: Vec<(u64, WindowLayout)> = Vec::new();
689
690 // Check for window changes.
691 let mut seen = HashSet::new();
692 let mut focused_id = None;
693 layout.with_windows(|mapped, _, ws_id, window_layout| {
694 let id = mapped.id().get();
695 seen.insert(id);
696
697 if mapped.is_focused() {
698 focused_id = Some(id);
699 }
700
701 let Some(ipc_win) = state.windows.get(&id) else {
702 let window = make_ipc_window(mapped, ws_id, window_layout);
703 events.push(Event::WindowOpenedOrChanged { window });
704 return;
705 };
706
707 let workspace_id = ws_id.map(|id| id.get());
708 let mut changed =
709 ipc_win.workspace_id != workspace_id || ipc_win.is_floating != mapped.is_floating();
710
711 changed |= with_toplevel_role(mapped.toplevel(), |role| {
712 ipc_win.title != role.title || ipc_win.app_id != role.app_id
713 });
714
715 if changed {
716 let window = make_ipc_window(mapped, ws_id, window_layout);
717 events.push(Event::WindowOpenedOrChanged { window });
718 return;
719 }
720
721 if ipc_win.layout != window_layout {
722 batch_change_layouts.push((id, window_layout));
723 }
724
725 if mapped.is_focused() && !ipc_win.is_focused {
726 events.push(Event::WindowFocusChanged { id: Some(id) });
727 }
728
729 let focus_timestamp = mapped.get_focus_timestamp().map(Timestamp::from);
730 if focus_timestamp != ipc_win.focus_timestamp {
731 events.push(Event::WindowFocusTimestampChanged {
732 id,
733 focus_timestamp,
734 });
735 }
736
737 let urgent = mapped.is_urgent();
738 if urgent != ipc_win.is_urgent {
739 events.push(Event::WindowUrgencyChanged { id, urgent })
740 }
741 });
742
743 // It might make sense to push layout changes after closed windows (since windows about to
744 // be closed will occupy the same column/tile positions as the window that moved into this
745 // vacated space), but also we are already pushing some layout changes in
746 // WindowOpenedOrChanged above, meaning that the receiving end has to handle this case
747 // anyway.
748 if !batch_change_layouts.is_empty() {
749 events.push(Event::WindowLayoutsChanged {
750 changes: batch_change_layouts,
751 });
752 }
753
754 // Check for closed windows.
755 let mut ipc_focused_id = None;
756 for (id, ipc_win) in &state.windows {
757 if !seen.contains(id) {
758 events.push(Event::WindowClosed { id: *id });
759 }
760
761 if ipc_win.is_focused {
762 ipc_focused_id = Some(id);
763 }
764 }
765
766 // Extra check for focus becoming None, since the checks above only work for focus becoming
767 // a different window.
768 if focused_id.is_none() && ipc_focused_id.is_some() {
769 events.push(Event::WindowFocusChanged { id: None });
770 }
771
772 for event in events {
773 state.apply(event.clone());
774 server.send_event(event);
775 }
776 }
777
778 pub fn ipc_refresh_overview(&mut self) {
779 let Some(server) = &self.niri.ipc_server else {
780 return;
781 };
782
783 let mut state = server.event_stream_state.borrow_mut();
784 let state = &mut state.overview;
785 let is_open = self.niri.layout.is_overview_open();
786
787 if state.is_open == is_open {
788 return;
789 }
790
791 let event = Event::OverviewOpenedOrClosed { is_open };
792 state.apply(event.clone());
793 server.send_event(event);
794 }
795
796 pub fn ipc_config_loaded(&mut self, failed: bool) {
797 let Some(server) = &self.niri.ipc_server else {
798 return;
799 };
800 let mut state = server.event_stream_state.borrow_mut();
801
802 let event = Event::ConfigLoaded { failed };
803 state.apply(event.clone());
804 server.send_event(event);
805 }
806
807 pub fn ipc_screenshot_taken(&mut self, path: Option<String>) {
808 let Some(server) = &self.niri.ipc_server else {
809 return;
810 };
811 let mut state = server.event_stream_state.borrow_mut();
812
813 let event = Event::ScreenshotCaptured { path };
814 state.apply(event.clone());
815 server.send_event(event);
816 }
817}