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