forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9ff2f83Ivan Molodetskikh1 year ago2099 commits

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