forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB66583cdIvan Molodetskikh1 year ago2489 commits

server.rs808 lines, 28.7 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 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 })
518}
519
520impl State {
521 pub fn ipc_keyboard_layouts_changed(&mut self) {
522 let keyboard = self.niri.seat.get_keyboard().unwrap();
523 let keyboard_layouts = keyboard.with_xkb_state(self, |context| {
524 let xkb = context.xkb().lock().unwrap();
525 let layouts = xkb.layouts();
526 KeyboardLayouts {
527 names: layouts
528 .map(|layout| xkb.layout_name(layout).to_owned())
529 .collect(),
530 current_idx: xkb.active_layout().0 as u8,
531 }
532 });
533
534 let Some(server) = &self.niri.ipc_server else {
535 return;
536 };
537
538 let mut state = server.event_stream_state.borrow_mut();
539 let state = &mut state.keyboard_layouts;
540
541 let event = Event::KeyboardLayoutsChanged { keyboard_layouts };
542 state.apply(event.clone());
543 server.send_event(event);
544 }
545
546 pub fn ipc_refresh_keyboard_layout_index(&mut self) {
547 let keyboard = self.niri.seat.get_keyboard().unwrap();
548 let idx = keyboard.with_xkb_state(self, |context| {
549 let xkb = context.xkb().lock().unwrap();
550 xkb.active_layout().0 as u8
551 });
552
553 let Some(server) = &self.niri.ipc_server else {
554 return;
555 };
556
557 let mut state = server.event_stream_state.borrow_mut();
558 let state = &mut state.keyboard_layouts;
559
560 if state.keyboard_layouts.as_ref().unwrap().current_idx == idx {
561 return;
562 }
563
564 let event = Event::KeyboardLayoutSwitched { idx };
565 state.apply(event.clone());
566 server.send_event(event);
567 }
568
569 pub fn ipc_refresh_layout(&mut self) {
570 self.ipc_refresh_workspaces();
571 self.ipc_refresh_windows();
572 self.ipc_refresh_overview();
573 }
574
575 fn ipc_refresh_workspaces(&mut self) {
576 let Some(server) = &self.niri.ipc_server else {
577 return;
578 };
579
580 let _span = tracy_client::span!("State::ipc_refresh_workspaces");
581
582 let mut state = server.event_stream_state.borrow_mut();
583 let state = &mut state.workspaces;
584
585 let mut events = Vec::new();
586 let layout = &self.niri.layout;
587 let focused_ws_id = layout.active_workspace().map(|ws| ws.id().get());
588
589 // Check for workspace changes.
590 let mut seen = HashSet::new();
591 let mut need_workspaces_changed = false;
592 for (mon, ws_idx, ws) in layout.workspaces() {
593 let id = ws.id().get();
594 seen.insert(id);
595
596 let Some(ipc_ws) = state.workspaces.get(&id) else {
597 // A new workspace was added.
598 need_workspaces_changed = true;
599 break;
600 };
601
602 // Check for any changes that we can't signal as individual events.
603 let output_name = mon.map(|mon| mon.output_name());
604 if ipc_ws.idx != u8::try_from(ws_idx + 1).unwrap_or(u8::MAX)
605 || ipc_ws.name.as_ref() != ws.name()
606 || ipc_ws.output.as_ref() != output_name
607 {
608 need_workspaces_changed = true;
609 break;
610 }
611
612 let active_window_id = ws.active_window().map(|win| win.id().get());
613 if ipc_ws.active_window_id != active_window_id {
614 events.push(Event::WorkspaceActiveWindowChanged {
615 workspace_id: id,
616 active_window_id,
617 });
618 }
619
620 // Check if this workspace urgent state changed.
621 let urgent = ws.is_urgent();
622 if urgent != ipc_ws.is_urgent {
623 events.push(Event::WorkspaceUrgencyChanged { id, urgent });
624 }
625
626 // Check if this workspace became focused.
627 let is_focused = Some(id) == focused_ws_id;
628 if is_focused && !ipc_ws.is_focused {
629 events.push(Event::WorkspaceActivated { id, focused: true });
630 continue;
631 }
632
633 // Check if this workspace became active.
634 let is_active = mon.is_some_and(|mon| mon.active_workspace_idx() == ws_idx);
635 if is_active && !ipc_ws.is_active {
636 events.push(Event::WorkspaceActivated { id, focused: false });
637 }
638 }
639
640 // Check if any workspaces were removed.
641 if !need_workspaces_changed && state.workspaces.keys().any(|id| !seen.contains(id)) {
642 need_workspaces_changed = true;
643 }
644
645 if need_workspaces_changed {
646 events.clear();
647
648 let workspaces = layout
649 .workspaces()
650 .map(|(mon, ws_idx, ws)| {
651 let id = ws.id().get();
652 Workspace {
653 id,
654 idx: u8::try_from(ws_idx + 1).unwrap_or(u8::MAX),
655 name: ws.name().cloned(),
656 output: mon.map(|mon| mon.output_name().clone()),
657 is_urgent: ws.is_urgent(),
658 is_active: mon.is_some_and(|mon| mon.active_workspace_idx() == ws_idx),
659 is_focused: Some(id) == focused_ws_id,
660 active_window_id: ws.active_window().map(|win| win.id().get()),
661 }
662 })
663 .collect();
664
665 events.push(Event::WorkspacesChanged { workspaces });
666 }
667
668 for event in events {
669 state.apply(event.clone());
670 server.send_event(event);
671 }
672 }
673
674 fn ipc_refresh_windows(&mut self) {
675 let Some(server) = &self.niri.ipc_server else {
676 return;
677 };
678
679 let _span = tracy_client::span!("State::ipc_refresh_windows");
680
681 let mut state = server.event_stream_state.borrow_mut();
682 let state = &mut state.windows;
683
684 let mut events = Vec::new();
685 let layout = &self.niri.layout;
686
687 let mut batch_change_layouts: Vec<(u64, WindowLayout)> = Vec::new();
688
689 // Check for window changes.
690 let mut seen = HashSet::new();
691 let mut focused_id = None;
692 layout.with_windows(|mapped, _, ws_id, window_layout| {
693 let id = mapped.id().get();
694 seen.insert(id);
695
696 if mapped.is_focused() {
697 focused_id = Some(id);
698 }
699
700 let Some(ipc_win) = state.windows.get(&id) else {
701 let window = make_ipc_window(mapped, ws_id, window_layout);
702 events.push(Event::WindowOpenedOrChanged { window });
703 return;
704 };
705
706 let workspace_id = ws_id.map(|id| id.get());
707 let mut changed =
708 ipc_win.workspace_id != workspace_id || ipc_win.is_floating != mapped.is_floating();
709
710 changed |= with_toplevel_role(mapped.toplevel(), |role| {
711 ipc_win.title != role.title || ipc_win.app_id != role.app_id
712 });
713
714 if changed {
715 let window = make_ipc_window(mapped, ws_id, window_layout);
716 events.push(Event::WindowOpenedOrChanged { window });
717 return;
718 }
719
720 if ipc_win.layout != window_layout {
721 batch_change_layouts.push((id, window_layout));
722 }
723
724 if mapped.is_focused() && !ipc_win.is_focused {
725 events.push(Event::WindowFocusChanged { id: Some(id) });
726 }
727
728 let urgent = mapped.is_urgent();
729 if urgent != ipc_win.is_urgent {
730 events.push(Event::WindowUrgencyChanged { id, urgent })
731 }
732 });
733
734 // It might make sense to push layout changes after closed windows (since windows about to
735 // be closed will occupy the same column/tile positions as the window that moved into this
736 // vacated space), but also we are already pushing some layout changes in
737 // WindowOpenedOrChanged above, meaning that the receiving end has to handle this case
738 // anyway.
739 if !batch_change_layouts.is_empty() {
740 events.push(Event::WindowLayoutsChanged {
741 changes: batch_change_layouts,
742 });
743 }
744
745 // Check for closed windows.
746 let mut ipc_focused_id = None;
747 for (id, ipc_win) in &state.windows {
748 if !seen.contains(id) {
749 events.push(Event::WindowClosed { id: *id });
750 }
751
752 if ipc_win.is_focused {
753 ipc_focused_id = Some(id);
754 }
755 }
756
757 // Extra check for focus becoming None, since the checks above only work for focus becoming
758 // a different window.
759 if focused_id.is_none() && ipc_focused_id.is_some() {
760 events.push(Event::WindowFocusChanged { id: None });
761 }
762
763 for event in events {
764 state.apply(event.clone());
765 server.send_event(event);
766 }
767 }
768
769 pub fn ipc_refresh_overview(&mut self) {
770 let Some(server) = &self.niri.ipc_server else {
771 return;
772 };
773
774 let mut state = server.event_stream_state.borrow_mut();
775 let state = &mut state.overview;
776 let is_open = self.niri.layout.is_overview_open();
777
778 if state.is_open == is_open {
779 return;
780 }
781
782 let event = Event::OverviewOpenedOrClosed { is_open };
783 state.apply(event.clone());
784 server.send_event(event);
785 }
786
787 pub fn ipc_config_loaded(&mut self, failed: bool) {
788 let Some(server) = &self.niri.ipc_server else {
789 return;
790 };
791 let mut state = server.event_stream_state.borrow_mut();
792
793 let event = Event::ConfigLoaded { failed };
794 state.apply(event.clone());
795 server.send_event(event);
796 }
797
798 pub fn ipc_screenshot_taken(&mut self, path: Option<String>) {
799 let Some(server) = &self.niri.ipc_server else {
800 return;
801 };
802 let mut state = server.event_stream_state.borrow_mut();
803
804 let event = Event::ScreenshotCaptured { path };
805 state.apply(event.clone());
806 server.send_event(event);
807 }
808}