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