forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBb0eb8adIvan Molodetskikh3 months ago2857 commits

niri.rs6569 lines, 245.9 KiBHistoryRawDownload
1use std::cell::{Cell, RefCell};
2use std::collections::{HashMap, HashSet};
3use std::ffi::OsString;
4use std::os::unix::net::UnixStream;
5use std::path::PathBuf;
6use std::rc::Rc;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::sync::mpsc::{self, Receiver, Sender};
9use std::sync::{Arc, Mutex};
10use std::time::{Duration, Instant};
11use std::{env, mem, thread};
12
13use _server_decoration::server::org_kde_kwin_server_decoration_manager::Mode as KdeDecorationsMode;
14use anyhow::{bail, ensure, Context};
15use calloop::futures::Scheduler;
16use niri_config::debug::PreviewRender;
17use niri_config::output::MaxBpc;
18use niri_config::{
19 Config, FloatOrInt, Key, Modifiers, OutputName, TrackLayout, WarpMouseToFocusMode,
20 WorkspaceReference, Xkb,
21};
22use smithay::backend::allocator::Fourcc;
23use smithay::backend::input::Keycode;
24use smithay::backend::renderer::damage::OutputDamageTracker;
25use smithay::backend::renderer::element::memory::MemoryRenderBufferRenderElement;
26use smithay::backend::renderer::element::surface::WaylandSurfaceRenderElement;
27use smithay::backend::renderer::element::utils::{
28 select_dmabuf_feedback, CropRenderElement, Relocate, RelocateRenderElement,
29 RescaleRenderElement,
30};
31use smithay::backend::renderer::element::{
32 default_primary_scanout_output_compare, Element, Id, Kind, PrimaryScanoutOutput, RenderElement,
33 RenderElementStates,
34};
35use smithay::backend::renderer::gles::GlesRenderer;
36use smithay::backend::renderer::sync::SyncPoint;
37use smithay::backend::renderer::Color32F;
38use smithay::desktop::utils::{
39 bbox_from_surface_tree, output_update, send_dmabuf_feedback_surface_tree,
40 send_frames_surface_tree, surface_presentation_feedback_flags_from_states,
41 surface_primary_scanout_output, take_presentation_feedback_surface_tree,
42 under_from_surface_tree, update_surface_primary_scanout_output, with_surfaces_surface_tree,
43 OutputPresentationFeedback,
44};
45use smithay::desktop::{
46 find_popup_root_surface, layer_map_for_output, LayerMap, LayerSurface, PopupGrab, PopupManager,
47 PopupUngrabStrategy, Space, Window, WindowSurfaceType,
48};
49use smithay::input::keyboard::{Layout as KeyboardLayout, XkbConfig};
50use smithay::input::pointer::{
51 CursorIcon, CursorImageStatus, CursorImageSurfaceData, Focus,
52 GrabStartData as PointerGrabStartData, MotionEvent,
53};
54use smithay::input::tablet::TabletSeatTrait;
55use smithay::input::{Seat, SeatState};
56use smithay::output::{self, Output, OutputModeSource, PhysicalProperties, Subpixel, WeakOutput};
57use smithay::reexports::calloop::generic::Generic;
58use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
59use smithay::reexports::calloop::{
60 Interest, LoopHandle, LoopSignal, Mode, PostAction, RegistrationToken,
61};
62use smithay::reexports::wayland_protocols::ext::session_lock::v1::server::ext_session_lock_v1::ExtSessionLockV1;
63use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::WmCapabilities;
64use smithay::reexports::wayland_protocols_misc::server_decoration as _server_decoration;
65use smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1;
66use smithay::reexports::wayland_server::backend::{
67 ClientData, ClientId, DisconnectReason, GlobalId,
68};
69use smithay::reexports::wayland_server::protocol::wl_shm;
70use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
71use smithay::reexports::wayland_server::{Client, Display, DisplayHandle, Resource};
72use smithay::utils::{
73 ClockSource, IsAlive as _, Logical, Monotonic, Physical, Point, Rectangle, Scale, Size,
74 Transform, SERIAL_COUNTER,
75};
76use smithay::wayland::background_effect::BackgroundEffectState;
77use smithay::wayland::compositor::{
78 with_states, with_surface_tree_downward, CompositorClientState, CompositorHandler,
79 CompositorState, HookId, SurfaceData, TraversalAction,
80};
81use smithay::wayland::cursor_shape::CursorShapeManagerState;
82use smithay::wayland::dmabuf::DmabufState;
83use smithay::wayland::fractional_scale::FractionalScaleManagerState;
84use smithay::wayland::idle_inhibit::IdleInhibitManagerState;
85use smithay::wayland::idle_notify::IdleNotifierState;
86use smithay::wayland::input_method::InputMethodManagerState;
87use smithay::wayland::keyboard_shortcuts_inhibit::{
88 KeyboardShortcutsInhibitState, KeyboardShortcutsInhibitor,
89};
90use smithay::wayland::output::OutputManagerState;
91use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraintsState};
92use smithay::wayland::pointer_gestures::PointerGesturesState;
93use smithay::wayland::presentation::PresentationState;
94use smithay::wayland::relative_pointer::RelativePointerManagerState;
95use smithay::wayland::security_context::SecurityContextState;
96use smithay::wayland::selection::data_device::{set_data_device_selection, DataDeviceState};
97use smithay::wayland::selection::ext_data_control::DataControlState as ExtDataControlState;
98use smithay::wayland::selection::primary_selection::PrimarySelectionState;
99use smithay::wayland::selection::wlr_data_control::DataControlState as WlrDataControlState;
100use smithay::wayland::session_lock::{LockSurface, SessionLockManagerState, SessionLocker};
101use smithay::wayland::shell::kde::decoration::KdeDecorationState;
102use smithay::wayland::shell::wlr_layer::{self, Layer, WlrLayerShellState};
103use smithay::wayland::shell::xdg::decoration::XdgDecorationState;
104use smithay::wayland::shell::xdg::XdgShellState;
105use smithay::wayland::shm::ShmState;
106#[cfg(test)]
107use smithay::wayland::single_pixel_buffer::SinglePixelBufferState;
108use smithay::wayland::socket::ListeningSocketSource;
109use smithay::wayland::tablet_manager::TabletManagerState;
110use smithay::wayland::text_input::TextInputManagerState;
111use smithay::wayland::viewporter::ViewporterState;
112use smithay::wayland::virtual_keyboard::VirtualKeyboardManagerState;
113use smithay::wayland::xdg_activation::XdgActivationState;
114use smithay::wayland::xdg_foreign::XdgForeignState;
115use wayland_server::protocol::wl_output::WlOutput;
116
117#[cfg(feature = "dbus")]
118use crate::a11y::A11y;
119use crate::animation::Clock;
120use crate::backend::tty::SurfaceDmabufFeedback;
121use crate::backend::{Backend, Headless, RenderResult, Tty, Winit};
122use crate::cursor::{CursorManager, CursorTextureCache, RenderCursor, XCursor};
123#[cfg(feature = "dbus")]
124use crate::dbus::freedesktop_locale1::Locale1ToNiri;
125#[cfg(feature = "dbus")]
126use crate::dbus::freedesktop_login1::Login1ToNiri;
127#[cfg(feature = "dbus")]
128use crate::dbus::gnome_shell_introspect::{self, IntrospectToNiri, NiriToIntrospect};
129#[cfg(feature = "dbus")]
130use crate::dbus::gnome_shell_screenshot::{NiriToScreenshot, ScreenshotToNiri};
131use crate::frame_clock::FrameClock;
132use crate::handlers::{configure_lock_surface, XDG_ACTIVATION_TOKEN_TIMEOUT};
133use crate::input::pick_color_grab::PickColorGrab;
134use crate::input::scroll_swipe_gesture::ScrollSwipeGesture;
135use crate::input::scroll_tracker::ScrollTracker;
136use crate::input::{
137 apply_libinput_settings, mods_with_finger_scroll_binds, mods_with_mouse_binds,
138 mods_with_tablet_stylus_binds, mods_with_wheel_binds, TabletData,
139};
140use crate::ipc::server::IpcServer;
141use crate::layer::mapped::LayerSurfaceRenderElement;
142use crate::layer::MappedLayer;
143use crate::layout::tile::TileRenderElement;
144use crate::layout::workspace::{Workspace, WorkspaceId};
145use crate::layout::{
146 HitType, Layout, LayoutElement as _, LayoutElementRenderElement, MonitorRenderElement,
147};
148use crate::niri_render_elements;
149use crate::protocols::ext_workspace::{self, ExtWorkspaceManagerState};
150use crate::protocols::foreign_toplevel::{self, ForeignToplevelManagerState};
151use crate::protocols::gamma_control::GammaControlManagerState;
152use crate::protocols::mutter_x11_interop::MutterX11InteropManagerState;
153use crate::protocols::output_management::OutputManagementManagerState;
154use crate::protocols::screencopy::{Screencopy, ScreencopyBuffer, ScreencopyManagerState};
155use crate::protocols::virtual_pointer::VirtualPointerManagerState;
156use crate::render_helpers::blur::BlurOptions;
157use crate::render_helpers::debug::push_opaque_regions;
158use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement;
159use crate::render_helpers::renderer::NiriRenderer;
160use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
161use crate::render_helpers::surface::push_elements_from_surface_tree;
162use crate::render_helpers::texture::TextureBuffer;
163use crate::render_helpers::xray::{Xray, XrayPos};
164use crate::render_helpers::{
165 encompassing_geo, render_to_dmabuf, render_to_encompassing_texture, render_to_shm,
166 render_to_texture, render_to_vec, shaders, RenderCtx, RenderTarget,
167};
168#[cfg(feature = "xdp-gnome-screencast")]
169use crate::screencasting::Screencasting;
170use crate::ui::config_error_notification::ConfigErrorNotification;
171use crate::ui::exit_confirm_dialog::{ExitConfirmDialog, ExitConfirmDialogRenderElement};
172use crate::ui::hotkey_overlay::HotkeyOverlay;
173use crate::ui::mru::{MruCloseRequest, WindowMruUi, WindowMruUiRenderElement};
174use crate::ui::screen_transition::{self, ScreenTransition};
175use crate::ui::screenshot_ui::{OutputScreenshot, ScreenshotUi, ScreenshotUiRenderElement};
176use crate::utils::scale::{closest_representable_scale, guess_monitor_scale};
177use crate::utils::spawning::{CHILD_DISPLAY, CHILD_ENV};
178use crate::utils::vblank_throttle::VBlankThrottle;
179use crate::utils::watcher::Watcher;
180use crate::utils::xwayland::satellite::Satellite;
181use crate::utils::{
182 center, center_f64, expand_home, get_monotonic_time, ipc_transform_to_smithay, is_mapped,
183 logical_output, make_screenshot_path, output_matches_name, output_size, panel_orientation,
184 send_scale_transform, write_png_rgba8, xwayland,
185};
186use crate::window::mapped::MappedId;
187use crate::window::{InitialConfigureState, Mapped, ResolvedWindowRules, Unmapped, WindowRef};
188
189const CLEAR_COLOR_LOCKED: [f32; 4] = [0.3, 0.1, 0.1, 1.];
190
191// We'll try to send frame callbacks at least once a second. We'll make a timer that fires once a
192// second, so with the worst timing the maximum interval between two frame callbacks for a surface
193// should be ~1.995 seconds.
194const FRAME_CALLBACK_THROTTLE: Option<Duration> = Some(Duration::from_millis(995));
195
196pub struct Niri {
197 pub config: Rc<RefCell<Config>>,
198
199 /// Output config from the config file.
200 ///
201 /// This does not include transient output config changes done via IPC. It is only used when
202 /// reloading the config from disk to determine if the output configuration should be reloaded
203 /// (and transient changes dropped).
204 pub config_file_output_config: niri_config::Outputs,
205
206 pub config_file_watcher: Option<Watcher>,
207
208 pub event_loop: LoopHandle<'static, State>,
209 pub scheduler: Scheduler<()>,
210 pub stop_signal: LoopSignal,
211 pub display_handle: DisplayHandle,
212
213 /// Whether niri was run with `--session`
214 pub is_session_instance: bool,
215
216 /// Name of the Wayland socket.
217 ///
218 /// This is `None` when creating `Niri` without a Wayland socket.
219 pub socket_name: Option<OsString>,
220
221 pub start_time: Instant,
222
223 /// Whether the at-startup=true window rules are active.
224 pub is_at_startup: bool,
225
226 /// Clock for driving animations.
227 pub clock: Clock,
228
229 // Each workspace corresponds to a Space. Each workspace generally has one Output mapped to it,
230 // however it may have none (when there are no outputs connected) or multiple (when mirroring).
231 pub layout: Layout<Mapped>,
232
233 // This space does not actually contain any windows, but all outputs are mapped into it
234 // according to their global position.
235 pub global_space: Space<Window>,
236
237 /// Mapped outputs, sorted by their name and position.
238 pub sorted_outputs: Vec<Output>,
239
240 // Windows which don't have a buffer attached yet.
241 pub unmapped_windows: HashMap<WlSurface, Unmapped>,
242
243 /// Layer surfaces which don't have a buffer attached yet.
244 pub unmapped_layer_surfaces: HashSet<WlSurface>,
245
246 /// Extra data for mapped layer surfaces.
247 pub mapped_layer_surfaces: HashMap<LayerSurface, MappedLayer>,
248
249 // Cached root surface for every surface, so that we can access it in destroyed() where the
250 // normal get_parent() is cleared out.
251 pub root_surface: HashMap<WlSurface, WlSurface>,
252
253 // Dmabuf readiness pre-commit hook for a surface.
254 pub dmabuf_pre_commit_hook: HashMap<WlSurface, HookId>,
255
256 /// Clients to notify about their blockers being cleared.
257 pub blocker_cleared_tx: Sender<Client>,
258 pub blocker_cleared_rx: Receiver<Client>,
259
260 pub output_state: HashMap<Output, OutputState>,
261
262 // When false, we're idling with monitors powered off.
263 pub monitors_active: bool,
264
265 /// Whether the laptop lid is closed.
266 ///
267 /// Libinput guarantees that the lid switch starts in open state, and if it was closed during
268 /// startup, libinput will immediately send a closed event.
269 pub is_lid_closed: bool,
270
271 pub devices: HashSet<input::Device>,
272 pub tablets: HashMap<input::Device, TabletData>,
273 pub touch: HashSet<input::Device>,
274
275 // Smithay state.
276 pub compositor_state: CompositorState,
277 pub xdg_shell_state: XdgShellState,
278 pub xdg_decoration_state: XdgDecorationState,
279 pub kde_decoration_state: KdeDecorationState,
280 pub layer_shell_state: WlrLayerShellState,
281 pub session_lock_state: SessionLockManagerState,
282 pub foreign_toplevel_state: ForeignToplevelManagerState,
283 pub ext_workspace_state: ExtWorkspaceManagerState,
284 pub screencopy_state: ScreencopyManagerState,
285 pub output_management_state: OutputManagementManagerState,
286 pub viewporter_state: ViewporterState,
287 pub background_effect_state: BackgroundEffectState,
288 pub xdg_foreign_state: XdgForeignState,
289 pub shm_state: ShmState,
290 pub output_manager_state: OutputManagerState,
291 pub dmabuf_state: DmabufState,
292 pub fractional_scale_manager_state: FractionalScaleManagerState,
293 pub seat_state: SeatState<State>,
294 pub tablet_state: TabletManagerState,
295 pub text_input_state: TextInputManagerState,
296 pub input_method_state: InputMethodManagerState,
297 pub keyboard_shortcuts_inhibit_state: KeyboardShortcutsInhibitState,
298 pub virtual_keyboard_state: VirtualKeyboardManagerState,
299 pub virtual_pointer_state: VirtualPointerManagerState,
300 pub pointer_gestures_state: PointerGesturesState,
301 pub relative_pointer_state: RelativePointerManagerState,
302 pub pointer_constraints_state: PointerConstraintsState,
303 pub idle_notifier_state: IdleNotifierState<State>,
304 pub idle_inhibit_manager_state: IdleInhibitManagerState,
305 pub data_device_state: DataDeviceState,
306 pub primary_selection_state: PrimarySelectionState,
307 pub wlr_data_control_state: WlrDataControlState,
308 pub ext_data_control_state: ExtDataControlState,
309 pub popups: PopupManager,
310 pub popup_grab: Option<PopupGrabState>,
311 pub presentation_state: PresentationState,
312 pub security_context_state: SecurityContextState,
313 pub gamma_control_manager_state: GammaControlManagerState,
314 pub activation_state: XdgActivationState,
315 pub mutter_x11_interop_state: MutterX11InteropManagerState,
316
317 // This will not work as is outside of tests, so it is gated with #[cfg(test)] for now. In
318 // particular, shaders will need to learn about the single pixel buffer. Also, it must be
319 // verified that a black single-pixel-buffer background lets the foreground surface to be
320 // unredirected.
321 //
322 // https://github.com/niri-wm/niri/issues/619
323 #[cfg(test)]
324 pub single_pixel_buffer_state: SinglePixelBufferState,
325
326 pub seat: Seat<State>,
327 /// Scancodes of the keys to suppress.
328 pub suppressed_keys: HashSet<Keycode>,
329 /// Button codes of the mouse buttons to suppress.
330 pub suppressed_buttons: HashSet<u32>,
331 pub bind_cooldown_timers: HashMap<Key, RegistrationToken>,
332 pub bind_repeat_timer: Option<RegistrationToken>,
333 pub keyboard_focus: KeyboardFocus,
334 pub layer_shell_on_demand_focus: Option<LayerSurface>,
335 pub idle_inhibiting_surfaces: HashSet<WlSurface>,
336 pub is_fdo_idle_inhibited: Arc<AtomicBool>,
337 pub keyboard_shortcuts_inhibiting_surfaces: HashMap<WlSurface, KeyboardShortcutsInhibitor>,
338
339 /// Most recent XKB settings from org.freedesktop.locale1.
340 pub xkb_from_locale1: Option<Xkb>,
341
342 pub cursor_manager: CursorManager,
343 pub cursor_texture_cache: CursorTextureCache,
344 pub cursor_shape_manager_state: CursorShapeManagerState,
345 pub dnd_icon: Option<DndIcon>,
346 /// Contents under pointer.
347 ///
348 /// Periodically updated: on motion and other events and in the loop callback. If you require
349 /// the real up-to-date contents somewhere, it's better to recompute on the spot.
350 ///
351 /// This is not pointer focus. I.e. during a click grab, the pointer focus remains on the
352 /// client with the grab, but this field will keep updating to the latest contents as if no
353 /// grab was active.
354 ///
355 /// This is primarily useful for emitting pointer motion events for surfaces that move
356 /// underneath the cursor on their own (i.e. when the tiling layout moves). In this case, not
357 /// taking grabs into account is expected, because we pass the information to pointer.motion()
358 /// which passes it down through grabs, which decide what to do with it as they see fit.
359 pub pointer_contents: PointContents,
360 pub pointer_visibility: PointerVisibility,
361 pub pointer_inactivity_timer: Option<RegistrationToken>,
362 /// Whether the pointer inactivity timer got reset this event loop iteration.
363 ///
364 /// Used for limiting the reset to once per iteration, so that it's not spammed with high
365 /// resolution mice.
366 pub pointer_inactivity_timer_got_reset: bool,
367 /// Whether the (idle notifier) activity was notified this event loop iteration.
368 ///
369 /// Used for limiting the notify to once per iteration, so that it's not spammed with high
370 /// resolution mice.
371 pub notified_activity_this_iteration: bool,
372 pub pointer_inside_hot_corner: bool,
373 pub pointer_constraint_position_hint: Option<Point<f64, Logical>>,
374 pub tablet_cursor_location: Option<Point<f64, Logical>>,
375 pub gesture_swipe_3f_cumulative: Option<(f64, f64)>,
376 pub overview_scroll_swipe_gesture: ScrollSwipeGesture,
377 pub vertical_wheel_tracker: ScrollTracker,
378 pub horizontal_wheel_tracker: ScrollTracker,
379 pub mods_with_mouse_binds: HashSet<Modifiers>,
380 pub mods_with_wheel_binds: HashSet<Modifiers>,
381 pub mods_with_tablet_stylus_binds: HashSet<Modifiers>,
382 pub vertical_finger_scroll_tracker: ScrollTracker,
383 pub horizontal_finger_scroll_tracker: ScrollTracker,
384 pub mods_with_finger_scroll_binds: HashSet<Modifiers>,
385
386 pub lock_state: LockState,
387
388 // State that we last sent to the logind LockedHint.
389 pub locked_hint: Option<bool>,
390
391 pub screenshot_ui: ScreenshotUi,
392 pub config_error_notification: ConfigErrorNotification,
393 pub hotkey_overlay: HotkeyOverlay,
394 pub exit_confirm_dialog: ExitConfirmDialog,
395
396 pub window_mru_ui: WindowMruUi,
397 pub pending_mru_commit: Option<PendingMruCommit>,
398
399 pub pick_window: Option<async_channel::Sender<Option<MappedId>>>,
400 pub pick_color: Option<async_channel::Sender<Option<niri_ipc::PickedColor>>>,
401
402 pub debug_draw_opaque_regions: bool,
403 pub debug_draw_damage: bool,
404
405 #[cfg(feature = "dbus")]
406 pub dbus: Option<crate::dbus::DBusServers>,
407 #[cfg(feature = "dbus")]
408 pub a11y_manager: Option<crate::dbus::freedesktop_a11y::Manager>,
409 #[cfg(feature = "dbus")]
410 pub a11y: A11y,
411 #[cfg(feature = "dbus")]
412 pub inhibit_power_key_fd: Option<zbus::zvariant::OwnedFd>,
413
414 pub ipc_server: Option<IpcServer>,
415 pub ipc_outputs_changed: bool,
416
417 pub satellite: Option<Satellite>,
418
419 #[cfg(feature = "xdp-gnome-screencast")]
420 pub casting: Screencasting,
421}
422
423smithay::delegate_dispatch2!(State);
424
425#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
426pub enum PointerVisibility {
427 /// The pointer is visible.
428 Visible,
429 /// The pointer is invisible, but retains its focus.
430 ///
431 /// This state is set temporarily after auto-hiding the pointer to keep tooltips open and grabs
432 /// ongoing.
433 Hidden,
434 /// The pointer is invisible and cannot focus.
435 ///
436 /// Corresponds to a fully disabled pointer, for example after a touchscreen input, or after
437 /// the pointer contents changed in a Hidden state.
438 Disabled,
439}
440
441impl PointerVisibility {
442 pub fn is_visible(&self) -> bool {
443 matches!(self, Self::Visible)
444 }
445}
446
447#[derive(Debug)]
448pub struct DndIcon {
449 pub surface: WlSurface,
450 pub offset: Point<i32, Logical>,
451}
452
453pub struct OutputState {
454 pub global: GlobalId,
455 pub frame_clock: FrameClock,
456 pub redraw_state: RedrawState,
457 pub on_demand_vrr_enabled: bool,
458 // After the last redraw, some ongoing animations still remain.
459 pub unfinished_animations_remain: bool,
460 /// Last sequence received in a vblank event.
461 pub last_drm_sequence: Option<u32>,
462 pub vblank_throttle: VBlankThrottle,
463 /// Sequence for frame callback throttling.
464 ///
465 /// We want to send frame callbacks for each surface at most once per monitor refresh cycle.
466 ///
467 /// Even if a surface commit resulted in empty damage to the monitor, we want to delay the next
468 /// frame callback until roughly when a VBlank would occur, had the monitor been damaged. This
469 /// is necessary to prevent clients busy-looping with frame callbacks that result in empty
470 /// damage.
471 ///
472 /// This counter wrapping-increments by 1 every time we move into the next refresh cycle, as
473 /// far as frame callback throttling is concerned. Specifically, it happens:
474 ///
475 /// 1. Upon a successful DRM frame submission. Notably, we don't wait for the VBlank here,
476 /// because the client buffers are already "latched" at the point of submission. Even if a
477 /// client submits a new buffer right away, we will wait for a VBlank to draw it, which
478 /// means that busy looping is avoided.
479 /// 2. If a frame resulted in empty damage, a timer is queued to fire roughly when a VBlank
480 /// would occur, based on the last presentation time and output refresh interval. Sequence
481 /// is incremented in that timer, before attempting a redraw or sending frame callbacks.
482 pub frame_callback_sequence: u32,
483 /// Solid color buffer for the backdrop that we use instead of clearing to avoid damage
484 /// tracking issues and make screenshots easier.
485 pub backdrop_buffer: SolidColorBuffer,
486 pub xray: Xray,
487 pub lock_render_state: LockRenderState,
488 pub lock_surface: Option<LockSurface>,
489 pub lock_color_buffer: SolidColorBuffer,
490 screen_transition: Option<ScreenTransition>,
491 /// Damage tracker used for the debug damage visualization.
492 pub debug_damage_tracker: OutputDamageTracker,
493}
494
495#[derive(Debug, Default)]
496pub enum RedrawState {
497 /// The compositor is idle.
498 #[default]
499 Idle,
500 /// A redraw is queued.
501 Queued,
502 /// We submitted a frame to the KMS and waiting for it to be presented.
503 WaitingForVBlank { redraw_needed: bool },
504 /// We did not submit anything to KMS and made a timer to fire at the estimated VBlank.
505 WaitingForEstimatedVBlank(RegistrationToken),
506 /// A redraw is queued on top of the above.
507 WaitingForEstimatedVBlankAndQueued(RegistrationToken),
508}
509
510pub struct PopupGrabState {
511 pub root: WlSurface,
512 pub grab: PopupGrab<State>,
513 pub has_keyboard_grab: bool,
514}
515
516// The surfaces here are always toplevel surfaces focused as far as niri's logic is concerned, even
517// when popup grabs are active (which means the real keyboard focus is on a popup descending from
518// that toplevel surface).
519#[derive(Debug, Clone, PartialEq, Eq)]
520pub enum KeyboardFocus {
521 // Layout is focused by default if there's nothing else to focus.
522 Layout { surface: Option<WlSurface> },
523 LayerShell { surface: WlSurface },
524 LockScreen { surface: Option<WlSurface> },
525 ScreenshotUi,
526 ExitConfirmDialog,
527 Overview,
528 Mru,
529}
530
531#[derive(Default, Clone, PartialEq)]
532pub struct PointContents {
533 // Output under point.
534 pub output: Option<Output>,
535 // Surface under point and its location in the global coordinate space.
536 //
537 // Can be `None` even when `window` is set, for example when the pointer is over the niri
538 // border around the window.
539 pub surface: Option<(WlSurface, Point<f64, Logical>)>,
540 // If surface belongs to a window, this is that window.
541 pub window: Option<(Window, HitType)>,
542 // If surface belongs to a layer surface, this is that layer surface.
543 pub layer: Option<LayerSurface>,
544 // Pointer is over a hot corner.
545 pub hot_corner: bool,
546}
547
548#[derive(Debug, Default)]
549pub enum LockState {
550 #[default]
551 Unlocked,
552 WaitingForSurfaces {
553 confirmation: SessionLocker,
554 deadline_token: RegistrationToken,
555 },
556 Locking(SessionLocker),
557 Locked(ExtSessionLockV1),
558}
559
560#[derive(PartialEq, Eq)]
561pub enum LockRenderState {
562 /// The output displays a normal session frame.
563 Unlocked,
564 /// The output displays a locked frame.
565 Locked,
566}
567
568// Not related to the one in Smithay.
569//
570// This state keeps track of when a surface last received a frame callback.
571struct SurfaceFrameThrottlingState {
572 /// Output and sequence that the frame callback was last sent at.
573 last_sent_at: RefCell<Option<(Output, u32)>>,
574}
575
576pub enum CenterCoords {
577 Separately,
578 Both,
579 // Force centering even if the cursor is already in the rectangle.
580 BothAlways,
581}
582
583#[derive(Clone, PartialEq, Eq)]
584pub enum CastTarget {
585 // Dynamic cast before selecting anything.
586 Nothing,
587 Output {
588 output: WeakOutput,
589 /// Cached name of the output.
590 name: String,
591 },
592 Window {
593 id: u64,
594 },
595}
596
597impl CastTarget {
598 pub fn output(output: &Output) -> Self {
599 Self::Output {
600 output: output.downgrade(),
601 name: output.name(),
602 }
603 }
604
605 pub fn matches_output(&self, weak: &WeakOutput) -> bool {
606 matches!(self, CastTarget::Output { output, .. } if output == weak)
607 }
608
609 pub fn matches(&self, ipc: &niri_ipc::CastTarget) -> bool {
610 use CastTarget::*;
611 match (self, ipc) {
612 (Nothing, niri_ipc::CastTarget::Nothing {}) => true,
613 (Output { name, .. }, niri_ipc::CastTarget::Output { name: ipc_name }) => {
614 name == ipc_name
615 }
616 (Window { id }, niri_ipc::CastTarget::Window { id: ipc_id }) => id == ipc_id,
617 _ => false,
618 }
619 }
620
621 pub fn make_ipc(&self) -> niri_ipc::CastTarget {
622 use CastTarget::*;
623 match self {
624 Nothing => niri_ipc::CastTarget::Nothing {},
625 Output { name, .. } => niri_ipc::CastTarget::Output { name: name.clone() },
626 Window { id } => niri_ipc::CastTarget::Window { id: *id },
627 }
628 }
629}
630
631/// Pending update to a window's focus timestamp.
632#[derive(Debug)]
633pub struct PendingMruCommit {
634 id: MappedId,
635 token: RegistrationToken,
636 stamp: Duration,
637}
638
639impl RedrawState {
640 fn queue_redraw(self) -> Self {
641 match self {
642 RedrawState::Idle => RedrawState::Queued,
643 RedrawState::WaitingForEstimatedVBlank(token) => {
644 RedrawState::WaitingForEstimatedVBlankAndQueued(token)
645 }
646
647 // A redraw is already queued.
648 value @ (RedrawState::Queued | RedrawState::WaitingForEstimatedVBlankAndQueued(_)) => {
649 value
650 }
651
652 // We're waiting for VBlank, request a redraw afterwards.
653 RedrawState::WaitingForVBlank { .. } => RedrawState::WaitingForVBlank {
654 redraw_needed: true,
655 },
656 }
657 }
658}
659
660impl Default for SurfaceFrameThrottlingState {
661 fn default() -> Self {
662 Self {
663 last_sent_at: RefCell::new(None),
664 }
665 }
666}
667
668impl KeyboardFocus {
669 pub fn surface(&self) -> Option<&WlSurface> {
670 match self {
671 KeyboardFocus::Layout { surface } => surface.as_ref(),
672 KeyboardFocus::LayerShell { surface } => Some(surface),
673 KeyboardFocus::LockScreen { surface } => surface.as_ref(),
674 KeyboardFocus::ScreenshotUi => None,
675 KeyboardFocus::ExitConfirmDialog => None,
676 KeyboardFocus::Overview => None,
677 KeyboardFocus::Mru => None,
678 }
679 }
680
681 pub fn into_surface(self) -> Option<WlSurface> {
682 match self {
683 KeyboardFocus::Layout { surface } => surface,
684 KeyboardFocus::LayerShell { surface } => Some(surface),
685 KeyboardFocus::LockScreen { surface } => surface,
686 KeyboardFocus::ScreenshotUi => None,
687 KeyboardFocus::ExitConfirmDialog => None,
688 KeyboardFocus::Overview => None,
689 KeyboardFocus::Mru => None,
690 }
691 }
692
693 pub fn is_layout(&self) -> bool {
694 matches!(self, KeyboardFocus::Layout { .. })
695 }
696
697 pub fn is_overview(&self) -> bool {
698 matches!(self, KeyboardFocus::Overview)
699 }
700}
701
702pub struct State {
703 pub backend: Backend,
704 pub niri: Niri,
705}
706
707impl State {
708 pub fn new(
709 config: Config,
710 event_loop: LoopHandle<'static, State>,
711 stop_signal: LoopSignal,
712 display: Display<State>,
713 headless: bool,
714 create_wayland_socket: bool,
715 is_session_instance: bool,
716 ) -> Result<Self, Box<dyn std::error::Error>> {
717 let _span = tracy_client::span!("State::new");
718
719 let config = Rc::new(RefCell::new(config));
720
721 let has_display = env::var_os("WAYLAND_DISPLAY").is_some()
722 || env::var_os("WAYLAND_SOCKET").is_some()
723 || env::var_os("DISPLAY").is_some();
724
725 let mut backend = if headless {
726 let headless = Headless::new();
727 Backend::Headless(headless)
728 } else if has_display {
729 let winit = Winit::new(config.clone(), event_loop.clone())?;
730 Backend::Winit(winit)
731 } else {
732 let tty = Tty::new(config.clone(), event_loop.clone())
733 .context("error initializing the TTY backend")?;
734 Backend::Tty(tty)
735 };
736
737 let mut niri = Niri::new(
738 config.clone(),
739 event_loop,
740 stop_signal,
741 display,
742 &backend,
743 create_wayland_socket,
744 is_session_instance,
745 );
746 backend.init(&mut niri);
747
748 let mut state = Self { backend, niri };
749
750 // Load the xkb_file config option if set by the user.
751 state.load_xkb_file();
752 // Initialize some IPC server state.
753 state.ipc_keyboard_layouts_changed();
754 // Focus the default monitor if set by the user.
755 state.focus_default_monitor();
756
757 Ok(state)
758 }
759
760 pub fn refresh_and_flush_clients(&mut self) {
761 let _span = tracy_client::span!("State::refresh_and_flush_clients");
762
763 self.refresh();
764
765 // Advance animations to the current time (not target render time) before rendering outputs
766 // in order to clear completed animations and render elements. Even if we're not rendering,
767 // it's good to advance every now and then so the workspace clean-up and animations don't
768 // build up (the 1 second frame callback timer will call this line).
769 self.niri.advance_animations();
770
771 self.niri.redraw_queued_outputs(&mut self.backend);
772
773 {
774 let _span = tracy_client::span!("flush_clients");
775 self.niri.display_handle.flush_clients().unwrap();
776 }
777
778 #[cfg(feature = "dbus")]
779 self.niri.update_locked_hint();
780
781 // Clear the time so it's fetched afresh next iteration.
782 self.niri.clock.clear();
783 self.niri.pointer_inactivity_timer_got_reset = false;
784 self.niri.notified_activity_this_iteration = false;
785 }
786
787 // We monitor both libinput and logind: libinput is always there (including without DBus), but
788 // it misses some switch events (e.g. after unsuspend) on some systems.
789 pub fn set_lid_closed(&mut self, is_closed: bool) {
790 if self.niri.is_lid_closed == is_closed {
791 return;
792 }
793
794 debug!("laptop lid {}", if is_closed { "closed" } else { "opened" });
795 self.niri.is_lid_closed = is_closed;
796 self.backend.on_output_config_changed(&mut self.niri);
797 }
798
799 fn refresh(&mut self) {
800 let _span = tracy_client::span!("State::refresh");
801
802 // Handle commits for surfaces whose blockers cleared this cycle. This should happen before
803 // layout.refresh() since this is where these surfaces handle commits.
804 self.notify_blocker_cleared();
805
806 // These should be called periodically, before flushing the clients.
807 self.niri.popups.cleanup();
808 self.refresh_popup_grab();
809 self.update_keyboard_focus();
810
811 // Should be called before refresh_layout() because that one will refresh other window
812 // states and then send a pending configure.
813 self.niri.refresh_window_states();
814
815 // Needs to be called after updating the keyboard focus.
816 self.niri.refresh_layout();
817
818 self.niri.cursor_manager.check_cursor_image_surface_alive();
819 self.niri.refresh_pointer_outputs();
820 self.niri.global_space.refresh();
821 self.niri.refresh_idle_inhibit();
822 self.refresh_pointer_contents();
823 foreign_toplevel::refresh(self);
824 ext_workspace::refresh(self);
825
826 #[cfg(feature = "xdp-gnome-screencast")]
827 self.niri.refresh_mapped_cast_outputs();
828 // Should happen before refresh_window_rules(), but after anything that can start or stop
829 // screencasts.
830 #[cfg(feature = "xdp-gnome-screencast")]
831 self.niri.refresh_mapped_cast_window_rules();
832 self.ipc_refresh_casts();
833
834 self.niri.refresh_window_rules();
835 self.refresh_ipc_outputs();
836 self.ipc_refresh_layout();
837 self.ipc_refresh_keyboard_layout_index();
838
839 // Needs to be called after updating the keyboard focus.
840 #[cfg(feature = "dbus")]
841 self.niri.refresh_a11y();
842 }
843
844 fn notify_blocker_cleared(&mut self) {
845 let dh = self.niri.display_handle.clone();
846 while let Ok(client) = self.niri.blocker_cleared_rx.try_recv() {
847 trace!("calling blocker_cleared");
848 self.client_compositor_state(&client)
849 .blocker_cleared(self, &dh);
850 }
851 }
852
853 pub fn move_cursor(&mut self, location: Point<f64, Logical>) {
854 let mut under = match self.niri.pointer_visibility {
855 PointerVisibility::Disabled => PointContents::default(),
856 _ => self.niri.contents_under(location),
857 };
858
859 // Disable the hidden pointer if the contents underneath have changed.
860 if !self.niri.pointer_visibility.is_visible() && self.niri.pointer_contents != under {
861 self.niri.pointer_visibility = PointerVisibility::Disabled;
862
863 // When setting PointerVisibility::Hidden together with pointer contents changing,
864 // we can change straight to nothing to avoid one frame of hover. Notably, this can
865 // be triggered through warp-mouse-to-focus combined with hide-when-typing.
866 under = PointContents::default();
867 }
868
869 self.niri.pointer_contents.clone_from(&under);
870
871 let pointer = &self.niri.seat.get_pointer().unwrap();
872 pointer.motion(
873 self,
874 under.surface,
875 &MotionEvent {
876 location,
877 serial: SERIAL_COUNTER.next_serial(),
878 time: get_monotonic_time().as_millis() as u32,
879 },
880 );
881 pointer.frame(self);
882
883 self.niri.maybe_activate_pointer_constraint();
884
885 // We do not show the pointer on programmatic or keyboard movement.
886
887 // FIXME: granular
888 self.niri.queue_redraw_all();
889 }
890
891 /// Moves cursor within the specified rectangle, only adjusting coordinates if needed.
892 fn move_cursor_to_rect(&mut self, rect: Rectangle<f64, Logical>, mode: CenterCoords) -> bool {
893 let pointer = &self.niri.seat.get_pointer().unwrap();
894 let cur_loc = pointer.current_location();
895 let x_in_bound = cur_loc.x >= rect.loc.x && cur_loc.x <= rect.loc.x + rect.size.w;
896 let y_in_bound = cur_loc.y >= rect.loc.y && cur_loc.y <= rect.loc.y + rect.size.h;
897
898 let p = match mode {
899 CenterCoords::Separately => {
900 if x_in_bound && y_in_bound {
901 return false;
902 } else if y_in_bound {
903 // adjust x
904 Point::from((rect.loc.x + rect.size.w / 2.0, cur_loc.y))
905 } else if x_in_bound {
906 // adjust y
907 Point::from((cur_loc.x, rect.loc.y + rect.size.h / 2.0))
908 } else {
909 // adjust x and y
910 center_f64(rect)
911 }
912 }
913 CenterCoords::Both => {
914 if x_in_bound && y_in_bound {
915 return false;
916 } else {
917 // adjust x and y
918 center_f64(rect)
919 }
920 }
921 CenterCoords::BothAlways => center_f64(rect),
922 };
923
924 self.move_cursor(p);
925 true
926 }
927
928 pub fn move_cursor_to_focused_tile(&mut self, mode: CenterCoords) -> bool {
929 if !self.niri.keyboard_focus.is_layout() {
930 return false;
931 }
932
933 if self.niri.tablet_cursor_location.is_some() {
934 return false;
935 }
936
937 let Some(output) = self.niri.layout.active_output() else {
938 return false;
939 };
940 let monitor = self.niri.layout.monitor_for_output(output).unwrap();
941
942 let mut rv = false;
943 let rect = monitor.active_window_visual_rectangle();
944
945 if let Some(rect) = rect {
946 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
947 let mut rect = rect;
948 rect.loc += output_geo.loc.to_f64();
949 rv = self.move_cursor_to_rect(rect, mode);
950 }
951
952 rv
953 }
954
955 pub fn focus_default_monitor(&mut self) {
956 // Our default target is the first output in sorted order.
957 let Some(mut target) = self.niri.sorted_outputs.first().cloned() else {
958 // No outputs are connected.
959 return;
960 };
961
962 let config = self.niri.config.borrow();
963 for config in &config.outputs.0 {
964 if !config.focus_at_startup {
965 continue;
966 }
967 if let Some(output) = self.niri.output_by_name_match(&config.name) {
968 target = output.clone();
969 break;
970 }
971 }
972 drop(config);
973
974 self.niri.layout.focus_output(&target);
975 self.move_cursor_to_output(&target);
976 }
977
978 /// Focus a specific window, taking care of a potential active output change and cursor
979 /// warp.
980 pub fn focus_window(&mut self, window: &Window) {
981 let active_output = self.niri.layout.active_output().cloned();
982
983 self.niri.layout.activate_window(window);
984
985 let new_active = self.niri.layout.active_output().cloned();
986 if new_active != active_output {
987 if !self.maybe_warp_cursor_to_focus_centered() {
988 self.move_cursor_to_output(&new_active.unwrap());
989 }
990 } else {
991 self.maybe_warp_cursor_to_focus();
992 }
993
994 // FIXME: granular
995 self.niri.queue_redraw_all();
996 }
997
998 pub fn confirm_mru(&mut self) {
999 if let Some(window) = self.niri.close_mru(MruCloseRequest::Confirm) {
1000 // focus_window() will warp the cursor to the window only when the keyboard focus is on
1001 // the layout. However, right now the keyboard focus is still on the MRU (that we had
1002 // just closed) since it's only updated at the end of the event loop cycle. Force-update
1003 // the keyboard focus here to make cursor warping work.
1004 self.update_keyboard_focus();
1005
1006 self.focus_window(&window);
1007 }
1008 }
1009
1010 pub fn maybe_warp_cursor_to_focus(&mut self) -> bool {
1011 let focused = match self.niri.config.borrow().input.warp_mouse_to_focus {
1012 None => return false,
1013 Some(inner) => match inner.mode {
1014 None => CenterCoords::Separately,
1015 Some(WarpMouseToFocusMode::CenterXy) => CenterCoords::Both,
1016 Some(WarpMouseToFocusMode::CenterXyAlways) => CenterCoords::BothAlways,
1017 },
1018 };
1019 self.move_cursor_to_focused_tile(focused)
1020 }
1021
1022 pub fn maybe_warp_cursor_to_focus_centered(&mut self) -> bool {
1023 let focused = match self.niri.config.borrow().input.warp_mouse_to_focus {
1024 None => return false,
1025 Some(inner) => match inner.mode {
1026 None => CenterCoords::Both,
1027 Some(WarpMouseToFocusMode::CenterXy) => CenterCoords::Both,
1028 Some(WarpMouseToFocusMode::CenterXyAlways) => CenterCoords::BothAlways,
1029 },
1030 };
1031 self.move_cursor_to_focused_tile(focused)
1032 }
1033
1034 pub fn refresh_pointer_contents(&mut self) {
1035 // Don't move the mouse pointer while the user is interacting with the tablet, as it causes
1036 // unwanted jumps for the client.
1037 if self.niri.tablet_cursor_location.is_some() {
1038 return;
1039 }
1040
1041 let _span = tracy_client::span!("Niri::refresh_pointer_contents");
1042
1043 let pointer = &self.niri.seat.get_pointer().unwrap();
1044 let location = pointer.current_location();
1045
1046 if !self.niri.exit_confirm_dialog.is_open()
1047 && !self.niri.is_locked()
1048 && !self.niri.screenshot_ui.is_open()
1049 {
1050 // Don't refresh cursor focus during transitions.
1051 if let Some((output, _)) = self.niri.output_under(location) {
1052 let monitor = self.niri.layout.monitor_for_output(output).unwrap();
1053 if monitor.are_transitions_ongoing() {
1054 return;
1055 }
1056 }
1057 }
1058
1059 if !self.update_pointer_contents() {
1060 return;
1061 }
1062
1063 pointer.frame(self);
1064
1065 // Pointer motion from a surface to nothing triggers a cursor change to default, which
1066 // means we may need to redraw.
1067
1068 // FIXME: granular
1069 self.niri.queue_redraw_all();
1070 }
1071
1072 pub fn update_pointer_contents(&mut self) -> bool {
1073 let _span = tracy_client::span!("Niri::update_pointer_contents");
1074
1075 let pointer = &self.niri.seat.get_pointer().unwrap();
1076 let location = pointer.current_location();
1077 let mut under = match self.niri.pointer_visibility {
1078 PointerVisibility::Disabled => PointContents::default(),
1079 _ => self.niri.contents_under(location),
1080 };
1081
1082 // We're not changing the global cursor location here, so if the contents did not change,
1083 // then nothing changed.
1084 if self.niri.pointer_contents == under {
1085 return false;
1086 }
1087
1088 // Disable the hidden pointer if the contents underneath have changed.
1089 if !self.niri.pointer_visibility.is_visible() {
1090 self.niri.pointer_visibility = PointerVisibility::Disabled;
1091
1092 // When setting PointerVisibility::Hidden together with pointer contents changing,
1093 // we can change straight to nothing to avoid one frame of hover. Notably, this can
1094 // be triggered through warp-mouse-to-focus combined with hide-when-typing.
1095 under = PointContents::default();
1096 if self.niri.pointer_contents == under {
1097 return false;
1098 }
1099 }
1100
1101 self.niri.pointer_contents.clone_from(&under);
1102
1103 pointer.motion(
1104 self,
1105 under.surface,
1106 &MotionEvent {
1107 location,
1108 serial: SERIAL_COUNTER.next_serial(),
1109 time: get_monotonic_time().as_millis() as u32,
1110 },
1111 );
1112
1113 self.niri.maybe_activate_pointer_constraint();
1114
1115 true
1116 }
1117
1118 pub fn move_cursor_to_output(&mut self, output: &Output) {
1119 let geo = self.niri.global_space.output_geometry(output).unwrap();
1120 self.move_cursor(center(geo).to_f64());
1121 }
1122
1123 pub fn refresh_popup_grab(&mut self) {
1124 if let Some(grab) = &mut self.niri.popup_grab {
1125 if grab.grab.has_ended() {
1126 self.niri.popup_grab = None;
1127 }
1128 }
1129 }
1130
1131 pub fn update_keyboard_focus(&mut self) {
1132 // Clean up on-demand layer surface focus if necessary.
1133 if let Some(surface) = &self.niri.layer_shell_on_demand_focus {
1134 // Still alive and has on-demand interactivity.
1135 let mut good = surface.alive()
1136 && surface.cached_state().keyboard_interactivity
1137 == wlr_layer::KeyboardInteractivity::OnDemand;
1138
1139 if let Some(mapped) = self.niri.mapped_layer_surfaces.get(surface) {
1140 // Check if it moved to the overview backdrop.
1141 if mapped.place_within_backdrop() {
1142 good = false;
1143 }
1144 } else {
1145 // The layer surface is alive but it got unmapped.
1146 good = false;
1147 }
1148
1149 if !good {
1150 self.niri.layer_shell_on_demand_focus = None;
1151 }
1152 }
1153
1154 // Compute the current focus.
1155 let focus = if self.niri.exit_confirm_dialog.is_open() {
1156 KeyboardFocus::ExitConfirmDialog
1157 } else if self.niri.is_locked() {
1158 KeyboardFocus::LockScreen {
1159 surface: self.niri.lock_surface_focus(),
1160 }
1161 } else if self.niri.screenshot_ui.is_open() {
1162 KeyboardFocus::ScreenshotUi
1163 } else if self.niri.window_mru_ui.is_open() {
1164 KeyboardFocus::Mru
1165 } else if let Some(output) = self.niri.layout.active_output() {
1166 let mon = self.niri.layout.monitor_for_output(output).unwrap();
1167 let layers = layer_map_for_output(output);
1168
1169 // Explicitly check for layer-shell popup grabs here, our keyboard focus will stay on
1170 // the root layer surface while it has grabs.
1171 let layer_grab = self.niri.popup_grab.as_ref().and_then(|g| {
1172 layers
1173 .layer_for_surface(&g.root, WindowSurfaceType::TOPLEVEL)
1174 .and_then(|l| l.can_receive_keyboard_focus().then(|| (&g.root, l.layer())))
1175 });
1176 let grab_on_layer = |layer: Layer| {
1177 layer_grab
1178 .and_then(move |(s, l)| if l == layer { Some(s.clone()) } else { None })
1179 .map(|surface| KeyboardFocus::LayerShell { surface })
1180 };
1181
1182 let layout_focus = || {
1183 self.niri
1184 .layout
1185 .focus()
1186 .map(|win| win.toplevel().wl_surface().clone())
1187 .map(|surface| KeyboardFocus::Layout {
1188 surface: Some(surface),
1189 })
1190 };
1191
1192 let excl_focus_on_layer = |layer| {
1193 layers.layers_on(layer).find_map(|surface| {
1194 if surface.cached_state().keyboard_interactivity
1195 != wlr_layer::KeyboardInteractivity::Exclusive
1196 {
1197 return None;
1198 }
1199
1200 let mapped = self.niri.mapped_layer_surfaces.get(surface)?;
1201 if mapped.place_within_backdrop() {
1202 return None;
1203 }
1204
1205 let surface = surface.wl_surface().clone();
1206 Some(KeyboardFocus::LayerShell { surface })
1207 })
1208 };
1209
1210 let on_d_focus_on_layer = |layer| {
1211 layers.layers_on(layer).find_map(|surface| {
1212 let is_on_demand_surface =
1213 Some(surface) == self.niri.layer_shell_on_demand_focus.as_ref();
1214 is_on_demand_surface
1215 .then(|| surface.wl_surface().clone())
1216 .map(|surface| KeyboardFocus::LayerShell { surface })
1217 })
1218 };
1219
1220 // Prefer exclusive focus on a layer, then check on-demand focus.
1221 let focus_on_layer =
1222 |layer| excl_focus_on_layer(layer).or_else(|| on_d_focus_on_layer(layer));
1223
1224 let is_overview_open = self.niri.layout.is_overview_open();
1225
1226 let mut surface = grab_on_layer(Layer::Overlay);
1227 // FIXME: we shouldn't prioritize the top layer grabs over regular overlay input or a
1228 // fullscreen layout window. This will need tracking in grab() to avoid handing it out
1229 // in the first place. Or a better way to structure this code.
1230 surface = surface.or_else(|| grab_on_layer(Layer::Top));
1231
1232 if !is_overview_open {
1233 surface = surface.or_else(|| grab_on_layer(Layer::Bottom));
1234 surface = surface.or_else(|| grab_on_layer(Layer::Background));
1235 }
1236
1237 surface = surface.or_else(|| focus_on_layer(Layer::Overlay));
1238
1239 if mon.render_above_top_layer() {
1240 surface = surface.or_else(layout_focus);
1241 surface = surface.or_else(|| focus_on_layer(Layer::Top));
1242 surface = surface.or_else(|| focus_on_layer(Layer::Bottom));
1243 surface = surface.or_else(|| focus_on_layer(Layer::Background));
1244 } else {
1245 surface = surface.or_else(|| focus_on_layer(Layer::Top));
1246
1247 if is_overview_open {
1248 surface = Some(surface.unwrap_or(KeyboardFocus::Overview));
1249 }
1250
1251 surface = surface.or_else(|| on_d_focus_on_layer(Layer::Bottom));
1252 surface = surface.or_else(|| on_d_focus_on_layer(Layer::Background));
1253 surface = surface.or_else(layout_focus);
1254
1255 // Bottom and background layers can only receive exclusive focus when there are no
1256 // layout windows.
1257 surface = surface.or_else(|| excl_focus_on_layer(Layer::Bottom));
1258 surface = surface.or_else(|| excl_focus_on_layer(Layer::Background));
1259 }
1260
1261 surface.unwrap_or(KeyboardFocus::Layout { surface: None })
1262 } else {
1263 KeyboardFocus::Layout { surface: None }
1264 };
1265
1266 let keyboard = self.niri.seat.get_keyboard().unwrap();
1267 if self.niri.keyboard_focus != focus {
1268 trace!(
1269 "keyboard focus changed from {:?} to {:?}",
1270 self.niri.keyboard_focus,
1271 focus
1272 );
1273
1274 // Tell the windows their new focus state for window rule purposes.
1275 if let KeyboardFocus::Layout {
1276 surface: Some(surface),
1277 } = &self.niri.keyboard_focus
1278 {
1279 if let Some((mapped, _)) = self.niri.layout.find_window_and_output_mut(surface) {
1280 mapped.set_is_focused(false);
1281 }
1282 }
1283 if let KeyboardFocus::Layout {
1284 surface: Some(surface),
1285 } = &focus
1286 {
1287 if let Some((mapped, _)) = self.niri.layout.find_window_and_output_mut(surface) {
1288 mapped.set_is_focused(true);
1289
1290 // If `mapped` does not have a focus timestamp, then the window is newly
1291 // created/mapped and a timestamp is unconditionally created.
1292 //
1293 // If `mapped` already has a timestamp only update it after the focus lock-in
1294 // period has gone by without the focus having elsewhere.
1295 let stamp = get_monotonic_time();
1296
1297 let debounce = self.niri.config.borrow().recent_windows.debounce_ms;
1298 let debounce = Duration::from_millis(u64::from(debounce));
1299
1300 if mapped.get_focus_timestamp().is_none() || debounce.is_zero() {
1301 mapped.set_focus_timestamp(stamp);
1302 } else {
1303 let timer = Timer::from_duration(debounce);
1304
1305 let focus_token = self
1306 .niri
1307 .event_loop
1308 .insert_source(timer, move |_, _, state| {
1309 state.niri.mru_apply_keyboard_commit();
1310 TimeoutAction::Drop
1311 })
1312 .unwrap();
1313 if let Some(PendingMruCommit { token, .. }) =
1314 self.niri.pending_mru_commit.replace(PendingMruCommit {
1315 id: mapped.id(),
1316 token: focus_token,
1317 stamp,
1318 })
1319 {
1320 self.niri.event_loop.remove(token);
1321 }
1322 }
1323 }
1324 }
1325
1326 if let Some(grab) = self.niri.popup_grab.as_mut() {
1327 if grab.has_keyboard_grab && Some(&grab.root) != focus.surface() {
1328 trace!(
1329 "grab root {:?} is not the new focus {:?}, ungrabbing",
1330 grab.root,
1331 focus
1332 );
1333
1334 grab.grab.ungrab(PopupUngrabStrategy::All);
1335 keyboard.unset_grab(self);
1336 self.niri.seat.get_pointer().unwrap().unset_grab(
1337 self,
1338 SERIAL_COUNTER.next_serial(),
1339 get_monotonic_time().as_millis() as u32,
1340 );
1341 self.niri.popup_grab = None;
1342 }
1343 }
1344
1345 if self.niri.config.borrow().input.keyboard.track_layout == TrackLayout::Window {
1346 let current_layout = keyboard.with_xkb_state(self, |context| {
1347 let xkb = context.xkb().lock().unwrap();
1348 xkb.active_layout()
1349 });
1350
1351 let mut new_layout = current_layout;
1352 // Store the currently active layout for the surface.
1353 if let Some(current_focus) = self.niri.keyboard_focus.surface() {
1354 with_states(current_focus, |data| {
1355 let cell = data
1356 .data_map
1357 .get_or_insert::<Cell<KeyboardLayout>, _>(Cell::default);
1358 cell.set(current_layout);
1359 });
1360 }
1361
1362 if let Some(focus) = focus.surface() {
1363 new_layout = with_states(focus, |data| {
1364 let cell = data.data_map.get_or_insert::<Cell<KeyboardLayout>, _>(|| {
1365 // The default layout is effectively the first layout in the
1366 // keymap, so use it for new windows.
1367 Cell::new(KeyboardLayout::default())
1368 });
1369 cell.get()
1370 });
1371 }
1372 if new_layout != current_layout && focus.surface().is_some() {
1373 keyboard.set_focus(self, None, SERIAL_COUNTER.next_serial());
1374 keyboard.with_xkb_state(self, |mut context| {
1375 context.set_layout(new_layout);
1376 });
1377 }
1378 }
1379
1380 self.niri.keyboard_focus.clone_from(&focus);
1381 keyboard.set_focus(self, focus.into_surface(), SERIAL_COUNTER.next_serial());
1382
1383 // FIXME: can be more granular.
1384 self.niri.queue_redraw_all();
1385 }
1386 }
1387
1388 /// Loads the xkb keymap from a file config setting.
1389 fn set_xkb_file(&mut self, xkb_file: String) -> anyhow::Result<()> {
1390 let xkb_file = PathBuf::from(xkb_file);
1391 let xkb_file = expand_home(&xkb_file)
1392 .context("failed to expand ~")?
1393 .unwrap_or(xkb_file);
1394
1395 let keymap = std::fs::read_to_string(xkb_file).context("failed to read xkb_file")?;
1396
1397 let keyboard = self.niri.seat.get_keyboard().unwrap();
1398 let num_lock = keyboard.modifier_state().num_lock;
1399
1400 keyboard
1401 .set_keymap_from_string(self, keymap)
1402 .context("failed to set keymap")?;
1403
1404 // Restore num lock to its previous value.
1405 let mut mods_state = keyboard.modifier_state();
1406 if mods_state.num_lock != num_lock {
1407 mods_state.num_lock = num_lock;
1408 keyboard.set_modifier_state(mods_state);
1409 }
1410
1411 Ok(())
1412 }
1413
1414 fn load_xkb_file(&mut self) {
1415 let xkb_file = self.niri.config.borrow().input.keyboard.xkb.file.clone();
1416 if let Some(xkb_file) = xkb_file {
1417 if let Err(err) = self.set_xkb_file(xkb_file) {
1418 warn!("error loading xkb_file: {err:?}");
1419 }
1420 }
1421 }
1422
1423 pub fn set_xkb_config(&mut self, xkb: XkbConfig) {
1424 let keyboard = self.niri.seat.get_keyboard().unwrap();
1425 let num_lock = keyboard.modifier_state().num_lock;
1426 if let Err(err) = keyboard.set_xkb_config(self, xkb) {
1427 warn!("error updating xkb config: {err:?}");
1428 return;
1429 }
1430
1431 // Restore num lock to its previous value.
1432 let mut mods_state = keyboard.modifier_state();
1433 if mods_state.num_lock != num_lock {
1434 mods_state.num_lock = num_lock;
1435 keyboard.set_modifier_state(mods_state);
1436 }
1437 }
1438
1439 pub fn reload_config(&mut self, config: Result<Config, ()>) {
1440 let _span = tracy_client::span!("State::reload_config");
1441
1442 let mut config = match config {
1443 Ok(config) => config,
1444 Err(()) => {
1445 self.niri.config_error_notification.show();
1446 self.niri.queue_redraw_all();
1447
1448 #[cfg(feature = "dbus")]
1449 self.niri.a11y_announce_config_error();
1450
1451 return;
1452 }
1453 };
1454
1455 self.niri.config_error_notification.hide();
1456
1457 // Find & orphan removed named workspaces.
1458 let mut removed_workspaces: Vec<String> = vec![];
1459 for ws in &self.niri.config.borrow().workspaces {
1460 if !config.workspaces.iter().any(|w| w.name == ws.name) {
1461 removed_workspaces.push(ws.name.0.clone());
1462 }
1463 }
1464 for name in removed_workspaces {
1465 self.niri.layout.unname_workspace(&name);
1466 }
1467
1468 self.niri.layout.update_config(&config);
1469 for mapped in self.niri.mapped_layer_surfaces.values_mut() {
1470 mapped.update_config(&config);
1471 }
1472
1473 // Create new named workspaces.
1474 for ws_config in &config.workspaces {
1475 self.niri.layout.ensure_named_workspace(ws_config);
1476 }
1477
1478 let rate = 1.0 / config.animations.slowdown.max(0.001);
1479 self.niri.clock.set_rate(rate);
1480 self.niri
1481 .clock
1482 .set_complete_instantly(config.animations.off);
1483
1484 *CHILD_ENV.write().unwrap() = mem::take(&mut config.environment);
1485
1486 let mut reload_xkb = None;
1487 let mut libinput_config_changed = false;
1488 let mut output_config_changed = false;
1489 let mut preserved_output_config = None;
1490 let mut window_rules_changed = false;
1491 let mut layer_rules_changed = false;
1492 let mut shaders_changed = false;
1493 let mut cursor_inactivity_timeout_changed = false;
1494 let mut recent_windows_changed = false;
1495 let mut xwls_changed = false;
1496 let mut old_config = self.niri.config.borrow_mut();
1497
1498 // Reload the cursor.
1499 if config.cursor != old_config.cursor {
1500 self.niri
1501 .cursor_manager
1502 .reload(&config.cursor.xcursor_theme, config.cursor.xcursor_size);
1503 self.niri.cursor_texture_cache.clear();
1504 }
1505
1506 // We need &mut self to reload the xkb config, so just store it here.
1507 if config.input.keyboard.xkb != old_config.input.keyboard.xkb {
1508 reload_xkb = Some(config.input.keyboard.xkb.clone());
1509 }
1510
1511 // Reload the repeat info.
1512 if config.input.keyboard.repeat_rate != old_config.input.keyboard.repeat_rate
1513 || config.input.keyboard.repeat_delay != old_config.input.keyboard.repeat_delay
1514 {
1515 let keyboard = self.niri.seat.get_keyboard().unwrap();
1516 keyboard.change_repeat_info(
1517 config.input.keyboard.repeat_rate.into(),
1518 config.input.keyboard.repeat_delay.into(),
1519 );
1520 }
1521
1522 if config.input.touchpad != old_config.input.touchpad
1523 || config.input.mouse != old_config.input.mouse
1524 || config.input.trackball != old_config.input.trackball
1525 || config.input.trackpoint != old_config.input.trackpoint
1526 || config.input.tablet != old_config.input.tablet
1527 || config.input.touch != old_config.input.touch
1528 {
1529 libinput_config_changed = true;
1530 }
1531
1532 let ignored_nodes_changed =
1533 config.debug.ignored_drm_devices != old_config.debug.ignored_drm_devices;
1534
1535 if config.outputs != self.niri.config_file_output_config {
1536 output_config_changed = true;
1537 self.niri
1538 .config_file_output_config
1539 .clone_from(&config.outputs);
1540 } else {
1541 // Output config did not change from the last disk load, so we need to preserve the
1542 // transient changes.
1543 preserved_output_config = Some(mem::take(&mut old_config.outputs));
1544 }
1545
1546 let binds_changed = config.binds != old_config.binds;
1547 let new_mod_key = self.backend.mod_key(&config);
1548 if new_mod_key != self.backend.mod_key(&old_config) || binds_changed {
1549 self.niri
1550 .hotkey_overlay
1551 .on_hotkey_config_updated(new_mod_key);
1552 self.niri.mods_with_mouse_binds = mods_with_mouse_binds(new_mod_key, &config.binds);
1553 self.niri.mods_with_wheel_binds = mods_with_wheel_binds(new_mod_key, &config.binds);
1554 self.niri.mods_with_tablet_stylus_binds =
1555 mods_with_tablet_stylus_binds(new_mod_key, &config.binds);
1556 self.niri.mods_with_finger_scroll_binds =
1557 mods_with_finger_scroll_binds(new_mod_key, &config.binds);
1558 }
1559
1560 if config.window_rules != old_config.window_rules {
1561 window_rules_changed = true;
1562 }
1563
1564 if config.layer_rules != old_config.layer_rules {
1565 layer_rules_changed = true;
1566 }
1567
1568 if config.animations.window_resize.custom_shader
1569 != old_config.animations.window_resize.custom_shader
1570 {
1571 let src = config.animations.window_resize.custom_shader.as_deref();
1572 self.backend.with_primary_renderer(|renderer| {
1573 shaders::set_custom_resize_program(renderer, src);
1574 });
1575 shaders_changed = true;
1576 }
1577
1578 if config.animations.window_close.custom_shader
1579 != old_config.animations.window_close.custom_shader
1580 {
1581 let src = config.animations.window_close.custom_shader.as_deref();
1582 self.backend.with_primary_renderer(|renderer| {
1583 shaders::set_custom_close_program(renderer, src);
1584 });
1585 shaders_changed = true;
1586 }
1587
1588 if config.animations.window_open.custom_shader
1589 != old_config.animations.window_open.custom_shader
1590 {
1591 let src = config.animations.window_open.custom_shader.as_deref();
1592 self.backend.with_primary_renderer(|renderer| {
1593 shaders::set_custom_open_program(renderer, src);
1594 });
1595 shaders_changed = true;
1596 }
1597
1598 if config.cursor.hide_after_inactive_ms != old_config.cursor.hide_after_inactive_ms {
1599 cursor_inactivity_timeout_changed = true;
1600 }
1601
1602 if config.debug.keep_laptop_panel_on_when_lid_is_closed
1603 != old_config.debug.keep_laptop_panel_on_when_lid_is_closed
1604 {
1605 output_config_changed = true;
1606 }
1607
1608 if config.debug.ignored_drm_devices != old_config.debug.ignored_drm_devices {
1609 output_config_changed = true;
1610 }
1611
1612 // FIXME: move backdrop rendering into layout::Monitor, then this will become unnecessary.
1613 if config.overview.backdrop_color != old_config.overview.backdrop_color {
1614 output_config_changed = true;
1615 }
1616 if config.layout.background_color != old_config.layout.background_color {
1617 output_config_changed = true;
1618 }
1619
1620 if config.recent_windows != old_config.recent_windows {
1621 recent_windows_changed = true;
1622 }
1623
1624 if config.xwayland_satellite != old_config.xwayland_satellite {
1625 xwls_changed = true;
1626 }
1627
1628 *old_config = config;
1629
1630 if let Some(outputs) = preserved_output_config {
1631 old_config.outputs = outputs;
1632 }
1633
1634 // Release the borrow.
1635 drop(old_config);
1636
1637 // Now with a &mut self we can reload the xkb config.
1638 if let Some(mut xkb) = reload_xkb {
1639 let mut set_xkb_config = true;
1640
1641 // It's fine to .take() the xkb file, as this is a
1642 // clone and the file field is not used in the XkbConfig.
1643 if let Some(xkb_file) = xkb.file.take() {
1644 if let Err(err) = self.set_xkb_file(xkb_file) {
1645 warn!("error reloading xkb_file: {err:?}");
1646 } else {
1647 // We successfully set xkb file so we don't need to fallback to XkbConfig.
1648 set_xkb_config = false;
1649 }
1650 }
1651
1652 if set_xkb_config {
1653 // If xkb is unset in the niri config, use settings from locale1.
1654 if xkb == Xkb::default() {
1655 trace!("using xkb from locale1");
1656 xkb = self.niri.xkb_from_locale1.clone().unwrap_or_default();
1657 }
1658
1659 self.set_xkb_config(xkb.to_xkb_config());
1660 }
1661
1662 self.ipc_keyboard_layouts_changed();
1663 }
1664
1665 if libinput_config_changed {
1666 let config = self.niri.config.borrow();
1667 for mut device in self.niri.devices.iter().cloned() {
1668 apply_libinput_settings(&config.input, &mut device);
1669 }
1670 }
1671
1672 if ignored_nodes_changed {
1673 self.backend.update_ignored_nodes_config(&mut self.niri);
1674 }
1675
1676 if output_config_changed {
1677 self.reload_output_config();
1678 }
1679
1680 if window_rules_changed {
1681 self.niri.recompute_window_rules();
1682 }
1683
1684 if layer_rules_changed {
1685 self.niri.recompute_layer_rules();
1686 }
1687
1688 if shaders_changed {
1689 self.niri.update_shaders();
1690 }
1691
1692 if cursor_inactivity_timeout_changed {
1693 // Force reset due to timeout change.
1694 self.niri.pointer_inactivity_timer_got_reset = false;
1695 self.niri.reset_pointer_inactivity_timer();
1696 }
1697
1698 if binds_changed {
1699 self.niri.window_mru_ui.update_binds();
1700 }
1701
1702 if recent_windows_changed {
1703 self.niri.window_mru_ui.update_config();
1704 }
1705
1706 if xwls_changed {
1707 // If xwl-s was previously working and is now off, we don't try to kill it or stop
1708 // watching the sockets, for simplicity's sake.
1709 let was_working = self.niri.satellite.is_some();
1710
1711 // Try to start, or restart in case the user corrected the path or something.
1712 xwayland::satellite::setup(self);
1713
1714 let config = self.niri.config.borrow();
1715 let display_name = (!config.xwayland_satellite.off)
1716 .then_some(self.niri.satellite.as_ref())
1717 .flatten()
1718 .map(|satellite| satellite.display_name().to_owned());
1719
1720 if let Some(name) = &display_name {
1721 if !was_working {
1722 info!("listening on X11 socket: {name}");
1723 }
1724 }
1725
1726 // This won't change the systemd environment, but oh well.
1727 *CHILD_DISPLAY.write().unwrap() = display_name;
1728 }
1729
1730 // Can't really update xdg-decoration settings since we have to hide the globals for CSD
1731 // due to the SDL2 bug... I don't imagine clients are prepared for the xdg-decoration
1732 // global suddenly appearing? Either way, right now it's live-reloaded in a sense that new
1733 // clients will use the new xdg-decoration setting.
1734
1735 self.niri.queue_redraw_all();
1736 }
1737
1738 pub fn reload_output_config(&mut self) {
1739 let mut resized_outputs = vec![];
1740 let mut recolored_outputs = vec![];
1741
1742 for output in self.niri.global_space.outputs() {
1743 let name = output.user_data().get::<OutputName>().unwrap();
1744 let full_config = self.niri.config.borrow_mut();
1745 let config = full_config.outputs.find(name);
1746
1747 let scale = config
1748 .and_then(|c| c.scale)
1749 .map(|s| s.0)
1750 .unwrap_or_else(|| {
1751 let size_mm = output.physical_properties().size;
1752 let resolution = output.current_mode().unwrap().size;
1753 guess_monitor_scale(size_mm, resolution)
1754 });
1755 let scale = closest_representable_scale(scale.clamp(0.1, 10.));
1756
1757 let mut transform = panel_orientation(output)
1758 + config
1759 .map(|c| ipc_transform_to_smithay(c.transform))
1760 .unwrap_or(Transform::Normal);
1761 // FIXME: fix winit damage on other transforms.
1762 if name.connector == "winit" {
1763 transform = Transform::Flipped180;
1764 }
1765
1766 if output.current_scale().fractional_scale() != scale
1767 || output.current_transform() != transform
1768 {
1769 output.change_current_state(
1770 None,
1771 Some(transform),
1772 Some(output::Scale::Fractional(scale)),
1773 None,
1774 );
1775 self.niri.ipc_outputs_changed = true;
1776 resized_outputs.push(output.clone());
1777 }
1778
1779 let mut backdrop_color = config
1780 .and_then(|c| c.backdrop_color)
1781 .unwrap_or(full_config.overview.backdrop_color)
1782 .to_array_unpremul();
1783 backdrop_color[3] = 1.;
1784 let backdrop_color = Color32F::from(backdrop_color);
1785
1786 if let Some(state) = self.niri.output_state.get_mut(output) {
1787 if state.backdrop_buffer.color() != backdrop_color {
1788 state.backdrop_buffer.set_color(backdrop_color);
1789 recolored_outputs.push(output.clone());
1790 }
1791 }
1792
1793 for mon in self.niri.layout.monitors_mut() {
1794 if mon.output() != output {
1795 continue;
1796 }
1797
1798 let mut layout_config = config.and_then(|c| c.layout.clone());
1799 // Support the deprecated non-layout background-color key.
1800 if let Some(layout) = &mut layout_config {
1801 if layout.background_color.is_none() {
1802 layout.background_color = config.and_then(|c| c.background_color);
1803 }
1804 }
1805
1806 if mon.update_layout_config(layout_config) {
1807 // Also redraw these; if anything, the background color could've changed.
1808 recolored_outputs.push(output.clone());
1809 }
1810 break;
1811 }
1812 }
1813
1814 for output in resized_outputs {
1815 self.niri.output_resized(&output);
1816 }
1817
1818 for output in recolored_outputs {
1819 self.niri.queue_redraw(&output);
1820 }
1821
1822 self.backend.on_output_config_changed(&mut self.niri);
1823
1824 self.niri.reposition_outputs(None);
1825
1826 if let Some(touch) = self.niri.seat.get_touch() {
1827 touch.cancel(self);
1828 }
1829
1830 let config = self.niri.config.borrow().outputs.clone();
1831 self.niri.output_management_state.on_config_changed(config);
1832 }
1833
1834 pub fn modify_output_config<F>(&mut self, name: &str, fun: F)
1835 where
1836 F: FnOnce(&mut niri_config::Output),
1837 {
1838 // Try hard to find the output config section corresponding to the output set by the
1839 // user. Since if we add a new section and some existing section also matches the
1840 // output, then our new section won't do anything.
1841 let temp;
1842 let match_name = if let Some(output) = self.niri.output_by_name_match(name) {
1843 output.user_data().get::<OutputName>().unwrap()
1844 } else if let Some(output_name) = self
1845 .backend
1846 .tty_checked()
1847 .and_then(|tty| tty.disconnected_connector_name_by_name_match(name))
1848 {
1849 temp = output_name;
1850 &temp
1851 } else {
1852 // Even if name is "make model serial", matching will work fine this way.
1853 temp = OutputName {
1854 connector: name.to_owned(),
1855 make: None,
1856 model: None,
1857 serial: None,
1858 };
1859 &temp
1860 };
1861
1862 let mut config = self.niri.config.borrow_mut();
1863 let config = if let Some(config) = config.outputs.find_mut(match_name) {
1864 config
1865 } else {
1866 config.outputs.0.push(niri_config::Output {
1867 // Save name as set by the user.
1868 name: String::from(name),
1869 ..Default::default()
1870 });
1871 config.outputs.0.last_mut().unwrap()
1872 };
1873
1874 fun(config);
1875 }
1876
1877 pub fn apply_transient_output_config(&mut self, name: &str, action: niri_ipc::OutputAction) {
1878 self.modify_output_config(name, move |config| match action {
1879 niri_ipc::OutputAction::Off => config.off = true,
1880 niri_ipc::OutputAction::On => config.off = false,
1881 niri_ipc::OutputAction::Mode { mode } => {
1882 config.mode = match mode {
1883 niri_ipc::ModeToSet::Automatic => None,
1884 niri_ipc::ModeToSet::Specific(mode) => Some(niri_config::output::Mode {
1885 custom: false,
1886 mode,
1887 }),
1888 };
1889 config.modeline = None;
1890 }
1891 niri_ipc::OutputAction::CustomMode { mode } => {
1892 config.mode = Some(niri_config::output::Mode { custom: true, mode });
1893 config.modeline = None;
1894 }
1895 niri_ipc::OutputAction::Modeline {
1896 clock,
1897 hdisplay,
1898 hsync_start,
1899 hsync_end,
1900 htotal,
1901 vdisplay,
1902 vsync_start,
1903 vsync_end,
1904 vtotal,
1905 hsync_polarity,
1906 vsync_polarity,
1907 } => {
1908 // Do not reset config.mode to None since it's used as a fallback.
1909 config.modeline = Some(niri_config::output::Modeline {
1910 clock,
1911 hdisplay,
1912 hsync_start,
1913 hsync_end,
1914 htotal,
1915 vdisplay,
1916 vsync_start,
1917 vsync_end,
1918 vtotal,
1919 hsync_polarity,
1920 vsync_polarity,
1921 })
1922 }
1923 niri_ipc::OutputAction::Scale { scale } => {
1924 config.scale = match scale {
1925 niri_ipc::ScaleToSet::Automatic => None,
1926 niri_ipc::ScaleToSet::Specific(scale) => Some(FloatOrInt(scale)),
1927 }
1928 }
1929 niri_ipc::OutputAction::Transform { transform } => config.transform = transform,
1930 niri_ipc::OutputAction::Position { position } => {
1931 config.position = match position {
1932 niri_ipc::PositionToSet::Automatic => None,
1933 niri_ipc::PositionToSet::Specific(position) => Some(niri_config::Position {
1934 x: position.x,
1935 y: position.y,
1936 }),
1937 }
1938 }
1939 niri_ipc::OutputAction::Vrr { vrr } => {
1940 config.variable_refresh_rate = if vrr.vrr {
1941 Some(niri_config::Vrr {
1942 on_demand: vrr.on_demand,
1943 })
1944 } else {
1945 None
1946 }
1947 }
1948 niri_ipc::OutputAction::MaxBpc { max_bpc } => config.max_bpc = Some(MaxBpc(max_bpc)),
1949 });
1950
1951 self.reload_output_config();
1952 }
1953
1954 pub fn refresh_ipc_outputs(&mut self) {
1955 if !self.niri.ipc_outputs_changed {
1956 return;
1957 }
1958 self.niri.ipc_outputs_changed = false;
1959
1960 let _span = tracy_client::span!("State::refresh_ipc_outputs");
1961
1962 for ipc_output in self.backend.ipc_outputs().lock().unwrap().values_mut() {
1963 let logical = self
1964 .niri
1965 .global_space
1966 .outputs()
1967 .find(|output| output.name() == ipc_output.name)
1968 .map(logical_output);
1969 ipc_output.logical = logical;
1970 }
1971
1972 #[cfg(feature = "dbus")]
1973 self.niri.on_ipc_outputs_changed();
1974
1975 let new_config = self.backend.ipc_outputs().lock().unwrap().clone();
1976 self.niri.output_management_state.notify_changes(new_config);
1977 }
1978
1979 pub fn open_screenshot_ui(&mut self, show_pointer: bool, path: Option<String>) {
1980 if self.niri.is_locked() || self.niri.screenshot_ui.is_open() {
1981 return;
1982 }
1983
1984 let default_output = self
1985 .niri
1986 .output_under_cursor()
1987 .or_else(|| self.niri.layout.active_output().cloned());
1988 let Some(default_output) = default_output else {
1989 return;
1990 };
1991
1992 self.niri.update_render_elements(None);
1993
1994 let Some(screenshots) = self
1995 .backend
1996 .with_primary_renderer(|renderer| self.niri.capture_screenshots(renderer).collect())
1997 else {
1998 return;
1999 };
2000
2001 // Now that we captured the screenshots, clear grabs like drag-and-drop, etc.
2002 let time = get_monotonic_time().as_millis() as u32;
2003 self.niri
2004 .seat
2005 .get_pointer()
2006 .unwrap()
2007 .unset_grab(self, SERIAL_COUNTER.next_serial(), time);
2008 if let Some(touch) = self.niri.seat.get_touch() {
2009 touch.unset_grab(self);
2010 }
2011
2012 // Can't unset_grab() from with_tools(), will deadlock on tablet seat mutex...
2013 let mut tools = Vec::new();
2014 self.niri.seat.tablet_seat().with_tools(|map| {
2015 tools = Vec::from_iter(map.values().cloned());
2016 });
2017 for tool in tools {
2018 tool.unset_grab(self, SERIAL_COUNTER.next_serial(), time);
2019 }
2020
2021 self.backend.with_primary_renderer(|renderer| {
2022 self.niri
2023 .screenshot_ui
2024 .open(renderer, screenshots, default_output, show_pointer, path)
2025 });
2026
2027 self.niri
2028 .cursor_manager
2029 .set_cursor_image(CursorImageStatus::Named(CursorIcon::Crosshair));
2030 self.niri.queue_redraw_all();
2031 }
2032
2033 pub fn handle_pick_color(&mut self, tx: async_channel::Sender<Option<niri_ipc::PickedColor>>) {
2034 let pointer = self.niri.seat.get_pointer().unwrap();
2035 let start_data = PointerGrabStartData {
2036 focus: None,
2037 button: 0,
2038 location: pointer.current_location(),
2039 };
2040 let grab = PickColorGrab::new(start_data);
2041 pointer.set_grab(self, grab, SERIAL_COUNTER.next_serial(), Focus::Clear);
2042 self.niri.pick_color = Some(tx);
2043 self.niri
2044 .cursor_manager
2045 .set_cursor_image(CursorImageStatus::Named(CursorIcon::Crosshair));
2046 self.niri.queue_redraw_all();
2047 }
2048
2049 pub fn confirm_screenshot(&mut self, write_to_disk: bool) {
2050 let ScreenshotUi::Open { path, .. } = &mut self.niri.screenshot_ui else {
2051 return;
2052 };
2053 let path = path.take();
2054
2055 self.backend.with_primary_renderer(|renderer| {
2056 match self.niri.screenshot_ui.capture(renderer) {
2057 Ok((size, pixels)) => {
2058 if let Err(err) = self.niri.save_screenshot(size, pixels, write_to_disk, path) {
2059 warn!("error saving screenshot: {err:?}");
2060 }
2061 }
2062 Err(err) => {
2063 warn!("error capturing screenshot: {err:?}");
2064 }
2065 }
2066 });
2067
2068 self.niri.screenshot_ui.close();
2069 self.niri
2070 .cursor_manager
2071 .set_cursor_image(CursorImageStatus::default_named());
2072 self.niri.queue_redraw_all();
2073 }
2074
2075 pub fn store_unmap_snapshot(&mut self, window: &Window, output: Option<&Output>) {
2076 // The unmapping tile may have an xray background, in which case we will render xray
2077 // elements, so they need to be updated.
2078 self.niri.update_xray_render_elements(output);
2079
2080 self.backend.with_primary_renderer(|renderer| {
2081 if let Some(output) = output {
2082 let mut ctx = RenderCtx {
2083 target: RenderTarget::Output,
2084 renderer,
2085 xray: None,
2086 };
2087
2088 self.niri.fill_xray_elements(ctx.r(), output);
2089
2090 // If any background layer has block_out_from, also fill the Screencast xray
2091 // buffer so the unmap snapshot can render a buffer with blocked-out background.
2092 //
2093 // This will be used in Tile::render_snapshot().
2094 let has_blocked_out = self.niri.has_blocked_out_background_layers(output);
2095 if has_blocked_out {
2096 let screencast_ctx = RenderCtx {
2097 target: RenderTarget::Screencast,
2098 ..ctx.r()
2099 };
2100 self.niri.fill_xray_elements(screencast_ctx, output);
2101 }
2102
2103 let state = self.niri.output_state.get_mut(output).unwrap();
2104 self.niri.layout.store_unmap_snapshot(
2105 renderer,
2106 Some(&mut state.xray),
2107 has_blocked_out,
2108 window,
2109 );
2110
2111 self.niri.clear_xray_elements(output);
2112 } else {
2113 self.niri
2114 .layout
2115 .store_unmap_snapshot(renderer, None, false, window);
2116 }
2117 });
2118 }
2119
2120 #[cfg(not(feature = "xdp-gnome-screencast"))]
2121 pub fn set_dynamic_cast_target(&mut self, _target: CastTarget) {}
2122
2123 #[cfg(feature = "dbus")]
2124 pub fn on_screen_shot_msg(
2125 &mut self,
2126 to_screenshot: &async_channel::Sender<NiriToScreenshot>,
2127 msg: ScreenshotToNiri,
2128 ) {
2129 match msg {
2130 ScreenshotToNiri::TakeScreenshot { include_cursor } => {
2131 self.handle_take_screenshot(to_screenshot, include_cursor);
2132 }
2133 ScreenshotToNiri::PickColor(tx) => {
2134 self.handle_pick_color(tx);
2135 }
2136 }
2137 }
2138
2139 #[cfg(feature = "dbus")]
2140 fn handle_take_screenshot(
2141 &mut self,
2142 to_screenshot: &async_channel::Sender<NiriToScreenshot>,
2143 include_cursor: bool,
2144 ) {
2145 let _span = tracy_client::span!("TakeScreenshot");
2146
2147 let rv = self.backend.with_primary_renderer(|renderer| {
2148 let on_done = {
2149 let to_screenshot = to_screenshot.clone();
2150 move |path| {
2151 let msg = NiriToScreenshot::ScreenshotResult(Some(path));
2152 if let Err(err) = to_screenshot.send_blocking(msg) {
2153 warn!("error sending path to screenshot: {err:?}");
2154 }
2155 }
2156 };
2157
2158 let res = self
2159 .niri
2160 .screenshot_all_outputs(renderer, include_cursor, on_done);
2161
2162 if let Err(err) = res {
2163 warn!("error taking a screenshot: {err:?}");
2164
2165 let msg = NiriToScreenshot::ScreenshotResult(None);
2166 if let Err(err) = to_screenshot.send_blocking(msg) {
2167 warn!("error sending None to screenshot: {err:?}");
2168 }
2169 }
2170 });
2171
2172 if rv.is_none() {
2173 let msg = NiriToScreenshot::ScreenshotResult(None);
2174 if let Err(err) = to_screenshot.send_blocking(msg) {
2175 warn!("error sending None to screenshot: {err:?}");
2176 }
2177 }
2178 }
2179
2180 #[cfg(feature = "dbus")]
2181 pub fn on_introspect_msg(
2182 &mut self,
2183 to_introspect: &async_channel::Sender<NiriToIntrospect>,
2184 msg: IntrospectToNiri,
2185 ) {
2186 use crate::utils::with_toplevel_role;
2187
2188 let IntrospectToNiri::GetWindows = msg;
2189 let _span = tracy_client::span!("GetWindows");
2190
2191 let mut windows = HashMap::new();
2192
2193 #[cfg(feature = "xdp-gnome-screencast")]
2194 windows.insert(
2195 self.niri.casting.dynamic_cast_id_for_portal.get(),
2196 gnome_shell_introspect::WindowProperties {
2197 title: String::from("niri Dynamic Cast Target"),
2198 app_id: String::from("rs.bxt.niri.desktop"),
2199 },
2200 );
2201
2202 self.niri.layout.with_windows(|mapped, _, _, _| {
2203 let id = mapped.id().get();
2204 let props = with_toplevel_role(mapped.toplevel(), |role| {
2205 gnome_shell_introspect::WindowProperties {
2206 title: role.title.clone().unwrap_or_default(),
2207 app_id: role
2208 .app_id
2209 .as_ref()
2210 // We don't do proper .desktop file tracking (it's quite involved), and
2211 // Wayland windows can set any app id they want. However, this seems to
2212 // work well enough in practice.
2213 .map(|app_id| format!("{app_id}.desktop"))
2214 .unwrap_or_default(),
2215 }
2216 });
2217
2218 windows.insert(id, props);
2219 });
2220
2221 let msg = NiriToIntrospect::Windows(windows);
2222 if let Err(err) = to_introspect.send_blocking(msg) {
2223 warn!("error sending windows to introspect: {err:?}");
2224 }
2225 }
2226
2227 #[cfg(feature = "dbus")]
2228 pub fn on_login1_msg(&mut self, msg: Login1ToNiri) {
2229 let Login1ToNiri::LidClosedChanged(is_closed) = msg;
2230
2231 trace!("login1 lid {}", if is_closed { "closed" } else { "opened" });
2232 self.set_lid_closed(is_closed);
2233 }
2234
2235 #[cfg(feature = "dbus")]
2236 pub fn on_locale1_msg(&mut self, msg: Locale1ToNiri) {
2237 let Locale1ToNiri::XkbChanged(xkb) = msg;
2238
2239 trace!("locale1 xkb settings changed: {xkb:?}");
2240 let xkb = self.niri.xkb_from_locale1.insert(xkb);
2241
2242 {
2243 let config = self.niri.config.borrow();
2244 if config.input.keyboard.xkb != Xkb::default() {
2245 trace!("ignoring locale1 xkb change because niri config has xkb settings");
2246 return;
2247 }
2248 }
2249
2250 let xkb = xkb.clone();
2251 self.set_xkb_config(xkb.to_xkb_config());
2252 self.ipc_keyboard_layouts_changed();
2253 }
2254}
2255
2256impl Niri {
2257 pub fn new(
2258 config: Rc<RefCell<Config>>,
2259 event_loop: LoopHandle<'static, State>,
2260 stop_signal: LoopSignal,
2261 display: Display<State>,
2262 backend: &Backend,
2263 create_wayland_socket: bool,
2264 is_session_instance: bool,
2265 ) -> Self {
2266 let _span = tracy_client::span!("Niri::new");
2267
2268 let (executor, scheduler) = calloop::futures::executor().unwrap();
2269 event_loop.insert_source(executor, |_, _, _| ()).unwrap();
2270
2271 let display_handle = display.handle();
2272 let config_ = config.borrow();
2273 let config_file_output_config = config_.outputs.clone();
2274
2275 let mut animation_clock = Clock::default();
2276
2277 let rate = 1.0 / config_.animations.slowdown.max(0.001);
2278 animation_clock.set_rate(rate);
2279 animation_clock.set_complete_instantly(config_.animations.off);
2280
2281 let layout = Layout::new(animation_clock.clone(), &config_);
2282
2283 let (blocker_cleared_tx, blocker_cleared_rx) = mpsc::channel();
2284
2285 fn client_is_unrestricted(client: &Client) -> bool {
2286 !client.get_data::<ClientState>().unwrap().restricted
2287 }
2288
2289 let compositor_state = CompositorState::new_v6::<State>(&display_handle);
2290 let xdg_shell_state = XdgShellState::new_with_capabilities::<State>(
2291 &display_handle,
2292 [WmCapabilities::Fullscreen, WmCapabilities::Maximize],
2293 );
2294 let xdg_decoration_state =
2295 XdgDecorationState::new_with_filter::<State, _>(&display_handle, |client| {
2296 client
2297 .get_data::<ClientState>()
2298 .unwrap()
2299 .can_view_decoration_globals
2300 });
2301 let kde_decoration_state = KdeDecorationState::new_with_filter::<State, _>(
2302 &display_handle,
2303 // If we want CSD we will hide the global.
2304 KdeDecorationsMode::Server,
2305 |client| {
2306 client
2307 .get_data::<ClientState>()
2308 .unwrap()
2309 .can_view_decoration_globals
2310 },
2311 );
2312 let layer_shell_state = WlrLayerShellState::new_with_filter::<State, _>(
2313 &display_handle,
2314 client_is_unrestricted,
2315 );
2316 let session_lock_state =
2317 SessionLockManagerState::new::<State, _>(&display_handle, client_is_unrestricted);
2318 let shm_state = ShmState::new::<State>(
2319 &display_handle,
2320 vec![wl_shm::Format::Xbgr8888, wl_shm::Format::Abgr8888],
2321 );
2322 let output_manager_state =
2323 OutputManagerState::new_with_xdg_output::<State>(&display_handle);
2324 let dmabuf_state = DmabufState::new();
2325 let fractional_scale_manager_state =
2326 FractionalScaleManagerState::new::<State>(&display_handle);
2327 let mut seat_state = SeatState::new();
2328 let tablet_state = TabletManagerState::new::<State>(&display_handle);
2329 let pointer_gestures_state = PointerGesturesState::new::<State>(&display_handle);
2330 let relative_pointer_state = RelativePointerManagerState::new::<State>(&display_handle);
2331 let pointer_constraints_state = PointerConstraintsState::new::<State>(&display_handle);
2332 let idle_notifier_state = IdleNotifierState::new(&display_handle, event_loop.clone());
2333 let idle_inhibit_manager_state = IdleInhibitManagerState::new::<State>(&display_handle);
2334 let data_device_state = DataDeviceState::new::<State>(&display_handle);
2335 let primary_selection_state =
2336 PrimarySelectionState::new_with_filter::<State, _>(&display_handle, |client| {
2337 !client
2338 .get_data::<ClientState>()
2339 .unwrap()
2340 .primary_selection_disabled
2341 });
2342 let wlr_data_control_state = WlrDataControlState::new::<State, _>(
2343 &display_handle,
2344 Some(&primary_selection_state),
2345 client_is_unrestricted,
2346 );
2347 let ext_data_control_state = ExtDataControlState::new::<State, _>(
2348 &display_handle,
2349 Some(&primary_selection_state),
2350 client_is_unrestricted,
2351 );
2352 let presentation_state =
2353 PresentationState::new::<State>(&display_handle, Monotonic::ID as u32);
2354 let security_context_state =
2355 SecurityContextState::new::<State, _>(&display_handle, client_is_unrestricted);
2356
2357 let text_input_state = TextInputManagerState::new::<State>(&display_handle);
2358 let input_method_state =
2359 InputMethodManagerState::new::<State, _>(&display_handle, client_is_unrestricted);
2360 let keyboard_shortcuts_inhibit_state =
2361 KeyboardShortcutsInhibitState::new::<State>(&display_handle);
2362 let virtual_keyboard_state =
2363 VirtualKeyboardManagerState::new::<State, _>(&display_handle, client_is_unrestricted);
2364 let virtual_pointer_state =
2365 VirtualPointerManagerState::new::<State, _>(&display_handle, client_is_unrestricted);
2366 let foreign_toplevel_state =
2367 ForeignToplevelManagerState::new::<State, _>(&display_handle, client_is_unrestricted);
2368 let ext_workspace_state =
2369 ExtWorkspaceManagerState::new::<State, _>(&display_handle, client_is_unrestricted);
2370 let mut output_management_state =
2371 OutputManagementManagerState::new::<State, _>(&display_handle, client_is_unrestricted);
2372 output_management_state.on_config_changed(config_.outputs.clone());
2373 let screencopy_state =
2374 ScreencopyManagerState::new::<State, _>(&display_handle, client_is_unrestricted);
2375 let viewporter_state = ViewporterState::new::<State>(&display_handle);
2376 let background_effect_state = BackgroundEffectState::new::<State>(&display_handle);
2377 let xdg_foreign_state = XdgForeignState::new::<State>(&display_handle);
2378
2379 let is_tty = matches!(backend, Backend::Tty(_));
2380 let gamma_control_manager_state =
2381 GammaControlManagerState::new::<State, _>(&display_handle, move |client| {
2382 is_tty && !client.get_data::<ClientState>().unwrap().restricted
2383 });
2384 let activation_state = XdgActivationState::new::<State>(&display_handle);
2385 event_loop
2386 .insert_source(
2387 Timer::from_duration(XDG_ACTIVATION_TOKEN_TIMEOUT),
2388 |_, _, state| {
2389 state.niri.activation_state.retain_tokens(|_, token_data| {
2390 token_data.timestamp.elapsed() < XDG_ACTIVATION_TOKEN_TIMEOUT
2391 });
2392 TimeoutAction::ToDuration(XDG_ACTIVATION_TOKEN_TIMEOUT)
2393 },
2394 )
2395 .unwrap();
2396
2397 let mutter_x11_interop_state =
2398 MutterX11InteropManagerState::new::<State, _>(&display_handle, move |_| true);
2399
2400 #[cfg(test)]
2401 let single_pixel_buffer_state = SinglePixelBufferState::new::<State>(&display_handle);
2402
2403 let mut seat: Seat<State> = seat_state.new_wl_seat(&display_handle, backend.seat_name());
2404 let keyboard = match seat.add_keyboard(
2405 config_.input.keyboard.xkb.to_xkb_config(),
2406 config_.input.keyboard.repeat_delay.into(),
2407 config_.input.keyboard.repeat_rate.into(),
2408 ) {
2409 Err(err) => {
2410 if let smithay::input::keyboard::Error::BadKeymap = err {
2411 warn!("error loading the configured xkb keymap, trying default");
2412 } else {
2413 warn!("error adding keyboard: {err:?}");
2414 }
2415 seat.add_keyboard(
2416 Default::default(),
2417 config_.input.keyboard.repeat_delay.into(),
2418 config_.input.keyboard.repeat_rate.into(),
2419 )
2420 .unwrap()
2421 }
2422 Ok(keyboard) => keyboard,
2423 };
2424 if config_.input.keyboard.numlock {
2425 let mut modifier_state = keyboard.modifier_state();
2426 modifier_state.num_lock = true;
2427 keyboard.set_modifier_state(modifier_state);
2428 }
2429 seat.add_pointer();
2430
2431 let cursor_shape_manager_state = CursorShapeManagerState::new::<State>(&display_handle);
2432 let cursor_manager =
2433 CursorManager::new(&config_.cursor.xcursor_theme, config_.cursor.xcursor_size);
2434
2435 let mod_key = backend.mod_key(&config.borrow());
2436 let mods_with_mouse_binds = mods_with_mouse_binds(mod_key, &config_.binds);
2437 let mods_with_wheel_binds = mods_with_wheel_binds(mod_key, &config_.binds);
2438 let mods_with_finger_scroll_binds = mods_with_finger_scroll_binds(mod_key, &config_.binds);
2439 let mods_with_tablet_stylus_binds = mods_with_tablet_stylus_binds(mod_key, &config_.binds);
2440
2441 let screenshot_ui = ScreenshotUi::new(animation_clock.clone(), config.clone());
2442 let window_mru_ui = WindowMruUi::new(config.clone());
2443 let config_error_notification =
2444 ConfigErrorNotification::new(animation_clock.clone(), config.clone());
2445
2446 let mut hotkey_overlay = HotkeyOverlay::new(config.clone(), mod_key);
2447 if !config_.hotkey_overlay.skip_at_startup {
2448 hotkey_overlay.show();
2449 }
2450
2451 let exit_confirm_dialog = ExitConfirmDialog::new(animation_clock.clone(), config.clone());
2452
2453 #[cfg(feature = "dbus")]
2454 let a11y = A11y::new(event_loop.clone());
2455
2456 event_loop
2457 .insert_source(
2458 Timer::from_duration(Duration::from_secs(1)),
2459 |_, _, state| {
2460 state.niri.send_frame_callbacks_on_fallback_timer();
2461 TimeoutAction::ToDuration(Duration::from_secs(1))
2462 },
2463 )
2464 .unwrap();
2465
2466 let socket_name = create_wayland_socket.then(|| {
2467 let socket_source = ListeningSocketSource::new_auto().unwrap();
2468 let socket_name = socket_source.socket_name().to_os_string();
2469 event_loop
2470 .insert_source(socket_source, move |client, _, state| {
2471 state.niri.insert_client(NewClient {
2472 client,
2473 restricted: false,
2474 credentials_unknown: false,
2475 });
2476 })
2477 .unwrap();
2478 socket_name
2479 });
2480
2481 let ipc_server = match IpcServer::start(&event_loop, socket_name.as_deref()) {
2482 Ok(server) => Some(server),
2483 Err(err) => {
2484 warn!("error starting IPC server: {err:?}");
2485 None
2486 }
2487 };
2488
2489 #[cfg(feature = "xdp-gnome-screencast")]
2490 let screencasting = Screencasting::new(&event_loop);
2491
2492 let display_source = Generic::new(display, Interest::READ, Mode::Level);
2493 event_loop
2494 .insert_source(display_source, |_, display, state| {
2495 // SAFETY: we don't drop the display.
2496 unsafe {
2497 display.get_mut().dispatch_clients(state).unwrap();
2498 }
2499 Ok(PostAction::Continue)
2500 })
2501 .unwrap();
2502
2503 event_loop
2504 .insert_source(
2505 Timer::from_duration(Duration::from_secs(60)),
2506 |_, _, state| {
2507 let _span = tracy_client::span!("startup timeout");
2508 state.niri.is_at_startup = false;
2509 state.niri.recompute_window_rules();
2510 state.niri.recompute_layer_rules();
2511 TimeoutAction::Drop
2512 },
2513 )
2514 .unwrap();
2515
2516 drop(config_);
2517 let mut niri = Self {
2518 config,
2519 config_file_output_config,
2520 config_file_watcher: None,
2521
2522 event_loop,
2523 scheduler,
2524 stop_signal,
2525 socket_name,
2526 display_handle,
2527 is_session_instance,
2528 start_time: Instant::now(),
2529 is_at_startup: true,
2530 clock: animation_clock,
2531
2532 layout,
2533 global_space: Space::default(),
2534 sorted_outputs: Vec::default(),
2535 output_state: HashMap::new(),
2536 unmapped_windows: HashMap::new(),
2537 unmapped_layer_surfaces: HashSet::new(),
2538 mapped_layer_surfaces: HashMap::new(),
2539 root_surface: HashMap::new(),
2540 dmabuf_pre_commit_hook: HashMap::new(),
2541 blocker_cleared_tx,
2542 blocker_cleared_rx,
2543 monitors_active: true,
2544 is_lid_closed: false,
2545
2546 devices: HashSet::new(),
2547 tablets: HashMap::new(),
2548 touch: HashSet::new(),
2549
2550 compositor_state,
2551 xdg_shell_state,
2552 xdg_decoration_state,
2553 kde_decoration_state,
2554 layer_shell_state,
2555 session_lock_state,
2556 foreign_toplevel_state,
2557 ext_workspace_state,
2558 output_management_state,
2559 screencopy_state,
2560 viewporter_state,
2561 background_effect_state,
2562 xdg_foreign_state,
2563 text_input_state,
2564 input_method_state,
2565 keyboard_shortcuts_inhibit_state,
2566 virtual_keyboard_state,
2567 virtual_pointer_state,
2568 shm_state,
2569 output_manager_state,
2570 dmabuf_state,
2571 fractional_scale_manager_state,
2572 seat_state,
2573 tablet_state,
2574 pointer_gestures_state,
2575 relative_pointer_state,
2576 pointer_constraints_state,
2577 idle_notifier_state,
2578 idle_inhibit_manager_state,
2579 data_device_state,
2580 primary_selection_state,
2581 wlr_data_control_state,
2582 ext_data_control_state,
2583 popups: PopupManager::default(),
2584 popup_grab: None,
2585 suppressed_keys: HashSet::new(),
2586 suppressed_buttons: HashSet::new(),
2587 bind_cooldown_timers: HashMap::new(),
2588 bind_repeat_timer: Option::default(),
2589 presentation_state,
2590 security_context_state,
2591 gamma_control_manager_state,
2592 activation_state,
2593 mutter_x11_interop_state,
2594 #[cfg(test)]
2595 single_pixel_buffer_state,
2596
2597 seat,
2598 keyboard_focus: KeyboardFocus::Layout { surface: None },
2599 layer_shell_on_demand_focus: None,
2600 idle_inhibiting_surfaces: HashSet::new(),
2601 is_fdo_idle_inhibited: Arc::new(AtomicBool::new(false)),
2602 keyboard_shortcuts_inhibiting_surfaces: HashMap::new(),
2603 xkb_from_locale1: None,
2604 cursor_manager,
2605 cursor_texture_cache: Default::default(),
2606 cursor_shape_manager_state,
2607 dnd_icon: None,
2608 pointer_contents: PointContents::default(),
2609 pointer_visibility: PointerVisibility::Visible,
2610 pointer_inactivity_timer: None,
2611 pointer_inactivity_timer_got_reset: false,
2612 notified_activity_this_iteration: false,
2613 pointer_inside_hot_corner: false,
2614 pointer_constraint_position_hint: None,
2615 tablet_cursor_location: None,
2616 gesture_swipe_3f_cumulative: None,
2617 overview_scroll_swipe_gesture: ScrollSwipeGesture::new(),
2618 vertical_wheel_tracker: ScrollTracker::new(120),
2619 horizontal_wheel_tracker: ScrollTracker::new(120),
2620 mods_with_mouse_binds,
2621 mods_with_wheel_binds,
2622 mods_with_tablet_stylus_binds,
2623
2624 // 10 is copied from Clutter: DISCRETE_SCROLL_STEP.
2625 vertical_finger_scroll_tracker: ScrollTracker::new(10),
2626 horizontal_finger_scroll_tracker: ScrollTracker::new(10),
2627 mods_with_finger_scroll_binds,
2628
2629 lock_state: LockState::Unlocked,
2630 locked_hint: None,
2631
2632 screenshot_ui,
2633 config_error_notification,
2634 hotkey_overlay,
2635 exit_confirm_dialog,
2636
2637 window_mru_ui,
2638 pending_mru_commit: None,
2639
2640 pick_window: None,
2641 pick_color: None,
2642
2643 debug_draw_opaque_regions: false,
2644 debug_draw_damage: false,
2645
2646 #[cfg(feature = "dbus")]
2647 dbus: None,
2648 #[cfg(feature = "dbus")]
2649 a11y_manager: None,
2650 #[cfg(feature = "dbus")]
2651 a11y,
2652 #[cfg(feature = "dbus")]
2653 inhibit_power_key_fd: None,
2654
2655 ipc_server,
2656 ipc_outputs_changed: false,
2657
2658 satellite: None,
2659
2660 #[cfg(feature = "xdp-gnome-screencast")]
2661 casting: screencasting,
2662 };
2663
2664 niri.reset_pointer_inactivity_timer();
2665
2666 niri
2667 }
2668
2669 pub fn insert_client(&mut self, client: NewClient) {
2670 let NewClient {
2671 client,
2672 restricted,
2673 credentials_unknown,
2674 } = client;
2675
2676 let config = self.config.borrow();
2677 let data = Arc::new(ClientState {
2678 compositor_state: Default::default(),
2679 can_view_decoration_globals: config.prefer_no_csd,
2680 primary_selection_disabled: config.clipboard.disable_primary,
2681 restricted,
2682 credentials_unknown,
2683 });
2684
2685 if let Err(err) = self.display_handle.insert_client(client, data) {
2686 warn!("error inserting client: {err}");
2687 }
2688 }
2689
2690 #[cfg(feature = "dbus")]
2691 pub fn inhibit_power_key(&mut self) -> anyhow::Result<()> {
2692 use smithay::reexports::rustix::io::{fcntl_setfd, FdFlags};
2693
2694 let conn = zbus::blocking::Connection::system()?;
2695
2696 let message = conn.call_method(
2697 Some("org.freedesktop.login1"),
2698 "/org/freedesktop/login1",
2699 Some("org.freedesktop.login1.Manager"),
2700 "Inhibit",
2701 &("handle-power-key", "niri", "Power key handling", "block"),
2702 )?;
2703
2704 let fd: zbus::zvariant::OwnedFd = message.body().deserialize()?;
2705
2706 // Don't leak the fd to child processes.
2707 if let Err(err) = fcntl_setfd(&fd, FdFlags::CLOEXEC) {
2708 warn!("error setting CLOEXEC on inhibit fd: {err:?}");
2709 };
2710
2711 self.inhibit_power_key_fd = Some(fd);
2712
2713 Ok(())
2714 }
2715
2716 /// Repositions all outputs, optionally adding a new output.
2717 pub fn reposition_outputs(&mut self, new_output: Option<&Output>) {
2718 let _span = tracy_client::span!("Niri::reposition_outputs");
2719
2720 #[derive(Debug)]
2721 struct Data {
2722 output: Output,
2723 name: OutputName,
2724 position: Option<Point<i32, Logical>>,
2725 config: Option<niri_config::Position>,
2726 }
2727
2728 let config = self.config.borrow();
2729 let mut outputs = vec![];
2730 for output in self.global_space.outputs().chain(new_output) {
2731 let name = output.user_data().get::<OutputName>().unwrap();
2732 let position = self.global_space.output_geometry(output).map(|geo| geo.loc);
2733 let config = config.outputs.find(name).and_then(|c| c.position);
2734
2735 outputs.push(Data {
2736 output: output.clone(),
2737 name: name.clone(),
2738 position,
2739 config,
2740 });
2741 }
2742 drop(config);
2743
2744 for Data { output, .. } in &outputs {
2745 self.global_space.unmap_output(output);
2746 }
2747
2748 // Connectors can appear in udev in any order. If we sort by name then we get output
2749 // positioning that does not depend on the order they appeared.
2750 //
2751 // This sorting first compares by make/model/serial so that it is stable regardless of the
2752 // connector name. However, if make/model/serial is equal or unknown, then it does fall
2753 // back to comparing the connector name, which should always be unique.
2754 outputs.sort_unstable_by(|a, b| a.name.compare(&b.name));
2755
2756 // Place all outputs with explicitly configured position first, then the unconfigured ones.
2757 outputs.sort_by_key(|d| d.config.is_none());
2758
2759 trace!(
2760 "placing outputs in order: {:?}",
2761 outputs.iter().map(|d| &d.name.connector)
2762 );
2763
2764 self.sorted_outputs = outputs
2765 .iter()
2766 .map(|Data { output, .. }| output.clone())
2767 .collect();
2768
2769 for data in outputs.into_iter() {
2770 let Data {
2771 output,
2772 name,
2773 position,
2774 config,
2775 } = data;
2776
2777 let size = output_size(&output).to_i32_round();
2778
2779 let new_position = config
2780 .map(|pos| Point::from((pos.x, pos.y)))
2781 .filter(|pos| {
2782 // Ensure that the requested position does not overlap any existing output.
2783 let target_geom = Rectangle::new(*pos, size);
2784
2785 let overlap = self
2786 .global_space
2787 .outputs()
2788 .map(|output| self.global_space.output_geometry(output).unwrap())
2789 .find(|geom| geom.overlaps(target_geom));
2790
2791 if let Some(overlap) = overlap {
2792 warn!(
2793 "output {} at x={} y={} sized {}x{} \
2794 overlaps an existing output at x={} y={} sized {}x{}, \
2795 falling back to automatic placement",
2796 name.connector,
2797 pos.x,
2798 pos.y,
2799 size.w,
2800 size.h,
2801 overlap.loc.x,
2802 overlap.loc.y,
2803 overlap.size.w,
2804 overlap.size.h,
2805 );
2806
2807 false
2808 } else {
2809 true
2810 }
2811 })
2812 .unwrap_or_else(|| {
2813 let x = self
2814 .global_space
2815 .outputs()
2816 .map(|output| self.global_space.output_geometry(output).unwrap())
2817 .map(|geom| geom.loc.x + geom.size.w)
2818 .max()
2819 .unwrap_or(0);
2820
2821 Point::from((x, 0))
2822 });
2823
2824 self.global_space.map_output(&output, new_position);
2825
2826 // By passing new_output as an Option, rather than mapping it into a bogus location
2827 // in global_space, we ensure that this branch always runs for it.
2828 if Some(new_position) != position {
2829 debug!(
2830 "putting output {} at x={} y={}",
2831 name.connector, new_position.x, new_position.y
2832 );
2833 output.change_current_state(None, None, None, Some(new_position));
2834 self.ipc_outputs_changed = true;
2835 self.queue_redraw(&output);
2836 }
2837 }
2838 }
2839
2840 pub fn add_output(&mut self, output: Output, refresh_interval: Option<Duration>, vrr: bool) {
2841 let global = output.create_global::<State>(&self.display_handle);
2842
2843 let name = output.user_data().get::<OutputName>().unwrap();
2844
2845 let config = self.config.borrow();
2846 let c = config.outputs.find(name);
2847 let scale = c.and_then(|c| c.scale).map(|s| s.0).unwrap_or_else(|| {
2848 let size_mm = output.physical_properties().size;
2849 let resolution = output.current_mode().unwrap().size;
2850 guess_monitor_scale(size_mm, resolution)
2851 });
2852 let scale = closest_representable_scale(scale.clamp(0.1, 10.));
2853
2854 let mut transform = panel_orientation(&output)
2855 + c.map(|c| ipc_transform_to_smithay(c.transform))
2856 .unwrap_or(Transform::Normal);
2857
2858 let mut backdrop_color = c
2859 .and_then(|c| c.backdrop_color)
2860 .unwrap_or(config.overview.backdrop_color)
2861 .to_array_unpremul();
2862 backdrop_color[3] = 1.;
2863
2864 // FIXME: fix winit damage on other transforms.
2865 if name.connector == "winit" {
2866 transform = Transform::Flipped180;
2867 }
2868
2869 let mut layout_config = c.and_then(|c| c.layout.clone());
2870 // Support the deprecated non-layout background-color key.
2871 if let Some(layout) = &mut layout_config {
2872 if layout.background_color.is_none() {
2873 layout.background_color = c.and_then(|c| c.background_color);
2874 }
2875 }
2876 drop(config);
2877
2878 // Set scale and transform before adding to the layout since that will read the output size.
2879 output.change_current_state(
2880 None,
2881 Some(transform),
2882 Some(output::Scale::Fractional(scale)),
2883 None,
2884 );
2885
2886 self.layout.add_output(output.clone(), layout_config);
2887
2888 let lock_render_state = if self.is_locked() {
2889 // We haven't rendered anything yet so it's as good as locked.
2890 LockRenderState::Locked
2891 } else {
2892 LockRenderState::Unlocked
2893 };
2894
2895 let size = output_size(&output);
2896 let state = OutputState {
2897 global,
2898 redraw_state: RedrawState::Idle,
2899 on_demand_vrr_enabled: false,
2900 unfinished_animations_remain: false,
2901 frame_clock: FrameClock::new(refresh_interval, vrr),
2902 last_drm_sequence: None,
2903 vblank_throttle: VBlankThrottle::new(self.event_loop.clone(), name.connector.clone()),
2904 frame_callback_sequence: 0,
2905 backdrop_buffer: SolidColorBuffer::new(size, backdrop_color),
2906 xray: Xray::new(),
2907 lock_render_state,
2908 lock_surface: None,
2909 lock_color_buffer: SolidColorBuffer::new(size, CLEAR_COLOR_LOCKED),
2910 screen_transition: None,
2911 debug_damage_tracker: OutputDamageTracker::from_output(&output),
2912 };
2913 let rv = self.output_state.insert(output.clone(), state);
2914 assert!(rv.is_none(), "output was already tracked");
2915
2916 // Must be last since it will call queue_redraw(output) which needs things to be filled-in.
2917 self.reposition_outputs(Some(&output));
2918 }
2919
2920 pub fn output_exists(&self, output: &Output) -> bool {
2921 self.output_state.contains_key(output)
2922 }
2923
2924 /// Converts a `WlOutput` to a corresponding `Output` if it exists.
2925 ///
2926 /// Compared to raw `Output::from_resource`, this method also verifies that the output still
2927 /// exists in niri. Right after the output global is disabled, but before it is removed for
2928 /// good, `Output::from_resource` will succeed, but since niri already forgot the output,
2929 /// accessing it can cause logic bugs.
2930 pub fn output_from_resource(&self, wl_output: &WlOutput) -> Option<Output> {
2931 Output::from_resource(wl_output).filter(|output| self.output_exists(output))
2932 }
2933
2934 pub fn remove_output(&mut self, output: &Output) {
2935 for layer in layer_map_for_output(output).layers() {
2936 layer.layer_surface().send_close();
2937 }
2938
2939 self.layout.remove_output(output);
2940 self.global_space.unmap_output(output);
2941 self.reposition_outputs(None);
2942 self.gamma_control_manager_state.output_removed(output);
2943
2944 let state = self.output_state.remove(output).unwrap();
2945
2946 match state.redraw_state {
2947 RedrawState::Idle => (),
2948 RedrawState::Queued => (),
2949 RedrawState::WaitingForVBlank { .. } => (),
2950 RedrawState::WaitingForEstimatedVBlank(token) => self.event_loop.remove(token),
2951 RedrawState::WaitingForEstimatedVBlankAndQueued(token) => self.event_loop.remove(token),
2952 }
2953
2954 self.stop_casts_for_target(CastTarget::output(output));
2955 self.screencopy_state.remove_output(output);
2956
2957 // Disable the output global and remove some time later to give the clients some time to
2958 // process it.
2959 let global = state.global;
2960 self.display_handle.disable_global::<State>(global.clone());
2961 self.event_loop
2962 .insert_source(
2963 Timer::from_duration(Duration::from_secs(10)),
2964 move |_, _, state| {
2965 state
2966 .niri
2967 .display_handle
2968 .remove_global::<State>(global.clone());
2969 TimeoutAction::Drop
2970 },
2971 )
2972 .unwrap();
2973
2974 match mem::take(&mut self.lock_state) {
2975 LockState::Locking(confirmation) => {
2976 // We're locking and an output was removed, check if the requirements are now met.
2977 let all_locked = self
2978 .output_state
2979 .values()
2980 .all(|state| state.lock_render_state == LockRenderState::Locked);
2981
2982 if all_locked {
2983 let lock = confirmation.ext_session_lock().clone();
2984 confirmation.lock();
2985 self.lock_state = LockState::Locked(lock);
2986 } else {
2987 // Still waiting.
2988 self.lock_state = LockState::Locking(confirmation);
2989 }
2990 }
2991 lock_state => {
2992 self.lock_state = lock_state;
2993 self.maybe_continue_to_locking();
2994 }
2995 }
2996
2997 if self.screenshot_ui.close() {
2998 self.cursor_manager
2999 .set_cursor_image(CursorImageStatus::default_named());
3000 self.queue_redraw_all();
3001 }
3002
3003 if self.window_mru_ui.output() == Some(output) {
3004 self.cancel_mru();
3005 }
3006 }
3007
3008 pub fn output_resized(&mut self, output: &Output) {
3009 let output_size = output_size(output);
3010 let scale = output.current_scale();
3011 let transform = output.current_transform();
3012
3013 {
3014 let mut layer_map = layer_map_for_output(output);
3015 for layer in layer_map.layers() {
3016 layer.with_surfaces(|surface, data| {
3017 send_scale_transform(surface, data, scale, transform);
3018 });
3019
3020 if let Some(mapped) = self.mapped_layer_surfaces.get_mut(layer) {
3021 mapped.update_sizes(output_size, scale.fractional_scale());
3022 }
3023 }
3024 layer_map.arrange();
3025 }
3026
3027 self.layout.update_output_size(output);
3028
3029 if let Some(state) = self.output_state.get_mut(output) {
3030 state.backdrop_buffer.resize(output_size);
3031
3032 state.lock_color_buffer.resize(output_size);
3033 if let Some(lock_surface) = &state.lock_surface {
3034 configure_lock_surface(lock_surface, output);
3035 }
3036 }
3037
3038 // If the output size changed with an open screenshot UI, close the screenshot UI.
3039 if let Some((old_size, old_scale, old_transform)) = self.screenshot_ui.output_size(output) {
3040 let output_mode = output.current_mode().unwrap();
3041 let size = transform.transform_size(output_mode.size);
3042 let scale = output.current_scale().fractional_scale();
3043 // FIXME: scale changes and transform flips shouldn't matter but they currently do since
3044 // I haven't quite figured out how to draw the screenshot textures in
3045 // physical coordinates.
3046 if old_size != size || old_scale != scale || old_transform != transform {
3047 self.screenshot_ui.close();
3048 self.cursor_manager
3049 .set_cursor_image(CursorImageStatus::default_named());
3050 self.queue_redraw_all();
3051 return;
3052 }
3053 }
3054
3055 self.queue_redraw(output);
3056 }
3057
3058 pub fn deactivate_monitors(&mut self, backend: &mut Backend) {
3059 if !self.monitors_active {
3060 return;
3061 }
3062
3063 self.monitors_active = false;
3064 backend.set_monitors_active(false);
3065 }
3066
3067 pub fn activate_monitors(&mut self, backend: &mut Backend) {
3068 if self.monitors_active {
3069 return;
3070 }
3071
3072 self.monitors_active = true;
3073 backend.set_monitors_active(true);
3074
3075 self.queue_redraw_all();
3076 }
3077
3078 pub fn output_under(&self, pos: Point<f64, Logical>) -> Option<(&Output, Point<f64, Logical>)> {
3079 let output = self.global_space.output_under(pos).next()?;
3080 let pos_within_output = pos
3081 - self
3082 .global_space
3083 .output_geometry(output)
3084 .unwrap()
3085 .loc
3086 .to_f64();
3087
3088 Some((output, pos_within_output))
3089 }
3090
3091 fn is_inside_hot_corner(&self, output: &Output, pos: Point<f64, Logical>) -> bool {
3092 let config = self.config.borrow();
3093 let hot_corners = output
3094 .user_data()
3095 .get::<OutputName>()
3096 .and_then(|name| config.outputs.find(name))
3097 .and_then(|c| c.hot_corners)
3098 .unwrap_or(config.gestures.hot_corners);
3099
3100 if hot_corners.off {
3101 return false;
3102 }
3103
3104 // Use size from the ceiled output geometry, since that's what we currently use for pointer
3105 // motion clamping.
3106 let geom = self.global_space.output_geometry(output).unwrap();
3107 let size = geom.size.to_f64();
3108
3109 let contains = move |corner: Point<f64, Logical>| {
3110 Rectangle::new(corner, Size::new(1., 1.)).contains(pos)
3111 };
3112
3113 if hot_corners.top_right && contains(Point::new(size.w - 1., 0.)) {
3114 return true;
3115 }
3116 if hot_corners.bottom_left && contains(Point::new(0., size.h - 1.)) {
3117 return true;
3118 }
3119 if hot_corners.bottom_right && contains(Point::new(size.w - 1., size.h - 1.)) {
3120 return true;
3121 }
3122
3123 // If the user didn't explicitly set any corners, we default to top-left.
3124 if (hot_corners.top_left
3125 || !(hot_corners.top_right || hot_corners.bottom_right || hot_corners.bottom_left))
3126 && contains(Point::new(0., 0.))
3127 {
3128 return true;
3129 }
3130
3131 false
3132 }
3133
3134 pub fn is_sticky_obscured_under(
3135 &self,
3136 output: &Output,
3137 pos_within_output: Point<f64, Logical>,
3138 ) -> bool {
3139 // The ordering here must be consistent with the ordering in render() so that input is
3140 // consistent with the visuals.
3141
3142 // Check if some layer-shell surface is on top.
3143 let layers = layer_map_for_output(output);
3144 let layer_surface_under = |layer, popup| {
3145 layers
3146 .layers_on(layer)
3147 .rev()
3148 .find_map(|layer| {
3149 let mapped = self.mapped_layer_surfaces.get(layer)?;
3150
3151 let mut layer_pos_within_output =
3152 layers.layer_geometry(layer).unwrap().loc.to_f64();
3153 layer_pos_within_output += mapped.bob_offset();
3154
3155 let surface_type = if popup {
3156 WindowSurfaceType::POPUP
3157 } else {
3158 WindowSurfaceType::TOPLEVEL
3159 } | WindowSurfaceType::SUBSURFACE;
3160 layer.surface_under(pos_within_output - layer_pos_within_output, surface_type)
3161 })
3162 .is_some()
3163 };
3164
3165 let layer_toplevel_under = |layer| layer_surface_under(layer, false);
3166 let layer_popup_under = |layer| layer_surface_under(layer, true);
3167
3168 if layer_popup_under(Layer::Overlay) || layer_toplevel_under(Layer::Overlay) {
3169 return true;
3170 }
3171
3172 let mon = self.layout.monitor_for_output(output).unwrap();
3173 if mon.render_above_top_layer() {
3174 return false;
3175 }
3176
3177 if self.is_inside_hot_corner(output, pos_within_output) {
3178 return true;
3179 }
3180
3181 if layer_popup_under(Layer::Top) || layer_toplevel_under(Layer::Top) {
3182 return true;
3183 }
3184
3185 false
3186 }
3187
3188 pub fn is_layout_obscured_under(
3189 &self,
3190 output: &Output,
3191 pos_within_output: Point<f64, Logical>,
3192 ) -> bool {
3193 if self.layout.is_overview_open() {
3194 return false;
3195 }
3196
3197 // Check if some layer-shell surface is on top.
3198 let layers = layer_map_for_output(output);
3199 let layer_popup_under = |layer| {
3200 layers
3201 .layers_on(layer)
3202 .rev()
3203 .find_map(|layer_surface| {
3204 let mapped = self.mapped_layer_surfaces.get(layer_surface)?;
3205 if mapped.place_within_backdrop() {
3206 return None;
3207 }
3208
3209 let mut layer_pos_within_output =
3210 layers.layer_geometry(layer_surface).unwrap().loc.to_f64();
3211 layer_pos_within_output += mapped.bob_offset();
3212
3213 // Background and bottom layers move together with the workspaces.
3214 let mon = self.layout.monitor_for_output(output)?;
3215 let (_, geo) = mon.workspace_under(pos_within_output)?;
3216 layer_pos_within_output += geo.loc;
3217
3218 let surface_type = WindowSurfaceType::POPUP | WindowSurfaceType::SUBSURFACE;
3219 layer_surface
3220 .surface_under(pos_within_output - layer_pos_within_output, surface_type)
3221 })
3222 .is_some()
3223 };
3224
3225 if layer_popup_under(Layer::Bottom) || layer_popup_under(Layer::Background) {
3226 return true;
3227 }
3228
3229 false
3230 }
3231
3232 /// Returns the workspace under the position to be activated.
3233 ///
3234 /// The return value is an output and a workspace index on it.
3235 pub fn workspace_under(
3236 &self,
3237 extended_bounds: bool,
3238 pos: Point<f64, Logical>,
3239 ) -> Option<(Output, &Workspace<Mapped>)> {
3240 if self.exit_confirm_dialog.is_open() || self.is_locked() || self.screenshot_ui.is_open() {
3241 return None;
3242 }
3243
3244 let (output, pos_within_output) = self.output_under(pos)?;
3245
3246 if self.is_sticky_obscured_under(output, pos_within_output) {
3247 return None;
3248 }
3249
3250 if self.is_layout_obscured_under(output, pos_within_output) {
3251 return None;
3252 }
3253
3254 let ws = self
3255 .layout
3256 .workspace_under(extended_bounds, output, pos_within_output)?;
3257 Some((output.clone(), ws))
3258 }
3259
3260 pub fn workspace_under_cursor(
3261 &self,
3262 extended_bounds: bool,
3263 ) -> Option<(Output, &Workspace<Mapped>)> {
3264 let pos = self.seat.get_pointer().unwrap().current_location();
3265 self.workspace_under(extended_bounds, pos)
3266 }
3267
3268 /// Returns the window under the position to be activated.
3269 ///
3270 /// The cursor may be inside the window's activation region, but not within the window's input
3271 /// region.
3272 pub fn window_under(&self, pos: Point<f64, Logical>) -> Option<&Mapped> {
3273 if self.exit_confirm_dialog.is_open()
3274 || self.is_locked()
3275 || self.screenshot_ui.is_open()
3276 || self.window_mru_ui.is_open()
3277 {
3278 return None;
3279 }
3280
3281 let (output, pos_within_output) = self.output_under(pos)?;
3282
3283 if self.is_sticky_obscured_under(output, pos_within_output) {
3284 return None;
3285 }
3286
3287 if let Some((window, _loc)) = self
3288 .layout
3289 .interactive_moved_window_under(output, pos_within_output)
3290 {
3291 return Some(window);
3292 }
3293
3294 if self.is_layout_obscured_under(output, pos_within_output) {
3295 return None;
3296 }
3297
3298 let (window, _loc) = self.layout.window_under(output, pos_within_output)?;
3299 Some(window)
3300 }
3301
3302 /// Returns the window under the cursor to be activated.
3303 ///
3304 /// The cursor may be inside the window's activation region, but not within the window's input
3305 /// region.
3306 pub fn window_under_cursor(&self) -> Option<&Mapped> {
3307 let pos = self.seat.get_pointer().unwrap().current_location();
3308 self.window_under(pos)
3309 }
3310
3311 /// Returns contents under the given point.
3312 ///
3313 /// We don't have a proper global space for all windows, so this function converts window
3314 /// locations to global space according to where they are rendered.
3315 ///
3316 /// This function does not take pointer or touch grabs into account.
3317 pub fn contents_under(&self, pos: Point<f64, Logical>) -> PointContents {
3318 let mut rv = PointContents::default();
3319
3320 let Some((output, pos_within_output)) = self.output_under(pos) else {
3321 return rv;
3322 };
3323 rv.output = Some(output.clone());
3324 let output_pos_in_global_space = self.global_space.output_geometry(output).unwrap().loc;
3325
3326 // The ordering here must be consistent with the ordering in render() so that input is
3327 // consistent with the visuals.
3328
3329 if self.exit_confirm_dialog.is_open() {
3330 return rv;
3331 } else if self.is_locked() {
3332 let Some(state) = self.output_state.get(output) else {
3333 return rv;
3334 };
3335 let Some(surface) = state.lock_surface.as_ref() else {
3336 return rv;
3337 };
3338
3339 rv.surface = under_from_surface_tree(
3340 surface.wl_surface(),
3341 pos_within_output,
3342 // We put lock surfaces at (0, 0).
3343 (0, 0),
3344 WindowSurfaceType::ALL,
3345 )
3346 .map(|(surface, pos_within_output)| {
3347 (
3348 surface,
3349 (pos_within_output + output_pos_in_global_space).to_f64(),
3350 )
3351 });
3352
3353 return rv;
3354 }
3355
3356 if self.screenshot_ui.is_open() || self.window_mru_ui.is_open() {
3357 return rv;
3358 }
3359
3360 let layers = layer_map_for_output(output);
3361 let layer_surface_under = |layer, popup| {
3362 layers
3363 .layers_on(layer)
3364 .rev()
3365 .find_map(|layer_surface| {
3366 let mapped = self.mapped_layer_surfaces.get(layer_surface)?;
3367 if mapped.place_within_backdrop() {
3368 return None;
3369 }
3370
3371 let mut layer_pos_within_output =
3372 layers.layer_geometry(layer_surface).unwrap().loc.to_f64();
3373 layer_pos_within_output += mapped.bob_offset();
3374
3375 // Background and bottom layers move together with the workspaces.
3376 if matches!(layer, Layer::Background | Layer::Bottom) {
3377 let mon = self.layout.monitor_for_output(output)?;
3378 let (_, geo) = mon.workspace_under(pos_within_output)?;
3379 layer_pos_within_output += geo.loc;
3380 // Don't need to deal with zoom here because in the overview background and
3381 // bottom layers don't receive input.
3382 }
3383
3384 let surface_type = if popup {
3385 WindowSurfaceType::POPUP
3386 } else {
3387 WindowSurfaceType::TOPLEVEL
3388 } | WindowSurfaceType::SUBSURFACE;
3389
3390 layer_surface
3391 .surface_under(pos_within_output - layer_pos_within_output, surface_type)
3392 .map(|(surface, pos_within_layer)| {
3393 (
3394 (surface, pos_within_layer.to_f64() + layer_pos_within_output),
3395 layer_surface,
3396 )
3397 })
3398 })
3399 .map(|(s, l)| (Some(s), (None, Some(l.clone()))))
3400 };
3401
3402 let layer_toplevel_under = |layer| layer_surface_under(layer, false);
3403 let layer_popup_under = |layer| layer_surface_under(layer, true);
3404
3405 let mapped_hit_data = |(mapped, hit): (&Mapped, HitType)| {
3406 let window = &mapped.window;
3407 let surface_and_pos = if let HitType::Input { win_pos } = hit {
3408 let win_pos_within_output = win_pos;
3409 window
3410 .surface_under(
3411 pos_within_output - win_pos_within_output,
3412 WindowSurfaceType::ALL,
3413 )
3414 .map(|(s, pos_within_window)| {
3415 (s, pos_within_window.to_f64() + win_pos_within_output)
3416 })
3417 } else {
3418 None
3419 };
3420 (surface_and_pos, (Some((window.clone(), hit)), None))
3421 };
3422
3423 let interactive_moved_window_under = || {
3424 self.layout
3425 .interactive_moved_window_under(output, pos_within_output)
3426 .map(mapped_hit_data)
3427 };
3428 let window_under = || {
3429 self.layout
3430 .window_under(output, pos_within_output)
3431 .map(mapped_hit_data)
3432 };
3433
3434 let mon = self.layout.monitor_for_output(output).unwrap();
3435
3436 let mut under =
3437 layer_popup_under(Layer::Overlay).or_else(|| layer_toplevel_under(Layer::Overlay));
3438
3439 let is_overview_open = self.layout.is_overview_open();
3440
3441 // When rendering above the top layer, we put the regular monitor elements first.
3442 // Otherwise, we will render all layer-shell pop-ups and the top layer on top.
3443 if mon.render_above_top_layer() {
3444 under = under
3445 .or_else(interactive_moved_window_under)
3446 .or_else(window_under)
3447 .or_else(|| layer_popup_under(Layer::Top))
3448 .or_else(|| layer_toplevel_under(Layer::Top))
3449 .or_else(|| layer_popup_under(Layer::Bottom))
3450 .or_else(|| layer_popup_under(Layer::Background))
3451 .or_else(|| layer_toplevel_under(Layer::Bottom))
3452 .or_else(|| layer_toplevel_under(Layer::Background));
3453 } else {
3454 if self.is_inside_hot_corner(output, pos_within_output) {
3455 rv.hot_corner = true;
3456 return rv;
3457 }
3458
3459 under = under
3460 .or_else(|| layer_popup_under(Layer::Top))
3461 .or_else(|| layer_toplevel_under(Layer::Top));
3462
3463 under = under.or_else(interactive_moved_window_under);
3464
3465 if !is_overview_open {
3466 under = under
3467 .or_else(|| layer_popup_under(Layer::Bottom))
3468 .or_else(|| layer_popup_under(Layer::Background));
3469 }
3470
3471 under = under.or_else(window_under);
3472
3473 if !is_overview_open {
3474 under = under
3475 .or_else(|| layer_toplevel_under(Layer::Bottom))
3476 .or_else(|| layer_toplevel_under(Layer::Background));
3477 }
3478 }
3479
3480 let Some((mut surface_and_pos, (window, layer))) = under else {
3481 return rv;
3482 };
3483
3484 if let Some((_, surface_pos)) = &mut surface_and_pos {
3485 *surface_pos += output_pos_in_global_space.to_f64();
3486 }
3487
3488 rv.surface = surface_and_pos;
3489 rv.window = window;
3490 rv.layer = layer;
3491 rv
3492 }
3493
3494 pub fn output_under_cursor(&self) -> Option<Output> {
3495 let pos = self.seat.get_pointer().unwrap().current_location();
3496 self.global_space.output_under(pos).next().cloned()
3497 }
3498
3499 pub fn output_left_of(&self, current: &Output) -> Option<Output> {
3500 let current_geo = self.global_space.output_geometry(current)?;
3501 let extended_geo = Rectangle::new(
3502 Point::from((i32::MIN / 2, current_geo.loc.y)),
3503 Size::from((i32::MAX, current_geo.size.h)),
3504 );
3505
3506 self.global_space
3507 .outputs()
3508 .map(|output| (output, self.global_space.output_geometry(output).unwrap()))
3509 .filter(|(_, geo)| center(*geo).x < center(current_geo).x && geo.overlaps(extended_geo))
3510 .min_by_key(|(_, geo)| center(current_geo).x - center(*geo).x)
3511 .map(|(output, _)| output)
3512 .cloned()
3513 }
3514
3515 pub fn output_right_of(&self, current: &Output) -> Option<Output> {
3516 let current_geo = self.global_space.output_geometry(current)?;
3517 let extended_geo = Rectangle::new(
3518 Point::from((i32::MIN / 2, current_geo.loc.y)),
3519 Size::from((i32::MAX, current_geo.size.h)),
3520 );
3521
3522 self.global_space
3523 .outputs()
3524 .map(|output| (output, self.global_space.output_geometry(output).unwrap()))
3525 .filter(|(_, geo)| center(*geo).x > center(current_geo).x && geo.overlaps(extended_geo))
3526 .min_by_key(|(_, geo)| center(*geo).x - center(current_geo).x)
3527 .map(|(output, _)| output)
3528 .cloned()
3529 }
3530
3531 pub fn output_up_of(&self, current: &Output) -> Option<Output> {
3532 let current_geo = self.global_space.output_geometry(current)?;
3533 let extended_geo = Rectangle::new(
3534 Point::from((current_geo.loc.x, i32::MIN / 2)),
3535 Size::from((current_geo.size.w, i32::MAX)),
3536 );
3537
3538 self.global_space
3539 .outputs()
3540 .map(|output| (output, self.global_space.output_geometry(output).unwrap()))
3541 .filter(|(_, geo)| center(*geo).y < center(current_geo).y && geo.overlaps(extended_geo))
3542 .min_by_key(|(_, geo)| center(current_geo).y - center(*geo).y)
3543 .map(|(output, _)| output)
3544 .cloned()
3545 }
3546
3547 pub fn output_down_of(&self, current: &Output) -> Option<Output> {
3548 let current_geo = self.global_space.output_geometry(current)?;
3549 let extended_geo = Rectangle::new(
3550 Point::from((current_geo.loc.x, i32::MIN / 2)),
3551 Size::from((current_geo.size.w, i32::MAX)),
3552 );
3553
3554 self.global_space
3555 .outputs()
3556 .map(|output| (output, self.global_space.output_geometry(output).unwrap()))
3557 .filter(|(_, geo)| center(*geo).y > center(current_geo).y && geo.overlaps(extended_geo))
3558 .min_by_key(|(_, geo)| center(*geo).y - center(current_geo).y)
3559 .map(|(output, _)| output)
3560 .cloned()
3561 }
3562
3563 pub fn output_previous_of(&self, current: &Output) -> Option<Output> {
3564 self.sorted_outputs
3565 .iter()
3566 .rev()
3567 .skip_while(|&output| output != current)
3568 .nth(1)
3569 .or(self.sorted_outputs.last())
3570 .filter(|&output| output != current)
3571 .cloned()
3572 }
3573
3574 pub fn output_next_of(&self, current: &Output) -> Option<Output> {
3575 self.sorted_outputs
3576 .iter()
3577 .skip_while(|&output| output != current)
3578 .nth(1)
3579 .or(self.sorted_outputs.first())
3580 .filter(|&output| output != current)
3581 .cloned()
3582 }
3583
3584 pub fn output_left(&self) -> Option<Output> {
3585 let active = self.layout.active_output()?;
3586 self.output_left_of(active)
3587 }
3588
3589 pub fn output_right(&self) -> Option<Output> {
3590 let active = self.layout.active_output()?;
3591 self.output_right_of(active)
3592 }
3593
3594 pub fn output_up(&self) -> Option<Output> {
3595 let active = self.layout.active_output()?;
3596 self.output_up_of(active)
3597 }
3598
3599 pub fn output_down(&self) -> Option<Output> {
3600 let active = self.layout.active_output()?;
3601 self.output_down_of(active)
3602 }
3603
3604 pub fn output_previous(&self) -> Option<Output> {
3605 let active = self.layout.active_output()?;
3606 self.output_previous_of(active)
3607 }
3608
3609 pub fn output_next(&self) -> Option<Output> {
3610 let active = self.layout.active_output()?;
3611 self.output_next_of(active)
3612 }
3613
3614 pub fn find_output_and_workspace_index(
3615 &self,
3616 workspace_reference: WorkspaceReference,
3617 ) -> Option<(Option<Output>, usize)> {
3618 let (target_workspace_index, target_workspace) = match workspace_reference {
3619 WorkspaceReference::Index(index) => {
3620 return Some((None, index.saturating_sub(1) as usize));
3621 }
3622 WorkspaceReference::Name(name) => self.layout.find_workspace_by_name(&name)?,
3623 WorkspaceReference::Id(id) => {
3624 let id = WorkspaceId::specific(id);
3625 self.layout.find_workspace_by_id(id)?
3626 }
3627 };
3628
3629 let target_output = target_workspace.current_output();
3630 Some((target_output.cloned(), target_workspace_index))
3631 }
3632
3633 pub fn find_window_by_id(&self, id: MappedId) -> Option<Window> {
3634 self.layout
3635 .windows()
3636 .find(|(_, m)| m.id() == id)
3637 .map(|(_, m)| m.window.clone())
3638 }
3639
3640 pub fn output_for_tablet(&self) -> Option<&Output> {
3641 let config = self.config.borrow();
3642 if config.input.tablet.map_to_focused_output {
3643 self.layout.active_output()
3644 } else {
3645 let map_to_output = config.input.tablet.map_to_output.as_ref();
3646 map_to_output.and_then(|name| self.output_by_name_match(name))
3647 }
3648 }
3649
3650 pub fn output_for_touch(&self) -> Option<&Output> {
3651 let config = self.config.borrow();
3652 let map_to_output = config.input.touch.map_to_output.as_ref();
3653 map_to_output
3654 .and_then(|name| self.output_by_name_match(name))
3655 .or_else(|| self.global_space.outputs().next())
3656 }
3657
3658 pub fn output_by_name_match(&self, target: &str) -> Option<&Output> {
3659 self.global_space
3660 .outputs()
3661 .find(|output| output_matches_name(output, target))
3662 }
3663
3664 pub fn output_for_root(&self, root: &WlSurface) -> Option<&Output> {
3665 // Check the main layout.
3666 let win_out = self.layout.find_window_and_output(root);
3667 let layout_output = win_out.map(|(_, output)| output);
3668 if let Some(output) = layout_output {
3669 return output;
3670 }
3671
3672 // Check layer-shell.
3673 let has_layer_surface = |o: &&Output| {
3674 layer_map_for_output(o)
3675 .layer_for_surface(root, WindowSurfaceType::TOPLEVEL)
3676 .is_some()
3677 };
3678 self.layout.outputs().find(has_layer_surface)
3679 }
3680
3681 pub fn lock_surface_focus(&self) -> Option<WlSurface> {
3682 let output_under_cursor = self.output_under_cursor();
3683 let output = output_under_cursor
3684 .as_ref()
3685 .or_else(|| self.layout.active_output())
3686 .or_else(|| self.global_space.outputs().next())?;
3687
3688 let state = self.output_state.get(output)?;
3689 state.lock_surface.as_ref().map(|s| s.wl_surface()).cloned()
3690 }
3691
3692 /// Schedules an immediate redraw on all outputs if one is not already scheduled.
3693 pub fn queue_redraw_all(&mut self) {
3694 for state in self.output_state.values_mut() {
3695 state.redraw_state = mem::take(&mut state.redraw_state).queue_redraw();
3696 }
3697 }
3698
3699 /// Schedules an immediate redraw if one is not already scheduled.
3700 pub fn queue_redraw(&mut self, output: &Output) {
3701 let state = self.output_state.get_mut(output).unwrap();
3702 state.redraw_state = mem::take(&mut state.redraw_state).queue_redraw();
3703 }
3704
3705 pub fn redraw_queued_outputs(&mut self, backend: &mut Backend) {
3706 let _span = tracy_client::span!("Niri::redraw_queued_outputs");
3707
3708 while let Some((output, _)) = self.output_state.iter().find(|(_, state)| {
3709 matches!(
3710 state.redraw_state,
3711 RedrawState::Queued | RedrawState::WaitingForEstimatedVBlankAndQueued(_)
3712 )
3713 }) {
3714 trace!("redrawing output");
3715 let output = output.clone();
3716 self.redraw(backend, &output);
3717 }
3718 }
3719
3720 pub fn render_pointer<R: NiriRenderer>(
3721 &self,
3722 renderer: &mut R,
3723 output: &Output,
3724 push: &mut dyn FnMut(PointerRenderElements<R>),
3725 ) {
3726 let _span = tracy_client::span!("Niri::render_pointer");
3727 let output_scale = output.current_scale();
3728 let output_pos = self.global_space.output_geometry(output).unwrap().loc;
3729
3730 // Check whether we need to draw the tablet cursor or the regular cursor.
3731 let pointer_pos = self
3732 .tablet_cursor_location
3733 .unwrap_or_else(|| self.seat.get_pointer().unwrap().current_location());
3734 let pointer_pos = pointer_pos - output_pos.to_f64();
3735
3736 // Get the render cursor to draw.
3737 let cursor_scale = output_scale.integer_scale();
3738 let render_cursor = self.cursor_manager.get_render_cursor(cursor_scale);
3739
3740 let output_scale = Scale::from(output.current_scale().fractional_scale());
3741
3742 match render_cursor {
3743 RenderCursor::Hidden => (),
3744 RenderCursor::Surface { surface, hotspot } => {
3745 let pointer_pos =
3746 (pointer_pos - hotspot.to_f64()).to_physical_precise_round(output_scale);
3747
3748 push_elements_from_surface_tree(
3749 renderer,
3750 &surface,
3751 pointer_pos,
3752 output_scale,
3753 1.,
3754 Kind::Cursor,
3755 &mut |elem| push(elem.into()),
3756 );
3757 }
3758 RenderCursor::Named {
3759 icon,
3760 scale,
3761 cursor,
3762 } => {
3763 let (idx, frame) = cursor.frame(self.start_time.elapsed().as_millis() as u32);
3764 let hotspot = XCursor::hotspot(frame).to_logical(scale);
3765 let pointer_pos =
3766 (pointer_pos - hotspot.to_f64()).to_physical_precise_round(output_scale);
3767
3768 let texture = self.cursor_texture_cache.get(icon, scale, &cursor, idx);
3769 match MemoryRenderBufferRenderElement::from_buffer(
3770 renderer,
3771 pointer_pos,
3772 &texture,
3773 None,
3774 None,
3775 None,
3776 Kind::Cursor,
3777 ) {
3778 Ok(element) => push(element.into()),
3779 Err(err) => {
3780 warn!("error importing a cursor texture: {err:?}");
3781 }
3782 }
3783 }
3784 }
3785
3786 if let Some(dnd_icon) = self.dnd_icon.as_ref() {
3787 let pointer_pos =
3788 (pointer_pos + dnd_icon.offset.to_f64()).to_physical_precise_round(output_scale);
3789 push_elements_from_surface_tree(
3790 renderer,
3791 &dnd_icon.surface,
3792 pointer_pos,
3793 output_scale,
3794 1.,
3795 Kind::ScanoutCandidate,
3796 &mut |elem| push(elem.into()),
3797 );
3798 }
3799 }
3800
3801 /// Checks if the pointer should be included on a window cast or screenshot.
3802 ///
3803 /// Returns `(cursor_global_pos, win_pos)` if the pointer should be included, or `None`
3804 /// otherwise.
3805 pub fn pointer_pos_for_window_cast(
3806 &self,
3807 mapped: &Mapped,
3808 ) -> Option<(Point<f64, Logical>, Point<f64, Logical>)> {
3809 // Tablet cursor.
3810 if let Some(tablet_pos) = self.tablet_cursor_location {
3811 let contents = self.contents_under(tablet_pos);
3812 if let Some((w, HitType::Input { win_pos })) = contents.window {
3813 if w == mapped.window {
3814 // Tablet tools don't currently expose current focus, and don't currently
3815 // have grabs. When those are implemented, this branch should be adjusted
3816 // to look more similar to the branch below.
3817 return Some((tablet_pos, win_pos));
3818 }
3819 }
3820 }
3821 // Regular cursor.
3822 else if let Some((w, HitType::Input { win_pos })) = &self.pointer_contents.window {
3823 if w == &mapped.window {
3824 // Grabs can modify the pointer focus, making it different from
3825 // pointer_contents. Notably, gestures like Mod+MMB will remove the pointer
3826 // focus, and ClickGrab will keep pointer focus on the clicked window even
3827 // while it's moving over a different window.
3828 //
3829 // So, double-check that current_focus() (after grabs) also matches the pointer
3830 // contents.
3831 let pointer = self.seat.get_pointer().unwrap();
3832
3833 // The DnD grab is a bit special because it has its own focus (data device)
3834 // while the pointer focus is cleared. That focus is not currently exposed from
3835 // Smithay, and showing DnD icons on window screenshots seems useful, so let's
3836 // just allow it during DnD grabs.
3837 let is_dnd_grab = pointer
3838 .with_grab(|_, grab| State::is_dnd_grab(grab.as_any()))
3839 .unwrap_or(false);
3840
3841 let current_focus_matches = is_dnd_grab
3842 || pointer
3843 .current_focus()
3844 .map(|focused| self.find_root_shell_surface(&focused))
3845 .is_some_and(|focused| mapped.is_wl_surface(&focused));
3846 if current_focus_matches {
3847 // We don't check for pointer visibility because it can only be Visible or
3848 // Hidden, and never Disabled (then it wouldn't have focus). Even when the
3849 // pointer is Hidden, we want to render it, since the user explicitly
3850 // requested show_pointer = true, and otherwise there's no easy way to
3851 // screenshot a window with pointer with hide-when-typing because pressing
3852 // the screenshot bind will hide the pointer.
3853 return Some((pointer.current_location(), *win_pos));
3854 }
3855 }
3856 }
3857
3858 None
3859 }
3860
3861 pub fn refresh_pointer_outputs(&mut self) {
3862 if !self.pointer_visibility.is_visible() {
3863 return;
3864 }
3865
3866 let _span = tracy_client::span!("Niri::refresh_pointer_outputs");
3867
3868 // Check whether we need to draw the tablet cursor or the regular cursor.
3869 let pointer_pos = self
3870 .tablet_cursor_location
3871 .unwrap_or_else(|| self.seat.get_pointer().unwrap().current_location());
3872
3873 match self.cursor_manager.cursor_image() {
3874 CursorImageStatus::Surface(ref surface) => {
3875 let hotspot = with_states(surface, |states| {
3876 states
3877 .data_map
3878 .get::<CursorImageSurfaceData>()
3879 .unwrap()
3880 .lock()
3881 .unwrap()
3882 .hotspot
3883 });
3884
3885 let surface_pos = pointer_pos.to_i32_round() - hotspot;
3886 let bbox = bbox_from_surface_tree(surface, surface_pos);
3887
3888 let dnd = self
3889 .dnd_icon
3890 .as_ref()
3891 .map(|icon| &icon.surface)
3892 .map(|surface| (surface, bbox_from_surface_tree(surface, surface_pos)));
3893
3894 // FIXME we basically need to pick the largest scale factor across the overlapping
3895 // outputs, this is how it's usually done in clients as well.
3896 let mut cursor_scale = 1.;
3897 let mut cursor_transform = Transform::Normal;
3898 let mut dnd_scale = 1.;
3899 let mut dnd_transform = Transform::Normal;
3900 for output in self.global_space.outputs() {
3901 let geo = self.global_space.output_geometry(output).unwrap();
3902
3903 // Compute pointer surface overlap.
3904 if let Some(mut overlap) = geo.intersection(bbox) {
3905 overlap.loc -= surface_pos;
3906 cursor_scale =
3907 f64::max(cursor_scale, output.current_scale().fractional_scale());
3908 // FIXME: using the largest overlapping or "primary" output transform would
3909 // make more sense here.
3910 cursor_transform = output.current_transform();
3911 output_update(output, Some(overlap), surface);
3912 } else {
3913 output_update(output, None, surface);
3914 }
3915
3916 // Compute DnD icon surface overlap.
3917 if let Some((surface, bbox)) = dnd {
3918 if let Some(mut overlap) = geo.intersection(bbox) {
3919 overlap.loc -= surface_pos;
3920 dnd_scale =
3921 f64::max(dnd_scale, output.current_scale().fractional_scale());
3922 // FIXME: using the largest overlapping or "primary" output transform
3923 // would make more sense here.
3924 dnd_transform = output.current_transform();
3925 output_update(output, Some(overlap), surface);
3926 } else {
3927 output_update(output, None, surface);
3928 }
3929 }
3930 }
3931
3932 with_states(surface, |data| {
3933 send_scale_transform(
3934 surface,
3935 data,
3936 output::Scale::Fractional(cursor_scale),
3937 cursor_transform,
3938 )
3939 });
3940 if let Some((surface, _)) = dnd {
3941 with_states(surface, |data| {
3942 send_scale_transform(
3943 surface,
3944 data,
3945 output::Scale::Fractional(dnd_scale),
3946 dnd_transform,
3947 );
3948 });
3949 }
3950 }
3951 cursor_image => {
3952 // There's no cursor surface, but there might be a DnD icon.
3953 let Some(surface) = self.dnd_icon.as_ref().map(|icon| &icon.surface) else {
3954 return;
3955 };
3956
3957 let icon = if let CursorImageStatus::Named(icon) = cursor_image {
3958 *icon
3959 } else {
3960 Default::default()
3961 };
3962
3963 let mut dnd_scale = 1.;
3964 let mut dnd_transform = Transform::Normal;
3965 for output in self.global_space.outputs() {
3966 let geo = self.global_space.output_geometry(output).unwrap();
3967
3968 // The default cursor is rendered at the right scale for each output, which
3969 // means that it may have a different hotspot for each output.
3970 let output_scale = output.current_scale().integer_scale();
3971 let cursor = self
3972 .cursor_manager
3973 .get_cursor_with_name(icon, output_scale)
3974 .unwrap_or_else(|| self.cursor_manager.get_default_cursor(output_scale));
3975
3976 // For simplicity, we always use frame 0 for this computation. Let's hope the
3977 // hotspot doesn't change between frames.
3978 let hotspot = XCursor::hotspot(&cursor.frames()[0]).to_logical(output_scale);
3979
3980 let surface_pos = pointer_pos.to_i32_round() - hotspot;
3981 let bbox = bbox_from_surface_tree(surface, surface_pos);
3982
3983 if let Some(mut overlap) = geo.intersection(bbox) {
3984 overlap.loc -= surface_pos;
3985 dnd_scale = f64::max(dnd_scale, output.current_scale().fractional_scale());
3986 // FIXME: using the largest overlapping or "primary" output transform would
3987 // make more sense here.
3988 dnd_transform = output.current_transform();
3989 output_update(output, Some(overlap), surface);
3990 } else {
3991 output_update(output, None, surface);
3992 }
3993 }
3994
3995 with_states(surface, |data| {
3996 send_scale_transform(
3997 surface,
3998 data,
3999 output::Scale::Fractional(dnd_scale),
4000 dnd_transform,
4001 );
4002 });
4003 }
4004 }
4005 }
4006
4007 pub fn refresh_layout(&mut self) {
4008 let layout_is_active = match &self.keyboard_focus {
4009 KeyboardFocus::Layout { .. } => true,
4010 KeyboardFocus::LayerShell { .. } => false,
4011
4012 // Draw layout as active in these cases to reduce unnecessary window animations.
4013 // There's no confusion because these are both fullscreen modes.
4014 //
4015 // FIXME: when going into the screenshot UI from a layer-shell focus, and then back to
4016 // layer-shell, the layout will briefly draw as active, despite never having focus.
4017 KeyboardFocus::LockScreen { .. } => true,
4018 KeyboardFocus::ScreenshotUi => true,
4019 KeyboardFocus::ExitConfirmDialog => true,
4020 KeyboardFocus::Overview => true,
4021 KeyboardFocus::Mru => true,
4022 };
4023
4024 self.layout.refresh(layout_is_active);
4025 }
4026
4027 pub fn refresh_idle_inhibit(&mut self) {
4028 let _span = tracy_client::span!("Niri::refresh_idle_inhibit");
4029
4030 self.idle_inhibiting_surfaces.retain(|s| s.is_alive());
4031
4032 let is_inhibited = self.is_fdo_idle_inhibited.load(Ordering::SeqCst)
4033 || self.idle_inhibiting_surfaces.iter().any(|surface| {
4034 with_states(surface, |states| {
4035 surface_primary_scanout_output(surface, states).is_some()
4036 })
4037 });
4038 self.idle_notifier_state.set_is_inhibited(is_inhibited);
4039 }
4040
4041 pub fn refresh_window_states(&mut self) {
4042 let _span = tracy_client::span!("Niri::refresh_window_states");
4043
4044 let config = self.config.borrow();
4045 self.layout.with_windows_mut(|mapped, _output| {
4046 mapped.update_tiled_state(config.prefer_no_csd);
4047 });
4048 drop(config);
4049 }
4050
4051 pub fn refresh_window_rules(&mut self) {
4052 let _span = tracy_client::span!("Niri::refresh_window_rules");
4053
4054 let config = self.config.borrow();
4055 let window_rules = &config.window_rules;
4056
4057 let mut windows = vec![];
4058 let mut outputs = HashSet::new();
4059 self.layout.with_windows_mut(|mapped, output| {
4060 if mapped.recompute_window_rules_if_needed(window_rules, self.is_at_startup) {
4061 windows.push(mapped.window.clone());
4062
4063 if let Some(output) = output {
4064 outputs.insert(output.clone());
4065 }
4066
4067 // Since refresh_window_rules() is called after refresh_layout(), we need to update
4068 // the tiled state right here, so that it's picked up by the following
4069 // send_pending_configure().
4070 mapped.update_tiled_state(config.prefer_no_csd);
4071 }
4072 });
4073 drop(config);
4074
4075 for win in windows {
4076 self.layout.update_window(&win, None);
4077 win.toplevel()
4078 .expect("no X11 support")
4079 .send_pending_configure();
4080 }
4081 for output in outputs {
4082 self.queue_redraw(&output);
4083 }
4084 }
4085
4086 pub fn advance_animations(&mut self) {
4087 let _span = tracy_client::span!("Niri::advance_animations");
4088
4089 self.layout.advance_animations();
4090 self.config_error_notification.advance_animations();
4091 self.exit_confirm_dialog.advance_animations();
4092 self.screenshot_ui.advance_animations();
4093 self.window_mru_ui.advance_animations();
4094
4095 for state in self.output_state.values_mut() {
4096 if let Some(transition) = &mut state.screen_transition {
4097 if transition.is_done() {
4098 state.screen_transition = None;
4099 }
4100 }
4101 }
4102 }
4103
4104 pub fn update_render_elements(&mut self, output: Option<&Output>) {
4105 self.update_xray_render_elements(output);
4106 self.layout.update_render_elements(output);
4107
4108 for (out, state) in self.output_state.iter_mut() {
4109 if output.is_none_or(|output| out == output) {
4110 let scale = Scale::from(out.current_scale().fractional_scale());
4111 let transform = out.current_transform();
4112
4113 if let Some(transition) = &mut state.screen_transition {
4114 transition.update_render_elements(scale, transform);
4115 }
4116
4117 let layer_map = layer_map_for_output(out);
4118 for surface in layer_map.layers() {
4119 let Some(mapped) = self.mapped_layer_surfaces.get_mut(surface) else {
4120 continue;
4121 };
4122 let Some(geo) = layer_map.layer_geometry(surface) else {
4123 continue;
4124 };
4125
4126 mapped.update_render_elements(geo.size.to_f64());
4127 }
4128 }
4129 }
4130 }
4131
4132 // Updates only those render elements that go in the xray buffer.
4133 pub fn update_xray_render_elements(&mut self, output: Option<&Output>) {
4134 for (out, state) in self.output_state.iter_mut() {
4135 if output.is_none_or(|output| out == output) {
4136 let scale = Scale::from(out.current_scale().fractional_scale());
4137 let mode = out.current_mode().unwrap();
4138 let transform = out.current_transform();
4139 let size = transform.transform_size(mode.size);
4140
4141 state.xray.workspaces.clear();
4142 let mon = self.layout.monitor_for_output(out).unwrap();
4143 for (ws, geo) in mon.workspaces_with_render_geo() {
4144 let bg_color = ws.render_background().color();
4145 state.xray.workspaces.push((geo, bg_color));
4146 }
4147 state.xray.backdrop_color = state.backdrop_buffer.color();
4148 let blur_options = BlurOptions::from(self.config.borrow().blur);
4149 for buf in &state.xray.background {
4150 let mut buffer = buf.borrow_mut();
4151 buffer.update_size(size, scale);
4152 buffer.update_blur_options(blur_options);
4153 }
4154 for buf in &state.xray.backdrop {
4155 let mut buffer = buf.borrow_mut();
4156 buffer.update_size(size, scale);
4157 buffer.update_blur_options(blur_options);
4158 }
4159
4160 let layer_map = layer_map_for_output(out);
4161 for surface in layer_map.layers_on(Layer::Background) {
4162 let Some(mapped) = self.mapped_layer_surfaces.get_mut(surface) else {
4163 continue;
4164 };
4165 let Some(geo) = layer_map.layer_geometry(surface) else {
4166 continue;
4167 };
4168
4169 mapped.update_render_elements(geo.size.to_f64());
4170 }
4171 }
4172 }
4173 }
4174
4175 pub fn update_shaders(&mut self) {
4176 self.layout.update_shaders();
4177
4178 for mapped in self.mapped_layer_surfaces.values_mut() {
4179 mapped.update_shaders();
4180 }
4181 }
4182
4183 pub fn render_to_vec<R: NiriRenderer>(
4184 &self,
4185 ctx: RenderCtx<R>,
4186 output: &Output,
4187 include_pointer: bool,
4188 ) -> Vec<OutputRenderElements<R>> {
4189 let mut elements = Vec::new();
4190 self.render(ctx, output, include_pointer, &mut |elem| {
4191 elements.push(elem)
4192 });
4193 elements
4194 }
4195
4196 pub fn render<R: NiriRenderer>(
4197 &self,
4198 mut ctx: RenderCtx<R>,
4199 output: &Output,
4200 include_pointer: bool,
4201 push: &mut dyn FnMut(OutputRenderElements<R>),
4202 ) {
4203 let _span = tracy_client::span!("Niri::render");
4204
4205 if ctx.target == RenderTarget::Output {
4206 if let Some(preview) = self.config.borrow().debug.preview_render {
4207 ctx.target = match preview {
4208 PreviewRender::Screencast => RenderTarget::Screencast,
4209 PreviewRender::ScreenCapture => RenderTarget::ScreenCapture,
4210 };
4211 }
4212 }
4213
4214 self.fill_xray_elements(ctx.as_gles(), output);
4215
4216 // Reborrow to shorten lifetime to be able to put in xray.
4217 let mut ctx = ctx.r();
4218 let state = self.output_state.get(output).unwrap();
4219 ctx.xray = Some(&state.xray);
4220
4221 self.render_inner(ctx, output, include_pointer, push);
4222
4223 self.clear_xray_elements(output);
4224 }
4225
4226 fn render_inner<R: NiriRenderer>(
4227 &self,
4228 mut ctx: RenderCtx<R>,
4229 output: &Output,
4230 include_pointer: bool,
4231 push: &mut dyn FnMut(OutputRenderElements<R>),
4232 ) {
4233 let state = self.output_state.get(output).unwrap();
4234 let output_scale = Scale::from(output.current_scale().fractional_scale());
4235
4236 let push = if self.debug_draw_opaque_regions {
4237 &mut move |elem| {
4238 push_opaque_regions(&elem, output_scale, push);
4239 push(elem);
4240 }
4241 } else {
4242 push
4243 };
4244
4245 // The pointer goes on the top.
4246 if include_pointer && self.pointer_visibility.is_visible() {
4247 self.render_pointer(ctx.renderer, output, &mut |elem| push(elem.into()));
4248 }
4249
4250 // Next, the screen transition texture.
4251 {
4252 if let Some(transition) = &state.screen_transition {
4253 push(transition.render(ctx.target).into());
4254 }
4255 }
4256
4257 // Next, the exit confirm dialog.
4258 self.exit_confirm_dialog
4259 .render(ctx.renderer, output, &mut |elem| push(elem.into()));
4260
4261 // Next, the config error notification too.
4262 if let Some(element) = self.config_error_notification.render(ctx.renderer, output) {
4263 push(element.into());
4264 }
4265
4266 // If the session is locked, draw the lock surface.
4267 if self.is_locked() {
4268 if let Some(surface) = state.lock_surface.as_ref() {
4269 push_elements_from_surface_tree(
4270 ctx.renderer,
4271 surface.wl_surface(),
4272 Point::new(0, 0),
4273 output_scale,
4274 1.,
4275 Kind::ScanoutCandidate,
4276 &mut |elem| push(elem.into()),
4277 );
4278 }
4279
4280 // Draw the solid color background.
4281 push(
4282 SolidColorRenderElement::from_buffer(
4283 &state.lock_color_buffer,
4284 (0., 0.),
4285 1.,
4286 Kind::Unspecified,
4287 )
4288 .into(),
4289 );
4290
4291 return;
4292 }
4293
4294 // Prepare the background elements.
4295 let backdrop = SolidColorRenderElement::from_buffer(
4296 &state.backdrop_buffer,
4297 (0., 0.),
4298 1.,
4299 Kind::Unspecified,
4300 )
4301 .into();
4302
4303 // If the screenshot UI is open, draw it.
4304 if self.screenshot_ui.is_open() {
4305 self.screenshot_ui
4306 .render_output(output, ctx.target, &mut |elem| push(elem.into()));
4307
4308 // Add the backdrop for outputs that were connected while the screenshot UI was open.
4309 push(backdrop);
4310
4311 return;
4312 }
4313
4314 // Draw the hotkey overlay on top.
4315 if let Some(element) = self.hotkey_overlay.render(ctx.renderer, output) {
4316 push(element.into());
4317 }
4318
4319 // Then, the Alt-Tab switcher.
4320 self.window_mru_ui
4321 .render_output(self, output, ctx.r(), &mut |elem| push(elem.into()));
4322
4323 // Don't draw the focus ring on the workspaces while interactively moving above those
4324 // workspaces, since the interactively-moved window already has a focus ring.
4325 let focus_ring = !self.layout.interactive_move_is_moving_above_output(output);
4326
4327 // Get monitor elements.
4328 let mon = self.layout.monitor_for_output(output).unwrap();
4329 let zoom = mon.overview_zoom();
4330
4331 // Get layer-shell elements.
4332 let layer_map = layer_map_for_output(output);
4333
4334 // We use macros instead of closures to avoid borrowing issues (renderer and push() go
4335 // into different functions).
4336 macro_rules! push_popups_from_layer {
4337 ($layer:expr, $ns:expr, $xray_pos:expr, $backdrop:expr, $push:expr) => {{
4338 self.render_layer_popups(
4339 ctx.r(),
4340 $ns,
4341 &layer_map,
4342 $layer,
4343 $xray_pos,
4344 $backdrop,
4345 $push,
4346 );
4347 }};
4348 ($layer:expr, true) => {{
4349 push_popups_from_layer!($layer, None, XrayPos::default(), true, &mut |elem| push(
4350 elem.into()
4351 ));
4352 }};
4353 ($layer:expr, $ns:expr, $xray_pos:expr, $push:expr) => {{
4354 push_popups_from_layer!($layer, $ns, $xray_pos, false, $push);
4355 }};
4356 ($layer:expr) => {{
4357 push_popups_from_layer!($layer, None, XrayPos::default(), false, &mut |elem| push(
4358 elem.into()
4359 ));
4360 }};
4361 }
4362 macro_rules! push_normal_from_layer {
4363 ($layer:expr, $ns:expr, $xray_pos:expr, $backdrop:expr, $push:expr) => {{
4364 self.render_layer_normal(
4365 ctx.r(),
4366 $ns,
4367 &layer_map,
4368 $layer,
4369 $xray_pos,
4370 $backdrop,
4371 $push,
4372 );
4373 }};
4374 ($layer:expr, true) => {{
4375 push_normal_from_layer!($layer, None, XrayPos::default(), true, &mut |elem| {
4376 push(elem.into())
4377 });
4378 }};
4379 ($layer:expr, $ns:expr, $xray_pos:expr, $push:expr) => {{
4380 push_normal_from_layer!($layer, $ns, $xray_pos, false, $push);
4381 }};
4382 ($layer:expr) => {{
4383 push_normal_from_layer!($layer, None, XrayPos::default(), false, &mut |elem| {
4384 push(elem.into())
4385 });
4386 }};
4387 }
4388
4389 // The overlay layer elements go next.
4390 push_popups_from_layer!(Layer::Overlay);
4391 push_normal_from_layer!(Layer::Overlay);
4392
4393 // When rendering above the top layer, we put the regular monitor elements first.
4394 // Otherwise, we will render all layer-shell pop-ups and the top layer on top.
4395 if mon.render_above_top_layer() {
4396 self.layout
4397 .render_interactive_move_for_output(ctx.r(), output, &mut |elem| push(elem.into()));
4398
4399 mon.render_insert_hint_between_workspaces(ctx.renderer, &mut |elem| push(elem.into()));
4400
4401 mon.render_workspaces(ctx.r(), focus_ring, &mut |elem| push(elem.into()));
4402
4403 push_popups_from_layer!(Layer::Top);
4404 push_normal_from_layer!(Layer::Top);
4405
4406 push_popups_from_layer!(Layer::Bottom);
4407 push_popups_from_layer!(Layer::Background);
4408 push_normal_from_layer!(Layer::Bottom);
4409 push_normal_from_layer!(Layer::Background);
4410
4411 // We don't expect more than one workspace when render_above_top_layer().
4412 if let Some((ws, _geo)) = mon.workspaces_with_render_geo().next() {
4413 push(ws.render_background().into());
4414 }
4415 } else {
4416 push_popups_from_layer!(Layer::Top);
4417 push_normal_from_layer!(Layer::Top);
4418
4419 self.layout
4420 .render_interactive_move_for_output(ctx.r(), output, &mut |elem| push(elem.into()));
4421
4422 mon.render_insert_hint_between_workspaces(ctx.renderer, &mut |elem| push(elem.into()));
4423
4424 // Macro instead of closure to avoid borrowing push().
4425 macro_rules! process {
4426 ($geo:expr) => {{
4427 &mut |elem| {
4428 if let Some(elem) = scale_relocate_crop(elem, output_scale, zoom, $geo) {
4429 push(elem.into());
4430 }
4431 }
4432 }};
4433 }
4434
4435 for (ws, geo) in mon.workspaces_with_render_geo() {
4436 let ns = Some(ws.id().get() as usize);
4437 let xray_pos = XrayPos::new(geo.loc, zoom);
4438 push_popups_from_layer!(Layer::Bottom, ns, xray_pos, process!(geo));
4439 push_popups_from_layer!(Layer::Background, ns, xray_pos, process!(geo));
4440 }
4441
4442 mon.render_workspaces(ctx.r(), focus_ring, &mut |elem| push(elem.into()));
4443
4444 for (ws, geo) in mon.workspaces_with_render_geo() {
4445 // The render element namespace. This will be set to the workspace index for
4446 // elements duplicated across workspaces (i.e. background and bottom layers) in
4447 // order to have their non-xray framebuffer effects separated from each other.
4448 //
4449 // This doesn't have to correspond exactly to workspace id or idx, the only
4450 // requirement is that there's only one framebuffer effect element with a given id +
4451 // namespace on the frame at once. Id + namespace is used as the cache key in the
4452 // damage tracker.
4453 let ns = Some(ws.id().get() as usize);
4454 let xray_pos = XrayPos::new(geo.loc, zoom);
4455 push_normal_from_layer!(Layer::Bottom, ns, xray_pos, process!(geo));
4456 push_normal_from_layer!(Layer::Background, ns, xray_pos, process!(geo));
4457
4458 process!(geo)(ws.render_background());
4459 }
4460 }
4461
4462 mon.render_workspace_shadows(ctx.renderer, &mut |elem| push(elem.into()));
4463
4464 // Then the backdrop.
4465 push_popups_from_layer!(Layer::Background, true);
4466 push_normal_from_layer!(Layer::Background, true);
4467
4468 push(backdrop);
4469 }
4470
4471 pub fn fill_xray_elements(&self, mut ctx: RenderCtx<GlesRenderer>, output: &Output) {
4472 let _span = tracy_client::span!("Niri::fill_xray_elements");
4473
4474 // Make sure the xrayed elements themselves cannot use xray by mistake.
4475 ctx.xray = None;
4476
4477 let state = self.output_state.get(output).unwrap();
4478 let xray = &state.xray;
4479 let layer_map = layer_map_for_output(output);
4480
4481 // FIXME: it would be cool to call this code on-demand. It's even relatively simple to do:
4482 // move this function to after the render_inner() call, check if
4483 // Rc::strong_count(&xray.background) > 1, and only then construct the elements. This way,
4484 // only if something referenced the xray buffer will the elements get constructed.
4485 //
4486 // Unfortunately, currently this runs into an important limitation: offscreens are rendered
4487 // immediately deep inside render_inner(), and when they are, they already need the xray
4488 // elements filled.
4489 //
4490 // Perhaps in the future when offscreen rendering becomes on-demand, this optimization will
4491 // be possible.
4492
4493 let mut buffer = xray.background[ctx.target as usize].borrow_mut();
4494 {
4495 let elements = buffer.elements();
4496 elements.clear();
4497 self.render_layer_normal(
4498 ctx.r(),
4499 None,
4500 &layer_map,
4501 Layer::Background,
4502 XrayPos::default(),
4503 false,
4504 &mut |elem| elements.push(elem.into()),
4505 );
4506 // Avoid unused capacity remaining forever.
4507 elements.shrink_to_fit();
4508 }
4509
4510 let mut buffer = xray.backdrop[ctx.target as usize].borrow_mut();
4511 {
4512 let elements = buffer.elements();
4513 elements.clear();
4514 self.render_layer_normal(
4515 ctx.r(),
4516 None,
4517 &layer_map,
4518 Layer::Background,
4519 XrayPos::default(),
4520 true,
4521 &mut |elem| elements.push(elem.into()),
4522 );
4523 // Avoid unused capacity remaining forever.
4524 elements.shrink_to_fit();
4525 }
4526 }
4527
4528 pub fn clear_xray_elements(&self, output: &Output) {
4529 let state = self.output_state.get(output).unwrap();
4530 let xray = &state.xray;
4531
4532 // Clear the xray elements for all render targets after all rendering that could use them
4533 // did so.
4534 for buf in &xray.background {
4535 buf.borrow_mut().elements().clear();
4536 }
4537 for buf in &xray.backdrop {
4538 buf.borrow_mut().elements().clear();
4539 }
4540 }
4541
4542 /// Checks if any background layer surface has `block_out_from` set.
4543 pub fn has_blocked_out_background_layers(&self, output: &Output) -> bool {
4544 let layer_map = layer_map_for_output(output);
4545 for for_backdrop in [false, true] {
4546 for (mapped, _geo) in
4547 self.layers_in_render_order(&layer_map, Layer::Background, for_backdrop)
4548 {
4549 if mapped.rules().block_out_from.is_some() {
4550 return true;
4551 }
4552 }
4553 }
4554 false
4555 }
4556
4557 fn layers_in_render_order<'a>(
4558 &'a self,
4559 layer_map: &'a LayerMap,
4560 layer: Layer,
4561 for_backdrop: bool,
4562 ) -> impl Iterator<Item = (&'a MappedLayer, Rectangle<i32, Logical>)> {
4563 // LayerMap returns layers in reverse stacking order.
4564 layer_map.layers_on(layer).rev().filter_map(move |surface| {
4565 let mapped = self.mapped_layer_surfaces.get(surface)?;
4566
4567 if for_backdrop != mapped.place_within_backdrop() {
4568 return None;
4569 }
4570
4571 let geo = layer_map.layer_geometry(surface)?;
4572 Some((mapped, geo))
4573 })
4574 }
4575
4576 #[allow(clippy::too_many_arguments)]
4577 fn render_layer_normal<R: NiriRenderer>(
4578 &self,
4579 mut ctx: RenderCtx<R>,
4580 ns: Option<usize>,
4581 layer_map: &LayerMap,
4582 layer: Layer,
4583 xray_pos: XrayPos,
4584 for_backdrop: bool,
4585 push: &mut dyn FnMut(LayerSurfaceRenderElement<R>),
4586 ) {
4587 for (mapped, geo) in self.layers_in_render_order(layer_map, layer, for_backdrop) {
4588 let loc = geo.loc.to_f64();
4589 let xray_pos = xray_pos.offset(loc);
4590 mapped.render_normal(ctx.r(), ns, loc, xray_pos, push);
4591 }
4592 }
4593
4594 #[allow(clippy::too_many_arguments)]
4595 fn render_layer_popups<R: NiriRenderer>(
4596 &self,
4597 mut ctx: RenderCtx<R>,
4598 ns: Option<usize>,
4599 layer_map: &LayerMap,
4600 layer: Layer,
4601 xray_pos: XrayPos,
4602 for_backdrop: bool,
4603 push: &mut dyn FnMut(LayerSurfaceRenderElement<R>),
4604 ) {
4605 for (mapped, geo) in self.layers_in_render_order(layer_map, layer, for_backdrop) {
4606 let loc = geo.loc.to_f64();
4607 let xray_pos = xray_pos.offset(loc);
4608 mapped.render_popups(ctx.r(), ns, loc, xray_pos, push);
4609 }
4610 }
4611
4612 fn redraw(&mut self, backend: &mut Backend, output: &Output) {
4613 let _span = tracy_client::span!("Niri::redraw");
4614
4615 // Verify our invariant.
4616 let state = self.output_state.get_mut(output).unwrap();
4617 assert!(matches!(
4618 state.redraw_state,
4619 RedrawState::Queued | RedrawState::WaitingForEstimatedVBlankAndQueued(_)
4620 ));
4621
4622 let target_presentation_time = state.frame_clock.next_presentation_time();
4623
4624 // Freeze the clock at the target time.
4625 self.clock.set_unadjusted(target_presentation_time);
4626
4627 self.update_render_elements(Some(output));
4628
4629 let mut res = RenderResult::Skipped;
4630 if self.monitors_active {
4631 let state = self.output_state.get_mut(output).unwrap();
4632 state.unfinished_animations_remain = self.layout.are_animations_ongoing(Some(output));
4633 state.unfinished_animations_remain |=
4634 self.config_error_notification.are_animations_ongoing();
4635 state.unfinished_animations_remain |= self.exit_confirm_dialog.are_animations_ongoing();
4636 state.unfinished_animations_remain |= self.screenshot_ui.are_animations_ongoing();
4637 state.unfinished_animations_remain |= self.window_mru_ui.are_animations_ongoing();
4638 state.unfinished_animations_remain |= state.screen_transition.is_some();
4639
4640 // Also keep redrawing if the current cursor is animated.
4641 state.unfinished_animations_remain |= self
4642 .cursor_manager
4643 .is_current_cursor_animated(output.current_scale().integer_scale());
4644
4645 // Also check layer surfaces.
4646 if !state.unfinished_animations_remain {
4647 state.unfinished_animations_remain |= layer_map_for_output(output)
4648 .layers()
4649 .filter_map(|surface| self.mapped_layer_surfaces.get(surface))
4650 .any(|mapped| mapped.are_animations_ongoing());
4651 }
4652
4653 // Render.
4654 res = backend.render(self, output, target_presentation_time);
4655 }
4656
4657 let is_locked = self.is_locked();
4658 let state = self.output_state.get_mut(output).unwrap();
4659
4660 if res == RenderResult::Skipped {
4661 // Update the redraw state on failed render.
4662 state.redraw_state = if let RedrawState::WaitingForEstimatedVBlank(token)
4663 | RedrawState::WaitingForEstimatedVBlankAndQueued(token) =
4664 state.redraw_state
4665 {
4666 RedrawState::WaitingForEstimatedVBlank(token)
4667 } else {
4668 RedrawState::Idle
4669 };
4670 }
4671
4672 // Update the lock render state on successful render, or if monitors are inactive. When
4673 // monitors are inactive on a TTY, they have no framebuffer attached, so no sensitive data
4674 // from a last render will be visible.
4675 if res != RenderResult::Skipped || !self.monitors_active {
4676 state.lock_render_state = if is_locked {
4677 LockRenderState::Locked
4678 } else {
4679 LockRenderState::Unlocked
4680 };
4681 }
4682
4683 // If we're in process of locking the session, check if the requirements were met.
4684 match mem::take(&mut self.lock_state) {
4685 LockState::Locking(confirmation) => {
4686 if state.lock_render_state == LockRenderState::Unlocked {
4687 // We needed to render a locked frame on this output but failed.
4688 self.unlock();
4689 } else {
4690 // Check if all outputs are now locked.
4691 let all_locked = self
4692 .output_state
4693 .values()
4694 .all(|state| state.lock_render_state == LockRenderState::Locked);
4695
4696 if all_locked {
4697 // All outputs are locked, report success.
4698 let lock = confirmation.ext_session_lock().clone();
4699 confirmation.lock();
4700 self.lock_state = LockState::Locked(lock);
4701 } else {
4702 // Still waiting for other outputs.
4703 self.lock_state = LockState::Locking(confirmation);
4704 }
4705 }
4706 }
4707 lock_state => self.lock_state = lock_state,
4708 }
4709
4710 self.refresh_on_demand_vrr(backend, output);
4711
4712 // Send the frame callbacks.
4713 //
4714 // FIXME: The logic here could be a bit smarter. Currently, during an animation, the
4715 // surfaces that are visible for the very last frame (e.g. because the camera is moving
4716 // away) will receive frame callbacks, and the surfaces that are invisible but will become
4717 // visible next frame will not receive frame callbacks (so they will show stale contents for
4718 // one frame). We could advance the animations for the next frame and send frame callbacks
4719 // according to the expected new positions.
4720 //
4721 // However, this should probably be restricted to sending frame callbacks to more surfaces,
4722 // to err on the safe side.
4723 self.send_frame_callbacks(output);
4724 backend.with_primary_renderer(|renderer| {
4725 #[cfg(feature = "xdp-gnome-screencast")]
4726 {
4727 // Render and send to PipeWire screencast streams.
4728 self.render_for_screen_cast(renderer, output, target_presentation_time);
4729
4730 // FIXME: when a window is hidden, it should probably still receive frame callbacks
4731 // and get rendered for screen cast. This is currently
4732 // unimplemented, but happens to work by chance, since output
4733 // redrawing is more eager than it should be.
4734 self.render_windows_for_screen_cast(renderer, output, target_presentation_time);
4735 }
4736
4737 self.render_for_screencopy_with_damage(renderer, output);
4738 });
4739 }
4740
4741 pub fn refresh_on_demand_vrr(&mut self, backend: &mut Backend, output: &Output) {
4742 let _span = tracy_client::span!("Niri::refresh_on_demand_vrr");
4743
4744 let name = output.user_data().get::<OutputName>().unwrap();
4745 let on_demand = self
4746 .config
4747 .borrow()
4748 .outputs
4749 .find(name)
4750 .is_some_and(|output| output.is_vrr_on_demand());
4751 if !on_demand {
4752 return;
4753 }
4754
4755 let current = self.layout.windows_for_output(output).any(|mapped| {
4756 mapped.rules().variable_refresh_rate == Some(true) && {
4757 let mut visible = false;
4758 mapped.window.with_surfaces(|surface, states| {
4759 if !visible
4760 && surface_primary_scanout_output(surface, states).as_ref() == Some(output)
4761 {
4762 visible = true;
4763 }
4764 });
4765 visible
4766 }
4767 });
4768
4769 backend.set_output_on_demand_vrr(self, output, current);
4770 }
4771
4772 pub fn update_primary_scanout_output(
4773 &self,
4774 output: &Output,
4775 render_element_states: &RenderElementStates,
4776 ) {
4777 // FIXME: potentially tweak the compare function. The default one currently always prefers a
4778 // higher refresh-rate output, which is not always desirable (i.e. with a very small
4779 // overlap).
4780 //
4781 // While we only have cursors and DnD icons crossing output boundaries though, it doesn't
4782 // matter all that much.
4783 if let CursorImageStatus::Surface(surface) = &self.cursor_manager.cursor_image() {
4784 with_surface_tree_downward(
4785 surface,
4786 (),
4787 |_, _, _| TraversalAction::DoChildren(()),
4788 |surface, states, _| {
4789 update_surface_primary_scanout_output(
4790 surface,
4791 output,
4792 states,
4793 None,
4794 render_element_states,
4795 default_primary_scanout_output_compare,
4796 );
4797 },
4798 |_, _, _| true,
4799 );
4800 }
4801
4802 if let Some(surface) = self.dnd_icon.as_ref().map(|icon| &icon.surface) {
4803 with_surface_tree_downward(
4804 surface,
4805 (),
4806 |_, _, _| TraversalAction::DoChildren(()),
4807 |surface, states, _| {
4808 update_surface_primary_scanout_output(
4809 surface,
4810 output,
4811 states,
4812 None,
4813 render_element_states,
4814 default_primary_scanout_output_compare,
4815 );
4816 },
4817 |_, _, _| true,
4818 );
4819 }
4820
4821 // We're only updating the current output's windows and layer surfaces. This should be fine
4822 // as in niri they can only be rendered on a single output at a time.
4823 //
4824 // The reason to do this at all is that it keeps track of whether the surface is visible or
4825 // not in a unified way with the pointer surfaces, which makes the logic elsewhere simpler.
4826
4827 for mapped in self.layout.windows_for_output(output) {
4828 let win = &mapped.window;
4829 let offscreen_data = mapped.offscreen_data();
4830 let offscreen_data = offscreen_data.as_ref();
4831
4832 win.with_surfaces(|surface, states| {
4833 let primary_scanout_output = states
4834 .data_map
4835 .get_or_insert_threadsafe(Mutex::<PrimaryScanoutOutput>::default);
4836 let mut primary_scanout_output = primary_scanout_output.lock().unwrap();
4837
4838 let mut id = Id::from_wayland_resource(surface);
4839
4840 if let Some(data) = offscreen_data {
4841 // We have offscreen data; it's likely that all surfaces are on it.
4842 if data.states.element_was_presented(id.clone()) {
4843 // If the surface was presented to the offscreen, use the offscreen's id.
4844 id = data.id.clone();
4845 }
4846
4847 // If we the surface wasn't presented to the offscreen it can mean:
4848 //
4849 // - The surface was invisible. For example, it's obscured by another surface on
4850 // the offscreen, or simply isn't mapped.
4851 // - The surface is rendered separately from the offscreen, for example: popups
4852 // during the window resize animation.
4853 //
4854 // In both of these cases, using the original surface element id and the
4855 // original states is the correct thing to do. We may find the surface in the
4856 // original states (in the second case). Either way, we definitely know it is
4857 // *not* in the offscreen, and we won't miss it.
4858 //
4859 // There's one edge case: if the surface is both in the offscreen and separate,
4860 // and the offscreen itself is invisible, while the separate surface is
4861 // visible. In this case we'll currently mark the surface as invisible. We
4862 // don't really use offscreens like that however, and if we start, it's easy
4863 // enough to fix (need an extra check).
4864 }
4865
4866 primary_scanout_output.update_from_render_element_states(
4867 id,
4868 output,
4869 None,
4870 render_element_states,
4871 |_, _, output, _| output,
4872 );
4873 });
4874 }
4875
4876 let xray = &self.output_state[output].xray;
4877 let xray_bg = xray.background[RenderTarget::Output as usize].borrow();
4878 let xray_bd = xray.backdrop[RenderTarget::Output as usize].borrow();
4879
4880 for layer in layer_map_for_output(output).layers() {
4881 let surface = layer.wl_surface();
4882 let is_background = layer.layer() == Layer::Background;
4883
4884 with_surfaces_surface_tree(surface, |surface, states| {
4885 let primary_scanout_output = states
4886 .data_map
4887 .get_or_insert_threadsafe(Mutex::<PrimaryScanoutOutput>::default);
4888 let mut primary_scanout_output = primary_scanout_output.lock().unwrap();
4889 let mut id = Id::from_wayland_resource(surface);
4890
4891 // Background layers may be invisible normally but visible through an xray
4892 // background effect. Try to find it and use the xray element's id in this case.
4893 //
4894 // FIXME: this won't work if there's another layer of offscreen (e.g. window with
4895 // an xray background during its opening animation). But hopefully with the
4896 // refactor to draw background effects outside offscreens it won't be a problem.
4897 if is_background && !render_element_states.element_was_presented(id.clone()) {
4898 // A layer may be present either in background or backdrop, never in both.
4899 if xray_bg
4900 .render_element_states()
4901 .is_some_and(|s| s.element_was_presented(id.clone()))
4902 {
4903 id = xray_bg.id().clone();
4904 } else if xray_bd
4905 .render_element_states()
4906 .is_some_and(|s| s.element_was_presented(id.clone()))
4907 {
4908 id = xray_bd.id().clone();
4909 }
4910 }
4911
4912 primary_scanout_output.update_from_render_element_states(
4913 id,
4914 output,
4915 None,
4916 render_element_states,
4917 // Layer surfaces are shown only on one output at a time.
4918 |_, _, output, _| output,
4919 );
4920 });
4921
4922 // Popups never go into xray buffers.
4923 for (popup, _) in PopupManager::popups_for_surface(surface) {
4924 let surface = popup.wl_surface();
4925 with_surfaces_surface_tree(surface, |surface, states| {
4926 update_surface_primary_scanout_output(
4927 surface,
4928 output,
4929 states,
4930 None,
4931 render_element_states,
4932 // Layer surfaces are shown only on one output at a time.
4933 |_, _, output, _| output,
4934 );
4935 });
4936 }
4937 }
4938
4939 if let Some(surface) = &self.output_state[output].lock_surface {
4940 with_surface_tree_downward(
4941 surface.wl_surface(),
4942 (),
4943 |_, _, _| TraversalAction::DoChildren(()),
4944 |surface, states, _| {
4945 update_surface_primary_scanout_output(
4946 surface,
4947 output,
4948 states,
4949 None,
4950 render_element_states,
4951 default_primary_scanout_output_compare,
4952 );
4953 },
4954 |_, _, _| true,
4955 );
4956 }
4957 }
4958
4959 pub fn send_dmabuf_feedbacks(
4960 &self,
4961 output: &Output,
4962 feedback: &SurfaceDmabufFeedback,
4963 render_element_states: &RenderElementStates,
4964 ) {
4965 let _span = tracy_client::span!("Niri::send_dmabuf_feedbacks");
4966
4967 // We can unconditionally send the current output's feedback to regular and layer-shell
4968 // surfaces, as they can only be displayed on a single output at a time. Even if a surface
4969 // is currently invisible, this is the DMABUF feedback that it should know about.
4970 for mapped in self.layout.windows_for_output(output) {
4971 mapped.window.send_dmabuf_feedback(
4972 output,
4973 |_, _| Some(output.clone()),
4974 |surface, _| {
4975 select_dmabuf_feedback(
4976 surface,
4977 render_element_states,
4978 &feedback.render,
4979 &feedback.scanout,
4980 )
4981 },
4982 );
4983 }
4984
4985 for surface in layer_map_for_output(output).layers() {
4986 surface.send_dmabuf_feedback(
4987 output,
4988 |_, _| Some(output.clone()),
4989 |surface, _| {
4990 select_dmabuf_feedback(
4991 surface,
4992 render_element_states,
4993 &feedback.render,
4994 &feedback.scanout,
4995 )
4996 },
4997 );
4998 }
4999
5000 if let Some(surface) = &self.output_state[output].lock_surface {
5001 send_dmabuf_feedback_surface_tree(
5002 surface.wl_surface(),
5003 output,
5004 |_, _| Some(output.clone()),
5005 |surface, _| {
5006 select_dmabuf_feedback(
5007 surface,
5008 render_element_states,
5009 &feedback.render,
5010 &feedback.scanout,
5011 )
5012 },
5013 );
5014 }
5015
5016 if let Some(surface) = self.dnd_icon.as_ref().map(|icon| &icon.surface) {
5017 send_dmabuf_feedback_surface_tree(
5018 surface,
5019 output,
5020 surface_primary_scanout_output,
5021 |surface, _| {
5022 select_dmabuf_feedback(
5023 surface,
5024 render_element_states,
5025 &feedback.render,
5026 &feedback.scanout,
5027 )
5028 },
5029 );
5030 }
5031
5032 if let CursorImageStatus::Surface(surface) = &self.cursor_manager.cursor_image() {
5033 send_dmabuf_feedback_surface_tree(
5034 surface,
5035 output,
5036 surface_primary_scanout_output,
5037 |surface, _| {
5038 select_dmabuf_feedback(
5039 surface,
5040 render_element_states,
5041 &feedback.render,
5042 &feedback.scanout,
5043 )
5044 },
5045 );
5046 }
5047 }
5048
5049 pub fn send_frame_callbacks(&mut self, output: &Output) {
5050 let _span = tracy_client::span!("Niri::send_frame_callbacks");
5051
5052 let state = self.output_state.get(output).unwrap();
5053 let sequence = state.frame_callback_sequence;
5054
5055 let should_send = |surface: &WlSurface, states: &SurfaceData| {
5056 // Do the standard primary scanout output check. For pointer surfaces it deduplicates
5057 // the frame callbacks across potentially multiple outputs, and for regular windows and
5058 // layer-shell surfaces it avoids sending frame callbacks to invisible surfaces.
5059 let current_primary_output = surface_primary_scanout_output(surface, states);
5060 if current_primary_output.as_ref() != Some(output) {
5061 return None;
5062 }
5063
5064 // Next, check the throttling status.
5065 let frame_throttling_state = states
5066 .data_map
5067 .get_or_insert(SurfaceFrameThrottlingState::default);
5068 let mut last_sent_at = frame_throttling_state.last_sent_at.borrow_mut();
5069
5070 let mut send = true;
5071
5072 // If we already sent a frame callback to this surface this output refresh
5073 // cycle, don't send one again to prevent empty-damage commit busy loops.
5074 if let Some((last_output, last_sequence)) = &*last_sent_at {
5075 if last_output == output && *last_sequence == sequence {
5076 send = false;
5077 }
5078 }
5079
5080 if send {
5081 *last_sent_at = Some((output.clone(), sequence));
5082 Some(output.clone())
5083 } else {
5084 None
5085 }
5086 };
5087
5088 let frame_callback_time = get_monotonic_time();
5089
5090 for mapped in self.layout.windows_for_output_mut(output) {
5091 mapped.send_frame(
5092 output,
5093 frame_callback_time,
5094 FRAME_CALLBACK_THROTTLE,
5095 should_send,
5096 );
5097 }
5098
5099 for surface in layer_map_for_output(output).layers() {
5100 surface.send_frame(
5101 output,
5102 frame_callback_time,
5103 FRAME_CALLBACK_THROTTLE,
5104 should_send,
5105 );
5106 }
5107
5108 if let Some(surface) = &self.output_state[output].lock_surface {
5109 send_frames_surface_tree(
5110 surface.wl_surface(),
5111 output,
5112 frame_callback_time,
5113 FRAME_CALLBACK_THROTTLE,
5114 should_send,
5115 );
5116 }
5117
5118 if let Some(surface) = self.dnd_icon.as_ref().map(|icon| &icon.surface) {
5119 send_frames_surface_tree(
5120 surface,
5121 output,
5122 frame_callback_time,
5123 FRAME_CALLBACK_THROTTLE,
5124 should_send,
5125 );
5126 }
5127
5128 if let CursorImageStatus::Surface(surface) = self.cursor_manager.cursor_image() {
5129 send_frames_surface_tree(
5130 surface,
5131 output,
5132 frame_callback_time,
5133 FRAME_CALLBACK_THROTTLE,
5134 should_send,
5135 );
5136 }
5137 }
5138
5139 pub fn send_frame_callbacks_on_fallback_timer(&mut self) {
5140 let _span = tracy_client::span!("Niri::send_frame_callbacks_on_fallback_timer");
5141
5142 // Make up a bogus output; we don't care about it here anyway, just the throttling timer.
5143 let output = Output::new(
5144 String::new(),
5145 PhysicalProperties {
5146 size: Size::from((0, 0)),
5147 subpixel: Subpixel::Unknown,
5148 make: String::new(),
5149 model: String::new(),
5150 serial_number: String::new(),
5151 },
5152 );
5153 let output = &output;
5154
5155 let frame_callback_time = get_monotonic_time();
5156
5157 self.layout.with_windows_mut(|mapped, _| {
5158 mapped.send_frame(
5159 output,
5160 frame_callback_time,
5161 FRAME_CALLBACK_THROTTLE,
5162 |_, _| None,
5163 );
5164 });
5165
5166 for (output, state) in self.output_state.iter() {
5167 for surface in layer_map_for_output(output).layers() {
5168 surface.send_frame(
5169 output,
5170 frame_callback_time,
5171 FRAME_CALLBACK_THROTTLE,
5172 |_, _| None,
5173 );
5174 }
5175
5176 if let Some(surface) = &state.lock_surface {
5177 send_frames_surface_tree(
5178 surface.wl_surface(),
5179 output,
5180 frame_callback_time,
5181 FRAME_CALLBACK_THROTTLE,
5182 |_, _| None,
5183 );
5184 }
5185 }
5186
5187 if let Some(surface) = &self.dnd_icon.as_ref().map(|icon| &icon.surface) {
5188 send_frames_surface_tree(
5189 surface,
5190 output,
5191 frame_callback_time,
5192 FRAME_CALLBACK_THROTTLE,
5193 |_, _| None,
5194 );
5195 }
5196
5197 if let CursorImageStatus::Surface(surface) = self.cursor_manager.cursor_image() {
5198 send_frames_surface_tree(
5199 surface,
5200 output,
5201 frame_callback_time,
5202 FRAME_CALLBACK_THROTTLE,
5203 |_, _| None,
5204 );
5205 }
5206 }
5207
5208 pub fn take_presentation_feedbacks(
5209 &mut self,
5210 output: &Output,
5211 render_element_states: &RenderElementStates,
5212 ) -> OutputPresentationFeedback {
5213 let mut feedback = OutputPresentationFeedback::new(output);
5214
5215 if let CursorImageStatus::Surface(surface) = &self.cursor_manager.cursor_image() {
5216 take_presentation_feedback_surface_tree(
5217 surface,
5218 &mut feedback,
5219 surface_primary_scanout_output,
5220 |surface, _| {
5221 surface_presentation_feedback_flags_from_states(
5222 surface,
5223 None,
5224 render_element_states,
5225 )
5226 },
5227 );
5228 }
5229
5230 if let Some(surface) = self.dnd_icon.as_ref().map(|icon| &icon.surface) {
5231 take_presentation_feedback_surface_tree(
5232 surface,
5233 &mut feedback,
5234 surface_primary_scanout_output,
5235 |surface, _| {
5236 surface_presentation_feedback_flags_from_states(
5237 surface,
5238 None,
5239 render_element_states,
5240 )
5241 },
5242 );
5243 }
5244
5245 for mapped in self.layout.windows_for_output(output) {
5246 mapped.window.take_presentation_feedback(
5247 &mut feedback,
5248 surface_primary_scanout_output,
5249 |surface, _| {
5250 surface_presentation_feedback_flags_from_states(
5251 surface,
5252 None,
5253 render_element_states,
5254 )
5255 },
5256 )
5257 }
5258
5259 for surface in layer_map_for_output(output).layers() {
5260 surface.take_presentation_feedback(
5261 &mut feedback,
5262 surface_primary_scanout_output,
5263 |surface, _| {
5264 surface_presentation_feedback_flags_from_states(
5265 surface,
5266 None,
5267 render_element_states,
5268 )
5269 },
5270 );
5271 }
5272
5273 if let Some(surface) = &self.output_state[output].lock_surface {
5274 take_presentation_feedback_surface_tree(
5275 surface.wl_surface(),
5276 &mut feedback,
5277 surface_primary_scanout_output,
5278 |surface, _| {
5279 surface_presentation_feedback_flags_from_states(
5280 surface,
5281 None,
5282 render_element_states,
5283 )
5284 },
5285 );
5286 }
5287
5288 feedback
5289 }
5290
5291 pub fn render_for_screencopy_with_damage(
5292 &mut self,
5293 renderer: &mut GlesRenderer,
5294 output: &Output,
5295 ) {
5296 let _span = tracy_client::span!("Niri::render_for_screencopy_with_damage");
5297
5298 let mut screencopy_state = mem::take(&mut self.screencopy_state);
5299
5300 screencopy_state.with_queues_mut(|queue| {
5301 let (damage_tracker, screencopy) = queue.split();
5302 if let Some(screencopy) = screencopy {
5303 if screencopy.output() == output {
5304 let ctx = RenderCtx {
5305 renderer,
5306 target: RenderTarget::ScreenCapture,
5307 xray: None,
5308 };
5309 let offset = screencopy.region_loc().upscale(-1);
5310 let mut elements = Vec::new();
5311 self.render(ctx, output, screencopy.overlay_cursor(), &mut |elem| {
5312 let elem =
5313 RelocateRenderElement::from_element(elem, offset, Relocate::Relative);
5314 elements.push(elem);
5315 });
5316
5317 let (damages, states) = Self::damage_screencopy_internal(
5318 output,
5319 &elements,
5320 damage_tracker,
5321 screencopy,
5322 );
5323 if let Some(damages) = damages {
5324 // Convert from Physical coordinates back to Buffer coordinates.
5325 let transform = output.current_transform();
5326 let physical_size = transform.transform_size(screencopy.buffer_size());
5327 let damages = damages.iter().map(|dmg| {
5328 dmg.to_logical(1).to_buffer(
5329 1,
5330 transform.invert(),
5331 &physical_size.to_logical(1),
5332 )
5333 });
5334
5335 screencopy.damage(damages);
5336
5337 let render_result = Self::render_for_screencopy_internal(
5338 renderer,
5339 damage_tracker,
5340 &elements,
5341 states,
5342 screencopy,
5343 );
5344 match render_result {
5345 Ok(sync) => {
5346 queue.pop().submit_after_sync(false, sync, &self.event_loop);
5347 }
5348 Err(err) => {
5349 // Recreate damage tracker to report full damage next check.
5350 *damage_tracker =
5351 OutputDamageTracker::new((0, 0), 1.0, Transform::Normal);
5352 queue.pop();
5353 warn!("error rendering for screencopy: {err:?}");
5354 }
5355 }
5356 } else {
5357 trace!("no damage found, waiting till next redraw");
5358 }
5359 };
5360 }
5361 });
5362
5363 self.screencopy_state = screencopy_state;
5364 }
5365
5366 pub fn render_for_screencopy_without_damage(
5367 &mut self,
5368 renderer: &mut GlesRenderer,
5369 manager: &ZwlrScreencopyManagerV1,
5370 screencopy: Screencopy,
5371 ) -> anyhow::Result<()> {
5372 let _span = tracy_client::span!("Niri::render_for_screencopy");
5373
5374 let output = screencopy.output();
5375 ensure!(
5376 self.output_state.contains_key(output),
5377 "screencopy output missing"
5378 );
5379
5380 self.update_render_elements(Some(output));
5381
5382 let ctx = RenderCtx {
5383 renderer,
5384 target: RenderTarget::ScreenCapture,
5385 xray: None,
5386 };
5387 let offset = screencopy.region_loc().upscale(-1);
5388 let mut elements = Vec::new();
5389 self.render(ctx, output, screencopy.overlay_cursor(), &mut |elem| {
5390 let elem = RelocateRenderElement::from_element(elem, offset, Relocate::Relative);
5391 elements.push(elem);
5392 });
5393
5394 let Some(damage_tracker) = self.screencopy_state.damage_tracker(manager) else {
5395 error!("screencopy queue must not be deleted as long as frames exist");
5396 bail!("screencopy queue missing");
5397 };
5398
5399 let (_damages, states) =
5400 Self::damage_screencopy_internal(output, &elements, damage_tracker, &screencopy);
5401 let res = Self::render_for_screencopy_internal(
5402 renderer,
5403 damage_tracker,
5404 &elements,
5405 states,
5406 &screencopy,
5407 );
5408 let res = res.map(|sync| screencopy.submit_after_sync(false, sync, &self.event_loop));
5409
5410 if res.is_err() {
5411 // Recreate damage tracker to report full damage next check.
5412 *damage_tracker = OutputDamageTracker::new((0, 0), 1.0, Transform::Normal);
5413 }
5414
5415 res
5416 }
5417
5418 fn damage_screencopy_internal<'a>(
5419 output: &Output,
5420 elements: &[impl Element],
5421 damage_tracker: &'a mut OutputDamageTracker,
5422 screencopy: &Screencopy,
5423 ) -> (
5424 Option<&'a Vec<Rectangle<i32, Physical>>>,
5425 RenderElementStates,
5426 ) {
5427 let OutputModeSource::Static {
5428 size: last_size,
5429 scale: last_scale,
5430 transform: last_transform,
5431 } = damage_tracker.mode().clone()
5432 else {
5433 unreachable!("damage tracker must have static mode");
5434 };
5435
5436 let size = screencopy.buffer_size();
5437 let scale: Scale<f64> = output.current_scale().fractional_scale().into();
5438 let transform = output.current_transform();
5439
5440 if size != last_size || scale != last_scale || transform != last_transform {
5441 *damage_tracker = OutputDamageTracker::new(size, scale, transform);
5442 }
5443
5444 // Just checked damage tracker has static mode
5445 damage_tracker.damage_output(1, elements).unwrap()
5446 }
5447
5448 #[allow(clippy::type_complexity)]
5449 fn render_for_screencopy_internal(
5450 renderer: &mut GlesRenderer,
5451 damage_tracker: &mut OutputDamageTracker,
5452 elements: &[impl RenderElement<GlesRenderer>],
5453 states: RenderElementStates,
5454 screencopy: &Screencopy,
5455 ) -> anyhow::Result<Option<SyncPoint>> {
5456 let sync = match screencopy.buffer() {
5457 ScreencopyBuffer::Dmabuf(dmabuf) => {
5458 let sync =
5459 render_to_dmabuf(renderer, damage_tracker, dmabuf.clone(), elements, states)
5460 .context("error rendering to screencopy dmabuf")?;
5461 Some(sync)
5462 }
5463 ScreencopyBuffer::Shm(wl_buffer) => {
5464 render_to_shm(renderer, damage_tracker, wl_buffer, elements, states)
5465 .context("error rendering to screencopy shm buffer")?;
5466 None
5467 }
5468 };
5469
5470 Ok(sync)
5471 }
5472
5473 #[cfg(not(feature = "xdp-gnome-screencast"))]
5474 pub fn stop_casts_for_target(&mut self, _target: CastTarget) {}
5475
5476 #[cfg(not(feature = "xdp-gnome-screencast"))]
5477 pub fn stop_cast(&mut self, _session_id: crate::utils::CastSessionId) {}
5478
5479 pub fn debug_toggle_damage(&mut self) {
5480 self.debug_draw_damage = !self.debug_draw_damage;
5481
5482 if self.debug_draw_damage {
5483 for (output, state) in &mut self.output_state {
5484 state.debug_damage_tracker = OutputDamageTracker::from_output(output);
5485 }
5486 }
5487
5488 self.queue_redraw_all();
5489 }
5490
5491 pub fn capture_screenshots<'a>(
5492 &'a self,
5493 renderer: &'a mut GlesRenderer,
5494 ) -> impl Iterator<Item = (Output, [OutputScreenshot; 3])> + 'a {
5495 self.global_space.outputs().cloned().filter_map(|output| {
5496 let size = output.current_mode().unwrap().size;
5497 let transform = output.current_transform();
5498 let size = transform.transform_size(size);
5499
5500 let scale = Scale::from(output.current_scale().fractional_scale());
5501 let targets = [
5502 RenderTarget::Output,
5503 RenderTarget::Screencast,
5504 RenderTarget::ScreenCapture,
5505 ];
5506 let screenshot = targets.map(|target| {
5507 let ctx = RenderCtx {
5508 renderer,
5509 target,
5510 xray: None,
5511 };
5512 let elements = self.render_to_vec(ctx, &output, false);
5513 let elements = elements.iter().rev();
5514
5515 let res = render_to_texture(
5516 renderer,
5517 size,
5518 scale,
5519 Transform::Normal,
5520 Fourcc::Abgr8888,
5521 elements,
5522 );
5523 if let Err(err) = &res {
5524 warn!("error rendering output {}: {err:?}", output.name());
5525 }
5526 let res_output = res.ok();
5527
5528 let mut pointer = Vec::new();
5529
5530 // We check the pointer visibility for Disabled (and not .is_visible()) in order to
5531 // show the pointer even when it's hidden through cursor {} options. The user can
5532 // then toggle it in the screenshot UI as needed.
5533 if self.pointer_visibility != PointerVisibility::Disabled {
5534 self.render_pointer(renderer, &output, &mut |elem| pointer.push(elem));
5535 }
5536
5537 let res_pointer = if pointer.is_empty() {
5538 None
5539 } else {
5540 let res = render_to_encompassing_texture(
5541 renderer,
5542 scale,
5543 Transform::Normal,
5544 Fourcc::Abgr8888,
5545 &pointer,
5546 );
5547 if let Err(err) = &res {
5548 warn!("error rendering pointer for {}: {err:?}", output.name());
5549 }
5550 res.ok()
5551 };
5552
5553 res_output.map(|(texture, _)| {
5554 OutputScreenshot::from_textures(
5555 renderer,
5556 scale,
5557 texture,
5558 res_pointer.map(|(texture, _, geo)| (texture, geo)),
5559 )
5560 })
5561 });
5562
5563 if screenshot.iter().any(|res| res.is_none()) {
5564 return None;
5565 }
5566
5567 let screenshot = screenshot.map(|res| res.unwrap());
5568 Some((output, screenshot))
5569 })
5570 }
5571
5572 pub fn screenshot(
5573 &mut self,
5574 renderer: &mut GlesRenderer,
5575 output: &Output,
5576 write_to_disk: bool,
5577 include_pointer: bool,
5578 path: Option<String>,
5579 ) -> anyhow::Result<()> {
5580 let _span = tracy_client::span!("Niri::screenshot");
5581
5582 self.update_render_elements(Some(output));
5583
5584 let size = output.current_mode().unwrap().size;
5585 let transform = output.current_transform();
5586 let size = transform.transform_size(size);
5587
5588 let scale = Scale::from(output.current_scale().fractional_scale());
5589 let ctx = RenderCtx {
5590 renderer,
5591 target: RenderTarget::ScreenCapture,
5592 xray: None,
5593 };
5594 let elements = self.render_to_vec(ctx, output, include_pointer);
5595 let elements = elements.iter().rev();
5596 let pixels = render_to_vec(
5597 renderer,
5598 size,
5599 scale,
5600 Transform::Normal,
5601 Fourcc::Abgr8888,
5602 elements,
5603 )?;
5604
5605 self.save_screenshot(size, pixels, write_to_disk, path)
5606 .context("error saving screenshot")
5607 }
5608
5609 pub fn screenshot_window(
5610 &self,
5611 renderer: &mut GlesRenderer,
5612 output: &Output,
5613 mapped: &Mapped,
5614 write_to_disk: bool,
5615 show_pointer: bool,
5616 path: Option<String>,
5617 ) -> anyhow::Result<()> {
5618 let _span = tracy_client::span!("Niri::screenshot_window");
5619
5620 let scale = Scale::from(output.current_scale().fractional_scale());
5621 let alpha =
5622 if mapped.sizing_mode().is_fullscreen() || mapped.is_ignoring_opacity_window_rule() {
5623 1.
5624 } else {
5625 mapped.rules().opacity.unwrap_or(1.).clamp(0., 1.)
5626 };
5627
5628 let mut elements: Vec<WindowScreenshotRenderElement<GlesRenderer>> = Vec::new();
5629
5630 // Add pointer if requested and it's over this window.
5631 if show_pointer {
5632 if let Some((_, win_pos)) = self.pointer_pos_for_window_cast(mapped) {
5633 // Pointer elements are at output-local physical coords.
5634 // Relocate by -win_pos to make them window-relative.
5635 let pos = win_pos.to_physical_precise_round(scale).upscale(-1);
5636 self.render_pointer(renderer, output, &mut |elem| {
5637 let elem = RelocateRenderElement::from_element(elem, pos, Relocate::Relative);
5638 elements.push(elem.into());
5639 });
5640 }
5641 }
5642 let pointer_count = elements.len();
5643
5644 let ctx = RenderCtx {
5645 renderer,
5646 target: RenderTarget::ScreenCapture,
5647 xray: None,
5648 };
5649 mapped.render(
5650 ctx,
5651 mapped.window.geometry().loc.to_f64(),
5652 scale,
5653 alpha,
5654 XrayPos::default(),
5655 &mut |elem| elements.push(elem.into()),
5656 );
5657
5658 // The pointer is not included in encompassing_geo because we don't want it to expand the
5659 // screenshot size.
5660 let geo = encompassing_geo(scale, elements.iter().skip(pointer_count));
5661 let elements = elements.iter().rev().map(|elem| {
5662 RelocateRenderElement::from_element(elem, geo.loc.upscale(-1), Relocate::Relative)
5663 });
5664 let pixels = render_to_vec(
5665 renderer,
5666 geo.size,
5667 scale,
5668 Transform::Normal,
5669 Fourcc::Abgr8888,
5670 elements,
5671 )?;
5672
5673 self.save_screenshot(geo.size, pixels, write_to_disk, path)
5674 .context("error saving screenshot")
5675 }
5676
5677 pub fn save_screenshot(
5678 &self,
5679 size: Size<i32, Physical>,
5680 pixels: Vec<u8>,
5681 write_to_disk: bool,
5682 path_arg: Option<String>,
5683 ) -> anyhow::Result<()> {
5684 let path = write_to_disk
5685 .then(|| {
5686 // When given an explicit path, don't try to strftime it or create parents.
5687 path_arg.map(|p| (PathBuf::from(p), false)).or_else(|| {
5688 match make_screenshot_path(&self.config.borrow()) {
5689 Ok(path) => path.map(|p| (p, true)),
5690 Err(err) => {
5691 warn!("error making screenshot path: {err:?}");
5692 None
5693 }
5694 }
5695 })
5696 })
5697 .flatten();
5698
5699 // Prepare to set the encoded image as our clipboard selection. This must be done from the
5700 // main thread.
5701 let (tx, rx) = calloop::channel::sync_channel::<Arc<[u8]>>(1);
5702 self.event_loop
5703 .insert_source(rx, move |event, _, state| match event {
5704 calloop::channel::Event::Msg(buf) => {
5705 set_data_device_selection(
5706 &state.niri.display_handle,
5707 &state.niri.seat,
5708 vec![String::from("image/png")],
5709 buf.clone(),
5710 );
5711 }
5712 calloop::channel::Event::Closed => (),
5713 })
5714 .unwrap();
5715
5716 // Prepare to send screenshot completion event back to main thread.
5717 let (event_tx, event_rx) = calloop::channel::sync_channel::<Option<String>>(1);
5718 self.event_loop
5719 .insert_source(event_rx, move |event, _, state| match event {
5720 calloop::channel::Event::Msg(path) => {
5721 state.ipc_screenshot_taken(path);
5722 }
5723 calloop::channel::Event::Closed => (),
5724 })
5725 .unwrap();
5726
5727 // Encode and save the image in a thread as it's slow.
5728 thread::spawn(move || {
5729 let mut buf = vec![];
5730
5731 let w = std::io::Cursor::new(&mut buf);
5732 if let Err(err) = write_png_rgba8(w, size.w as u32, size.h as u32, &pixels) {
5733 warn!("error encoding screenshot image: {err:?}");
5734 return;
5735 }
5736
5737 let buf: Arc<[u8]> = Arc::from(buf.into_boxed_slice());
5738 let _ = tx.send(buf.clone());
5739
5740 let mut image_path = None;
5741
5742 if let Some((path, create_parent)) = path {
5743 debug!("saving screenshot to {path:?}");
5744
5745 if create_parent {
5746 if let Some(parent) = path.parent() {
5747 // Relative paths with one component, i.e. "test.png", have Some("") parent.
5748 if !parent.as_os_str().is_empty() {
5749 if let Err(err) = std::fs::create_dir_all(parent) {
5750 if err.kind() != std::io::ErrorKind::AlreadyExists {
5751 warn!("error creating screenshot directory: {err:?}");
5752 }
5753 }
5754 }
5755 }
5756 }
5757
5758 match std::fs::write(&path, buf) {
5759 Ok(()) => image_path = Some(path),
5760 Err(err) => {
5761 warn!("error saving screenshot image: {err:?}");
5762 }
5763 }
5764 } else {
5765 debug!("not saving screenshot to disk");
5766 }
5767
5768 #[cfg(feature = "dbus")]
5769 if let Err(err) = crate::utils::show_screenshot_notification(image_path.as_deref()) {
5770 warn!("error showing screenshot notification: {err:?}");
5771 }
5772
5773 // Send screenshot completion event.
5774 let path_string = image_path
5775 .as_ref()
5776 .and_then(|p| p.to_str())
5777 .map(|s| s.to_owned());
5778 let _ = event_tx.send(path_string);
5779 });
5780
5781 Ok(())
5782 }
5783
5784 #[cfg(feature = "dbus")]
5785 pub fn screenshot_all_outputs(
5786 &mut self,
5787 renderer: &mut GlesRenderer,
5788 include_pointer: bool,
5789 on_done: impl FnOnce(PathBuf) + Send + 'static,
5790 ) -> anyhow::Result<()> {
5791 let _span = tracy_client::span!("Niri::screenshot_all_outputs");
5792
5793 self.update_render_elements(None);
5794
5795 let outputs: Vec<_> = self.global_space.outputs().cloned().collect();
5796
5797 // FIXME: support multiple outputs, needs fixing multi-scale handling and cropping.
5798 anyhow::ensure!(outputs.len() == 1);
5799
5800 let output = outputs.into_iter().next().unwrap();
5801 let geom = self.global_space.output_geometry(&output).unwrap();
5802
5803 let output_scale = output.current_scale().integer_scale();
5804 let geom = geom.to_physical(output_scale);
5805
5806 let size = geom.size;
5807 let transform = output.current_transform();
5808 let size = transform.transform_size(size);
5809
5810 let ctx = RenderCtx {
5811 renderer,
5812 target: RenderTarget::ScreenCapture,
5813 xray: None,
5814 };
5815 let elements = self.render_to_vec(ctx, &output, include_pointer);
5816 let elements = elements.iter().rev();
5817 let pixels = render_to_vec(
5818 renderer,
5819 size,
5820 Scale::from(f64::from(output_scale)),
5821 Transform::Normal,
5822 Fourcc::Abgr8888,
5823 elements,
5824 )?;
5825
5826 let path = make_screenshot_path(&self.config.borrow())
5827 .ok()
5828 .flatten()
5829 .unwrap_or_else(|| {
5830 let mut path = env::temp_dir();
5831 path.push("screenshot.png");
5832 path
5833 });
5834 debug!("saving screenshot to {path:?}");
5835
5836 thread::spawn(move || {
5837 let file = match std::fs::File::create(&path) {
5838 Ok(file) => file,
5839 Err(err) => {
5840 warn!("error creating file: {err:?}");
5841 return;
5842 }
5843 };
5844
5845 let w = std::io::BufWriter::new(file);
5846 if let Err(err) = write_png_rgba8(w, size.w as u32, size.h as u32, &pixels) {
5847 warn!("error encoding screenshot image: {err:?}");
5848 return;
5849 }
5850
5851 on_done(path);
5852 });
5853
5854 Ok(())
5855 }
5856
5857 pub fn is_locked(&self) -> bool {
5858 match self.lock_state {
5859 LockState::Unlocked | LockState::WaitingForSurfaces { .. } => false,
5860 LockState::Locking(_) | LockState::Locked(_) => true,
5861 }
5862 }
5863
5864 pub fn lock(&mut self, confirmation: SessionLocker) {
5865 // Check if another client is in the process of locking.
5866 if matches!(
5867 self.lock_state,
5868 LockState::WaitingForSurfaces { .. } | LockState::Locking(_)
5869 ) {
5870 info!("refusing lock as another client is currently locking");
5871 return;
5872 }
5873
5874 // Check if we're already locked with an active client.
5875 if let LockState::Locked(lock) = &self.lock_state {
5876 if lock.is_alive() {
5877 info!("refusing lock as already locked with an active client");
5878 return;
5879 }
5880
5881 // If the client had died, continue with the new lock.
5882 info!("locking session (replacing existing dead lock)");
5883
5884 // Since the session was already locked, we know that the outputs are blanked, and
5885 // can lock right away.
5886 let lock = confirmation.ext_session_lock().clone();
5887 confirmation.lock();
5888 self.lock_state = LockState::Locked(lock);
5889
5890 return;
5891 }
5892
5893 info!("locking session");
5894
5895 if self.output_state.is_empty() {
5896 // There are no outputs, lock the session right away.
5897 self.screenshot_ui.close();
5898 self.cursor_manager
5899 .set_cursor_image(CursorImageStatus::default_named());
5900
5901 let lock = confirmation.ext_session_lock().clone();
5902 confirmation.lock();
5903 self.lock_state = LockState::Locked(lock);
5904 } else {
5905 // There are outputs which we need to redraw before locking. But before we do that,
5906 // let's wait for the lock surfaces.
5907 //
5908 // Give them a second; swaylock can take its time to paint a big enough image.
5909 let timer = Timer::from_duration(Duration::from_millis(1000));
5910 let deadline_token = self
5911 .event_loop
5912 .insert_source(timer, |_, _, state| {
5913 trace!("lock deadline expired, continuing");
5914 state.niri.continue_to_locking();
5915 TimeoutAction::Drop
5916 })
5917 .unwrap();
5918
5919 self.lock_state = LockState::WaitingForSurfaces {
5920 confirmation,
5921 deadline_token,
5922 };
5923 }
5924 }
5925
5926 pub fn maybe_continue_to_locking(&mut self) {
5927 if !matches!(self.lock_state, LockState::WaitingForSurfaces { .. }) {
5928 // Not waiting.
5929 return;
5930 }
5931
5932 // Check if there are any outputs whose lock surfaces had not had a commit yet.
5933 for state in self.output_state.values() {
5934 let Some(surface) = &state.lock_surface else {
5935 // Surface not created yet.
5936 return;
5937 };
5938
5939 if !is_mapped(surface.wl_surface()) {
5940 return;
5941 }
5942 }
5943
5944 // All good.
5945 trace!("lock surfaces are ready, continuing");
5946 self.continue_to_locking();
5947 }
5948
5949 fn continue_to_locking(&mut self) {
5950 match mem::take(&mut self.lock_state) {
5951 LockState::WaitingForSurfaces {
5952 confirmation,
5953 deadline_token,
5954 } => {
5955 self.event_loop.remove(deadline_token);
5956
5957 self.screenshot_ui.close();
5958 self.cursor_manager
5959 .set_cursor_image(CursorImageStatus::default_named());
5960 self.cancel_mru();
5961
5962 if self.output_state.is_empty() {
5963 // There are no outputs, lock the session right away.
5964 let lock = confirmation.ext_session_lock().clone();
5965 confirmation.lock();
5966 self.lock_state = LockState::Locked(lock);
5967 } else {
5968 // There are outputs which we need to redraw before locking.
5969 self.lock_state = LockState::Locking(confirmation);
5970 self.queue_redraw_all();
5971 }
5972 }
5973 other => {
5974 error!("continue_to_locking() called with wrong lock state: {other:?}",);
5975 self.lock_state = other;
5976 }
5977 }
5978 }
5979
5980 pub fn unlock(&mut self) {
5981 info!("unlocking session");
5982
5983 let prev = mem::take(&mut self.lock_state);
5984 if let LockState::WaitingForSurfaces { deadline_token, .. } = prev {
5985 self.event_loop.remove(deadline_token);
5986 }
5987
5988 for output_state in self.output_state.values_mut() {
5989 output_state.lock_surface = None;
5990 }
5991 self.queue_redraw_all();
5992 }
5993
5994 #[cfg(feature = "dbus")]
5995 fn update_locked_hint(&mut self) {
5996 use std::sync::LazyLock;
5997
5998 if !self.is_session_instance {
5999 return;
6000 }
6001
6002 static XDG_SESSION_ID: LazyLock<Option<String>> = LazyLock::new(|| {
6003 let id = std::env::var("XDG_SESSION_ID").ok();
6004 if id.is_none() {
6005 warn!(
6006 "env var 'XDG_SESSION_ID' is unset or invalid; logind LockedHint won't be set"
6007 );
6008 }
6009 id
6010 });
6011
6012 let Some(session_id) = &*XDG_SESSION_ID else {
6013 return;
6014 };
6015
6016 fn call(session_id: &str, locked: bool) -> anyhow::Result<()> {
6017 let conn = zbus::blocking::Connection::system()
6018 .context("error connecting to the system bus")?;
6019
6020 let message = conn
6021 .call_method(
6022 Some("org.freedesktop.login1"),
6023 "/org/freedesktop/login1",
6024 Some("org.freedesktop.login1.Manager"),
6025 "GetSession",
6026 &(session_id),
6027 )
6028 .context("failed to call GetSession")?;
6029
6030 let message_body = message.body();
6031 let session_path: zbus::zvariant::ObjectPath = message_body
6032 .deserialize()
6033 .context("failed to deserialize GetSession reply")?;
6034
6035 conn.call_method(
6036 Some("org.freedesktop.login1"),
6037 session_path,
6038 Some("org.freedesktop.login1.Session"),
6039 "SetLockedHint",
6040 &(locked),
6041 )
6042 .context("failed to call SetLockedHint")?;
6043
6044 Ok(())
6045 }
6046
6047 // Consider only the fully locked state here. When using the locked hint with sleep
6048 // inhibitor tools, we want to allow sleep only after the screens are fully cleared with
6049 // the lock screen, which corresponds to the Locked state.
6050 let locked = matches!(self.lock_state, LockState::Locked(_));
6051
6052 if self.locked_hint.is_some_and(|h| h == locked) {
6053 return;
6054 }
6055
6056 self.locked_hint = Some(locked);
6057
6058 let res = thread::Builder::new()
6059 .name("Logind LockedHint Updater".to_owned())
6060 .spawn(move || {
6061 let _span = tracy_client::span!("LockedHint");
6062
6063 if let Err(err) = call(session_id, locked) {
6064 warn!("failed to set logind LockedHint: {err:?}");
6065 }
6066 });
6067
6068 if let Err(err) = res {
6069 warn!("error spawning a thread to set logind LockedHint: {err:?}");
6070 }
6071 }
6072
6073 pub fn new_lock_surface(&mut self, surface: LockSurface, output: &Output) {
6074 let lock = match &self.lock_state {
6075 LockState::Unlocked => {
6076 error!("tried to add a lock surface on an unlocked session");
6077 return;
6078 }
6079 LockState::WaitingForSurfaces { confirmation, .. } => confirmation.ext_session_lock(),
6080 LockState::Locking(confirmation) => confirmation.ext_session_lock(),
6081 LockState::Locked(lock) => lock,
6082 };
6083
6084 if lock.client() != surface.wl_surface().client() {
6085 debug!("ignoring lock surface from an unrelated client");
6086 return;
6087 }
6088
6089 if lock != surface.ext_session_lock() {
6090 debug!("ignoring lock surface from an unrelated lock instance");
6091 return;
6092 }
6093
6094 let Some(output_state) = self.output_state.get_mut(output) else {
6095 error!("missing output state");
6096 return;
6097 };
6098
6099 output_state.lock_surface = Some(surface);
6100 }
6101
6102 /// Activates the pointer constraint if necessary according to the current pointer contents.
6103 ///
6104 /// Make sure the pointer location and contents are up to date before calling this.
6105 pub fn maybe_activate_pointer_constraint(&self) {
6106 let Some((surface, surface_loc)) = &self.pointer_contents.surface else {
6107 return;
6108 };
6109
6110 let pointer = self.seat.get_pointer().unwrap();
6111 if Some(surface) != pointer.current_focus().as_ref() {
6112 return;
6113 }
6114
6115 with_pointer_constraint(surface, &pointer, |constraint| {
6116 let Some(constraint) = constraint else { return };
6117
6118 if constraint.is_active() {
6119 return;
6120 }
6121
6122 // Constraint does not apply if not within region.
6123 if let Some(region) = constraint.region() {
6124 let pointer_pos = pointer.current_location();
6125 let pos_within_surface = pointer_pos - *surface_loc;
6126 if !region.contains(pos_within_surface.to_i32_round()) {
6127 return;
6128 }
6129 }
6130
6131 constraint.activate();
6132 });
6133 }
6134
6135 pub fn focus_layer_surface_if_on_demand(&mut self, surface: Option<LayerSurface>) {
6136 if let Some(surface) = surface {
6137 if surface.cached_state().keyboard_interactivity
6138 == wlr_layer::KeyboardInteractivity::OnDemand
6139 {
6140 if self.layer_shell_on_demand_focus.as_ref() != Some(&surface) {
6141 self.layer_shell_on_demand_focus = Some(surface);
6142
6143 // FIXME: granular.
6144 self.queue_redraw_all();
6145 }
6146
6147 return;
6148 }
6149 }
6150
6151 // Something else got clicked, clear on-demand layer-shell focus.
6152 if self.layer_shell_on_demand_focus.is_some() {
6153 self.layer_shell_on_demand_focus = None;
6154
6155 // FIXME: granular.
6156 self.queue_redraw_all();
6157 }
6158 }
6159
6160 /// Tries to find and return the root shell surface for a given surface.
6161 ///
6162 /// I.e. for popups, this function will try to find the parent toplevel or layer surface. For
6163 /// regular subsurfaces, it will find the root surface.
6164 pub fn find_root_shell_surface(&self, surface: &WlSurface) -> WlSurface {
6165 let Some(root) = self.root_surface.get(surface) else {
6166 return surface.clone();
6167 };
6168
6169 if let Some(popup) = self.popups.find_popup(root) {
6170 return find_popup_root_surface(&popup).unwrap_or_else(|_| root.clone());
6171 }
6172
6173 root.clone()
6174 }
6175
6176 #[cfg(feature = "dbus")]
6177 pub fn on_ipc_outputs_changed(&self) {
6178 let _span = tracy_client::span!("Niri::on_ipc_outputs_changed");
6179
6180 let Some(dbus) = &self.dbus else { return };
6181 let Some(conn_display_config) = dbus.conn_display_config.clone() else {
6182 return;
6183 };
6184
6185 let res = thread::Builder::new()
6186 .name("DisplayConfig MonitorsChanged Emitter".to_owned())
6187 .spawn(move || {
6188 use crate::dbus::mutter_display_config::DisplayConfig;
6189 let _span = tracy_client::span!("MonitorsChanged");
6190 let iface = match conn_display_config
6191 .object_server()
6192 .interface::<_, DisplayConfig>("/org/gnome/Mutter/DisplayConfig")
6193 {
6194 Ok(iface) => iface,
6195 Err(err) => {
6196 warn!("error getting DisplayConfig interface: {err:?}");
6197 return;
6198 }
6199 };
6200
6201 async_io::block_on(async move {
6202 if let Err(err) = DisplayConfig::monitors_changed(iface.signal_emitter()).await
6203 {
6204 warn!("error emitting MonitorsChanged: {err:?}");
6205 }
6206 });
6207 });
6208
6209 if let Err(err) = res {
6210 warn!("error spawning a thread to send MonitorsChanged: {err:?}");
6211 }
6212 }
6213
6214 pub fn handle_focus_follows_mouse(&mut self, new_focus: &PointContents) {
6215 let Some(ffm) = self.config.borrow().input.focus_follows_mouse else {
6216 return;
6217 };
6218
6219 let pointer = &self.seat.get_pointer().unwrap();
6220 if pointer.is_grabbed() {
6221 return;
6222 }
6223
6224 if self.window_mru_ui.is_open() {
6225 return;
6226 }
6227
6228 // Recompute the current pointer focus because we don't update it during animations.
6229 let current_focus = self.contents_under(pointer.current_location());
6230
6231 if let Some(output) = &new_focus.output {
6232 if current_focus.output.as_ref() != Some(output) {
6233 self.layout.focus_output(output);
6234 }
6235 }
6236
6237 if let Some(window) = &new_focus.window {
6238 if !self.layout.is_overview_open() && current_focus.window.as_ref() != Some(window) {
6239 let (window, hit) = window;
6240
6241 // Don't trigger focus-follows-mouse over the tab indicator.
6242 if matches!(
6243 hit,
6244 HitType::Activate {
6245 is_tab_indicator: true
6246 }
6247 ) {
6248 return;
6249 }
6250
6251 if !self.layout.should_trigger_focus_follows_mouse_on(window) {
6252 return;
6253 }
6254
6255 if let Some(threshold) = ffm.max_scroll_amount {
6256 if self.layout.scroll_amount_to_activate(window) > threshold.0 {
6257 return;
6258 }
6259 }
6260
6261 self.layout.activate_window_without_raising(window);
6262 self.layer_shell_on_demand_focus = None;
6263 }
6264 }
6265
6266 if let Some(layer) = &new_focus.layer {
6267 if current_focus.layer.as_ref() != Some(layer) {
6268 self.layer_shell_on_demand_focus = Some(layer.clone());
6269 }
6270 }
6271 }
6272
6273 pub fn do_screen_transition(&mut self, renderer: &mut GlesRenderer, delay_ms: Option<u16>) {
6274 let _span = tracy_client::span!("Niri::do_screen_transition");
6275
6276 self.update_render_elements(None);
6277
6278 let textures: Vec<_> = self
6279 .output_state
6280 .keys()
6281 .cloned()
6282 .filter_map(|output| {
6283 let size = output.current_mode().unwrap().size;
6284 let transform = output.current_transform();
6285
6286 let scale = Scale::from(output.current_scale().fractional_scale());
6287 let targets = [
6288 RenderTarget::Output,
6289 RenderTarget::Screencast,
6290 RenderTarget::ScreenCapture,
6291 ];
6292 let textures = targets.map(|target| {
6293 let ctx = RenderCtx {
6294 renderer,
6295 target,
6296 xray: None,
6297 };
6298 let elements = self.render_to_vec(ctx, &output, false);
6299 let elements = elements.iter().rev();
6300
6301 let res = render_to_texture(
6302 renderer,
6303 size,
6304 scale,
6305 transform,
6306 Fourcc::Abgr8888,
6307 elements,
6308 );
6309
6310 if let Err(err) = &res {
6311 warn!("error rendering output {}: {err:?}", output.name());
6312 }
6313
6314 res
6315 });
6316
6317 if textures.iter().any(|res| res.is_err()) {
6318 return None;
6319 }
6320
6321 let textures = textures.map(|res| {
6322 let texture = res.unwrap().0;
6323 TextureBuffer::from_texture(
6324 renderer,
6325 texture,
6326 scale,
6327 transform,
6328 Vec::new(), // We want windows below to get frame callbacks.
6329 )
6330 });
6331
6332 Some((output, textures))
6333 })
6334 .collect();
6335
6336 let delay = delay_ms.map_or(screen_transition::DELAY, |d| {
6337 Duration::from_millis(u64::from(d))
6338 });
6339
6340 for (output, from_texture) in textures {
6341 let state = self.output_state.get_mut(&output).unwrap();
6342 state.screen_transition = Some(ScreenTransition::new(
6343 from_texture,
6344 delay,
6345 self.clock.clone(),
6346 ));
6347 }
6348
6349 // We don't actually need to queue a redraw because the point is to freeze the screen for a
6350 // bit, and even if the delay was zero, we're drawing the same contents anyway.
6351 }
6352
6353 pub fn recompute_window_rules(&mut self) {
6354 let _span = tracy_client::span!("Niri::recompute_window_rules");
6355
6356 let changed = {
6357 let window_rules = &self.config.borrow().window_rules;
6358
6359 for unmapped in self.unmapped_windows.values_mut() {
6360 let new_rules = ResolvedWindowRules::compute(
6361 window_rules,
6362 WindowRef::Unmapped(unmapped),
6363 self.is_at_startup,
6364 );
6365 if let InitialConfigureState::Configured { rules, .. } = &mut unmapped.state {
6366 *rules = new_rules;
6367 }
6368 }
6369
6370 let mut windows = vec![];
6371 self.layout.with_windows_mut(|mapped, _| {
6372 if mapped.recompute_window_rules(window_rules, self.is_at_startup) {
6373 windows.push(mapped.window.clone());
6374 }
6375 });
6376 let changed = !windows.is_empty();
6377 for win in windows {
6378 self.layout.update_window(&win, None);
6379 }
6380 changed
6381 };
6382
6383 if changed {
6384 // FIXME: granular.
6385 self.queue_redraw_all();
6386 }
6387 }
6388
6389 pub fn recompute_layer_rules(&mut self) {
6390 let _span = tracy_client::span!("Niri::recompute_layer_rules");
6391
6392 let mut changed = false;
6393 {
6394 let config = self.config.borrow();
6395 let rules = &config.layer_rules;
6396
6397 for mapped in self.mapped_layer_surfaces.values_mut() {
6398 if mapped.recompute_layer_rules(rules, self.is_at_startup) {
6399 changed = true;
6400 mapped.update_config(&config);
6401 }
6402 }
6403 }
6404
6405 if changed {
6406 // FIXME: granular.
6407 self.queue_redraw_all();
6408 }
6409 }
6410
6411 pub fn reset_pointer_inactivity_timer(&mut self) {
6412 if self.pointer_inactivity_timer_got_reset {
6413 return;
6414 }
6415
6416 let _span = tracy_client::span!("Niri::reset_pointer_inactivity_timer");
6417
6418 if let Some(token) = self.pointer_inactivity_timer.take() {
6419 self.event_loop.remove(token);
6420 }
6421
6422 let Some(timeout_ms) = self.config.borrow().cursor.hide_after_inactive_ms else {
6423 return;
6424 };
6425
6426 let duration = Duration::from_millis(timeout_ms as u64);
6427 let timer = Timer::from_duration(duration);
6428 let token = self
6429 .event_loop
6430 .insert_source(timer, move |_, _, state| {
6431 state.niri.pointer_inactivity_timer = None;
6432
6433 // If the pointer is already invisible, don't reset it back to Hidden causing one
6434 // frame of hover.
6435 if state.niri.pointer_visibility.is_visible() {
6436 state.niri.pointer_visibility = PointerVisibility::Hidden;
6437 state.niri.queue_redraw_all();
6438 }
6439
6440 TimeoutAction::Drop
6441 })
6442 .unwrap();
6443 self.pointer_inactivity_timer = Some(token);
6444
6445 self.pointer_inactivity_timer_got_reset = true;
6446 }
6447
6448 pub fn notify_activity(&mut self) {
6449 if self.notified_activity_this_iteration {
6450 return;
6451 }
6452
6453 let _span = tracy_client::span!("Niri::notify_activity");
6454
6455 self.idle_notifier_state.notify_activity(&self.seat);
6456
6457 self.notified_activity_this_iteration = true;
6458 }
6459
6460 pub fn close_mru(&mut self, close_request: MruCloseRequest) -> Option<Window> {
6461 if !self.window_mru_ui.is_open() {
6462 return None;
6463 }
6464 self.queue_redraw_all();
6465
6466 let id = self.window_mru_ui.close(close_request)?;
6467 self.find_window_by_id(id)
6468 }
6469
6470 pub fn cancel_mru(&mut self) {
6471 self.close_mru(MruCloseRequest::Cancel);
6472 }
6473
6474 /// Apply a pending MRU commit immediately.
6475 ///
6476 /// Called for example on keyboard events that reach the active window, which immediately adds
6477 /// it to the MRU.
6478 pub fn mru_apply_keyboard_commit(&mut self) {
6479 let Some(pending) = self.pending_mru_commit.take() else {
6480 return;
6481 };
6482 self.event_loop.remove(pending.token);
6483
6484 if let Some(window) = self
6485 .layout
6486 .workspaces_mut()
6487 .flat_map(|ws| ws.windows_mut())
6488 .find(|w| w.id() == pending.id)
6489 {
6490 window.set_focus_timestamp(pending.stamp);
6491 }
6492 }
6493
6494 pub fn queue_redraw_mru_output(&mut self) {
6495 if let Some(output) = self.window_mru_ui.output().cloned() {
6496 self.queue_redraw(&output);
6497 }
6498 }
6499}
6500
6501pub struct NewClient {
6502 pub client: UnixStream,
6503 pub restricted: bool,
6504 pub credentials_unknown: bool,
6505}
6506
6507pub struct ClientState {
6508 pub compositor_state: CompositorClientState,
6509 pub can_view_decoration_globals: bool,
6510 pub primary_selection_disabled: bool,
6511 /// Whether this client is denied from the restricted protocols such as security-context.
6512 pub restricted: bool,
6513 /// We cannot retrieve this client's socket credentials.
6514 pub credentials_unknown: bool,
6515}
6516
6517impl ClientData for ClientState {
6518 fn initialized(&self, _client_id: ClientId) {}
6519 fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {}
6520}
6521
6522fn scale_relocate_crop<E: Element>(
6523 elem: E,
6524 output_scale: Scale<f64>,
6525 zoom: f64,
6526 ws_geo: Rectangle<f64, Logical>,
6527) -> Option<CropRenderElement<RelocateRenderElement<RescaleRenderElement<E>>>> {
6528 let ws_geo = ws_geo.to_physical_precise_round(output_scale);
6529 let elem = RescaleRenderElement::from_element(elem, Point::from((0, 0)), zoom);
6530 let elem = RelocateRenderElement::from_element(elem, ws_geo.loc, Relocate::Relative);
6531 CropRenderElement::from_element(elem, output_scale, ws_geo)
6532}
6533
6534niri_render_elements! {
6535 PointerRenderElements<R> => {
6536 Wayland = WaylandSurfaceRenderElement<R>,
6537 NamedPointer = MemoryRenderBufferRenderElement<R>,
6538 }
6539}
6540
6541niri_render_elements! {
6542 WindowScreenshotRenderElement<R> => {
6543 Layout = LayoutElementRenderElement<R>,
6544 Pointer = RelocateRenderElement<PointerRenderElements<R>>,
6545 }
6546}
6547
6548niri_render_elements! {
6549 OutputRenderElements<R> => {
6550 Monitor = MonitorRenderElement<R>,
6551 RescaledTile = RescaleRenderElement<TileRenderElement<R>>,
6552 LayerSurface = LayerSurfaceRenderElement<R>,
6553 RelocatedLayerSurface = CropRenderElement<RelocateRenderElement<RescaleRenderElement<
6554 LayerSurfaceRenderElement<R>
6555 >>>,
6556 RelocatedColor = CropRenderElement<RelocateRenderElement<RescaleRenderElement<
6557 SolidColorRenderElement
6558 >>>,
6559 Pointer = PointerRenderElements<R>,
6560 Wayland = WaylandSurfaceRenderElement<R>,
6561 SolidColor = SolidColorRenderElement,
6562 ScreenshotUi = ScreenshotUiRenderElement,
6563 WindowMruUi = WindowMruUiRenderElement<R>,
6564 ExitConfirmDialog = ExitConfirmDialogRenderElement,
6565 Texture = PrimaryGpuTextureRenderElement,
6566 // Used for the CPU-rendered panels.
6567 RelocatedMemoryBuffer = RelocateRenderElement<MemoryRenderBufferRenderElement<R>>,
6568 }
6569}