forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB64a9351Ivan Molodetskikh2 years ago1319 commits

niri.rs4689 lines, 172.0 KiBHistoryRawDownload
1use std::cell::{Cell, OnceCell, RefCell};
2use std::collections::{HashMap, HashSet};
3use std::ffi::OsString;
4use std::path::PathBuf;
5use std::rc::Rc;
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::mpsc::{self, Receiver, Sender};
8use std::sync::{Arc, Mutex};
9use std::time::{Duration, Instant};
10use std::{env, mem, thread};
11
12use _server_decoration::server::org_kde_kwin_server_decoration_manager::Mode as KdeDecorationsMode;
13use anyhow::{bail, ensure, Context};
14use calloop::futures::Scheduler;
15use niri_config::{
16 Config, FloatOrInt, Key, Modifiers, PreviewRender, TrackLayout, WorkspaceReference,
17 DEFAULT_BACKGROUND_COLOR,
18};
19use smithay::backend::allocator::Fourcc;
20use smithay::backend::renderer::damage::OutputDamageTracker;
21use smithay::backend::renderer::element::memory::MemoryRenderBufferRenderElement;
22use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
23use smithay::backend::renderer::element::surface::{
24 render_elements_from_surface_tree, WaylandSurfaceRenderElement,
25};
26use smithay::backend::renderer::element::utils::{
27 select_dmabuf_feedback, Relocate, RelocateRenderElement,
28};
29use smithay::backend::renderer::element::{
30 default_primary_scanout_output_compare, AsRenderElements, Element as _, Id, Kind,
31 PrimaryScanoutOutput, RenderElementStates,
32};
33use smithay::backend::renderer::gles::GlesRenderer;
34use smithay::backend::renderer::sync::SyncPoint;
35use smithay::backend::renderer::{Color32F, Unbind};
36use smithay::desktop::utils::{
37 bbox_from_surface_tree, output_update, send_dmabuf_feedback_surface_tree,
38 send_frames_surface_tree, surface_presentation_feedback_flags_from_states,
39 surface_primary_scanout_output, take_presentation_feedback_surface_tree,
40 under_from_surface_tree, update_surface_primary_scanout_output, OutputPresentationFeedback,
41};
42use smithay::desktop::{
43 layer_map_for_output, LayerSurface, PopupGrab, PopupManager, PopupUngrabStrategy, Space,
44 Window, WindowSurfaceType,
45};
46use smithay::input::keyboard::{Layout as KeyboardLayout, XkbContextHandler};
47use smithay::input::pointer::{CursorIcon, CursorImageAttributes, CursorImageStatus, MotionEvent};
48use smithay::input::{Seat, SeatState};
49use smithay::output::{self, Output, OutputModeSource, PhysicalProperties, Subpixel};
50use smithay::reexports::calloop::generic::Generic;
51use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
52use smithay::reexports::calloop::{
53 Interest, LoopHandle, LoopSignal, Mode, PostAction, RegistrationToken,
54};
55use smithay::reexports::wayland_protocols::ext::session_lock::v1::server::ext_session_lock_v1::ExtSessionLockV1;
56use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::WmCapabilities;
57use smithay::reexports::wayland_protocols_misc::server_decoration as _server_decoration;
58use smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1;
59use smithay::reexports::wayland_server::backend::{
60 ClientData, ClientId, DisconnectReason, GlobalId,
61};
62use smithay::reexports::wayland_server::protocol::wl_shm;
63use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
64use smithay::reexports::wayland_server::{Client, Display, DisplayHandle, Resource};
65use smithay::utils::{
66 ClockSource, IsAlive as _, Logical, Monotonic, Physical, Point, Rectangle, Scale, Size,
67 Transform, SERIAL_COUNTER,
68};
69use smithay::wayland::compositor::{
70 with_states, with_surface_tree_downward, CompositorClientState, CompositorHandler,
71 CompositorState, HookId, SurfaceData, TraversalAction,
72};
73use smithay::wayland::cursor_shape::CursorShapeManagerState;
74use smithay::wayland::dmabuf::DmabufState;
75use smithay::wayland::fractional_scale::FractionalScaleManagerState;
76use smithay::wayland::idle_inhibit::IdleInhibitManagerState;
77use smithay::wayland::idle_notify::IdleNotifierState;
78use smithay::wayland::input_method::{InputMethodManagerState, InputMethodSeat};
79use smithay::wayland::output::OutputManagerState;
80use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraintsState};
81use smithay::wayland::pointer_gestures::PointerGesturesState;
82use smithay::wayland::presentation::PresentationState;
83use smithay::wayland::relative_pointer::RelativePointerManagerState;
84use smithay::wayland::security_context::SecurityContextState;
85use smithay::wayland::selection::data_device::{set_data_device_selection, DataDeviceState};
86use smithay::wayland::selection::primary_selection::PrimarySelectionState;
87use smithay::wayland::selection::wlr_data_control::DataControlState;
88use smithay::wayland::session_lock::{LockSurface, SessionLockManagerState, SessionLocker};
89use smithay::wayland::shell::kde::decoration::KdeDecorationState;
90use smithay::wayland::shell::wlr_layer::{self, Layer, WlrLayerShellState};
91use smithay::wayland::shell::xdg::decoration::XdgDecorationState;
92use smithay::wayland::shell::xdg::XdgShellState;
93use smithay::wayland::shm::ShmState;
94use smithay::wayland::socket::ListeningSocketSource;
95use smithay::wayland::tablet_manager::TabletManagerState;
96use smithay::wayland::text_input::TextInputManagerState;
97use smithay::wayland::viewporter::ViewporterState;
98use smithay::wayland::virtual_keyboard::VirtualKeyboardManagerState;
99use smithay::wayland::xdg_activation::XdgActivationState;
100use smithay::wayland::xdg_foreign::XdgForeignState;
101
102use crate::backend::tty::SurfaceDmabufFeedback;
103use crate::backend::{Backend, RenderResult, Tty, Winit};
104use crate::cursor::{CursorManager, CursorTextureCache, RenderCursor, XCursor};
105#[cfg(feature = "dbus")]
106use crate::dbus::gnome_shell_introspect::{self, IntrospectToNiri, NiriToIntrospect};
107#[cfg(feature = "dbus")]
108use crate::dbus::gnome_shell_screenshot::{NiriToScreenshot, ScreenshotToNiri};
109#[cfg(feature = "xdp-gnome-screencast")]
110use crate::dbus::mutter_screen_cast::{self, ScreenCastToNiri};
111use crate::frame_clock::FrameClock;
112use crate::handlers::configure_lock_surface;
113use crate::input::scroll_tracker::ScrollTracker;
114use crate::input::{
115 apply_libinput_settings, mods_with_finger_scroll_binds, mods_with_wheel_binds, TabletData,
116};
117use crate::ipc::server::IpcServer;
118use crate::layout::{Layout, LayoutElement as _, MonitorRenderElement};
119use crate::protocols::foreign_toplevel::{self, ForeignToplevelManagerState};
120use crate::protocols::gamma_control::GammaControlManagerState;
121use crate::protocols::mutter_x11_interop::MutterX11InteropManagerState;
122use crate::protocols::output_management::OutputManagementManagerState;
123use crate::protocols::screencopy::{Screencopy, ScreencopyBuffer, ScreencopyManagerState};
124use crate::pw_utils::{Cast, PipeWire};
125#[cfg(feature = "xdp-gnome-screencast")]
126use crate::pw_utils::{CastSizeChange, CastTarget, PwToNiri};
127use crate::render_helpers::debug::draw_opaque_regions;
128use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement;
129use crate::render_helpers::renderer::NiriRenderer;
130use crate::render_helpers::texture::TextureBuffer;
131use crate::render_helpers::{
132 render_to_dmabuf, render_to_encompassing_texture, render_to_shm, render_to_texture,
133 render_to_vec, shaders, RenderTarget,
134};
135use crate::ui::config_error_notification::ConfigErrorNotification;
136use crate::ui::exit_confirm_dialog::ExitConfirmDialog;
137use crate::ui::hotkey_overlay::HotkeyOverlay;
138use crate::ui::screen_transition::{self, ScreenTransition};
139use crate::ui::screenshot_ui::{OutputScreenshot, ScreenshotUi, ScreenshotUiRenderElement};
140use crate::utils::scale::{closest_representable_scale, guess_monitor_scale};
141use crate::utils::spawning::CHILD_ENV;
142use crate::utils::{
143 center, center_f64, get_monotonic_time, ipc_transform_to_smithay, logical_output,
144 make_screenshot_path, output_size, send_scale_transform, write_png_rgba8,
145};
146use crate::window::{InitialConfigureState, Mapped, ResolvedWindowRules, Unmapped, WindowRef};
147use crate::{animation, niri_render_elements};
148
149const CLEAR_COLOR_LOCKED: [f32; 4] = [0.3, 0.1, 0.1, 1.];
150
151// We'll try to send frame callbacks at least once a second. We'll make a timer that fires once a
152// second, so with the worst timing the maximum interval between two frame callbacks for a surface
153// should be ~1.995 seconds.
154const FRAME_CALLBACK_THROTTLE: Option<Duration> = Some(Duration::from_millis(995));
155
156pub struct Niri {
157 pub config: Rc<RefCell<Config>>,
158
159 /// Output config from the config file.
160 ///
161 /// This does not include transient output config changes done via IPC. It is only used when
162 /// reloading the config from disk to determine if the output configuration should be reloaded
163 /// (and transient changes dropped).
164 pub config_file_output_config: niri_config::Outputs,
165
166 pub event_loop: LoopHandle<'static, State>,
167 pub scheduler: Scheduler<()>,
168 pub stop_signal: LoopSignal,
169 pub display_handle: DisplayHandle,
170 pub socket_name: OsString,
171
172 pub start_time: Instant,
173
174 /// Whether the at-startup=true window rules are active.
175 pub is_at_startup: bool,
176
177 // Each workspace corresponds to a Space. Each workspace generally has one Output mapped to it,
178 // however it may have none (when there are no outputs connected) or multiple (when mirroring).
179 pub layout: Layout<Mapped>,
180
181 // This space does not actually contain any windows, but all outputs are mapped into it
182 // according to their global position.
183 pub global_space: Space<Window>,
184
185 // Windows which don't have a buffer attached yet.
186 pub unmapped_windows: HashMap<WlSurface, Unmapped>,
187
188 // Cached root surface for every surface, so that we can access it in destroyed() where the
189 // normal get_parent() is cleared out.
190 pub root_surface: HashMap<WlSurface, WlSurface>,
191
192 // Dmabuf readiness pre-commit hook for a surface.
193 pub dmabuf_pre_commit_hook: HashMap<WlSurface, HookId>,
194
195 /// Clients to notify about their blockers being cleared.
196 pub blocker_cleared_tx: Sender<Client>,
197 pub blocker_cleared_rx: Receiver<Client>,
198
199 pub output_state: HashMap<Output, OutputState>,
200 pub output_by_name: HashMap<String, Output>,
201
202 // When false, we're idling with monitors powered off.
203 pub monitors_active: bool,
204
205 pub devices: HashSet<input::Device>,
206 pub tablets: HashMap<input::Device, TabletData>,
207 pub touch: HashSet<input::Device>,
208
209 // Smithay state.
210 pub compositor_state: CompositorState,
211 pub xdg_shell_state: XdgShellState,
212 pub xdg_decoration_state: XdgDecorationState,
213 pub kde_decoration_state: KdeDecorationState,
214 pub layer_shell_state: WlrLayerShellState,
215 pub session_lock_state: SessionLockManagerState,
216 pub foreign_toplevel_state: ForeignToplevelManagerState,
217 pub screencopy_state: ScreencopyManagerState,
218 pub output_management_state: OutputManagementManagerState,
219 pub viewporter_state: ViewporterState,
220 pub xdg_foreign_state: XdgForeignState,
221 pub shm_state: ShmState,
222 pub output_manager_state: OutputManagerState,
223 pub dmabuf_state: DmabufState,
224 pub fractional_scale_manager_state: FractionalScaleManagerState,
225 pub seat_state: SeatState<State>,
226 pub tablet_state: TabletManagerState,
227 pub text_input_state: TextInputManagerState,
228 pub input_method_state: InputMethodManagerState,
229 pub virtual_keyboard_state: VirtualKeyboardManagerState,
230 pub pointer_gestures_state: PointerGesturesState,
231 pub relative_pointer_state: RelativePointerManagerState,
232 pub pointer_constraints_state: PointerConstraintsState,
233 pub idle_notifier_state: IdleNotifierState<State>,
234 pub idle_inhibit_manager_state: IdleInhibitManagerState,
235 pub data_device_state: DataDeviceState,
236 pub primary_selection_state: PrimarySelectionState,
237 pub data_control_state: DataControlState,
238 pub popups: PopupManager,
239 pub popup_grab: Option<PopupGrabState>,
240 pub presentation_state: PresentationState,
241 pub security_context_state: SecurityContextState,
242 pub gamma_control_manager_state: GammaControlManagerState,
243 pub activation_state: XdgActivationState,
244 pub mutter_x11_interop_state: MutterX11InteropManagerState,
245
246 pub seat: Seat<State>,
247 /// Scancodes of the keys to suppress.
248 pub suppressed_keys: HashSet<u32>,
249 pub bind_cooldown_timers: HashMap<Key, RegistrationToken>,
250 pub bind_repeat_timer: Option<RegistrationToken>,
251 pub keyboard_focus: KeyboardFocus,
252 pub layer_shell_on_demand_focus: Option<LayerSurface>,
253 pub idle_inhibiting_surfaces: HashSet<WlSurface>,
254 pub is_fdo_idle_inhibited: Arc<AtomicBool>,
255
256 pub cursor_manager: CursorManager,
257 pub cursor_texture_cache: CursorTextureCache,
258 pub cursor_shape_manager_state: CursorShapeManagerState,
259 pub dnd_icon: Option<WlSurface>,
260 pub pointer_focus: PointerFocus,
261 /// Whether the pointer is hidden, for example due to a previous touch input.
262 ///
263 /// When this happens, the pointer also loses any focus. This is so that touch can prevent
264 /// various tooltips from sticking around.
265 pub pointer_hidden: bool,
266 // FIXME: this should be able to be removed once PointerFocus takes grabs into account.
267 pub pointer_grab_ongoing: bool,
268 pub tablet_cursor_location: Option<Point<f64, Logical>>,
269 pub gesture_swipe_3f_cumulative: Option<(f64, f64)>,
270 pub vertical_wheel_tracker: ScrollTracker,
271 pub horizontal_wheel_tracker: ScrollTracker,
272 pub mods_with_wheel_binds: HashSet<Modifiers>,
273 pub vertical_finger_scroll_tracker: ScrollTracker,
274 pub horizontal_finger_scroll_tracker: ScrollTracker,
275 pub mods_with_finger_scroll_binds: HashSet<Modifiers>,
276
277 pub lock_state: LockState,
278
279 pub screenshot_ui: ScreenshotUi,
280 pub config_error_notification: ConfigErrorNotification,
281 pub hotkey_overlay: HotkeyOverlay,
282 pub exit_confirm_dialog: Option<ExitConfirmDialog>,
283
284 pub debug_draw_opaque_regions: bool,
285 pub debug_draw_damage: bool,
286
287 #[cfg(feature = "dbus")]
288 pub dbus: Option<crate::dbus::DBusServers>,
289 #[cfg(feature = "dbus")]
290 pub inhibit_power_key_fd: Option<zbus::zvariant::OwnedFd>,
291
292 pub ipc_server: Option<IpcServer>,
293 pub ipc_outputs_changed: bool,
294
295 // Casts are dropped before PipeWire to prevent a double-free (yay).
296 pub casts: Vec<Cast>,
297 pub pipewire: Option<PipeWire>,
298
299 // Screencast output for each mapped window.
300 #[cfg(feature = "xdp-gnome-screencast")]
301 pub mapped_cast_output: HashMap<Window, Output>,
302}
303
304pub struct OutputState {
305 pub global: GlobalId,
306 pub frame_clock: FrameClock,
307 pub redraw_state: RedrawState,
308 pub on_demand_vrr_enabled: bool,
309 // After the last redraw, some ongoing animations still remain.
310 pub unfinished_animations_remain: bool,
311 /// Last sequence received in a vblank event.
312 pub last_drm_sequence: Option<u32>,
313 /// Sequence for frame callback throttling.
314 ///
315 /// We want to send frame callbacks for each surface at most once per monitor refresh cycle.
316 ///
317 /// Even if a surface commit resulted in empty damage to the monitor, we want to delay the next
318 /// frame callback until roughly when a VBlank would occur, had the monitor been damaged. This
319 /// is necessary to prevent clients busy-looping with frame callbacks that result in empty
320 /// damage.
321 ///
322 /// This counter wrapping-increments by 1 every time we move into the next refresh cycle, as
323 /// far as frame callback throttling is concerned. Specifically, it happens:
324 ///
325 /// 1. Upon a successful DRM frame submission. Notably, we don't wait for the VBlank here,
326 /// because the client buffers are already "latched" at the point of submission. Even if a
327 /// client submits a new buffer right away, we will wait for a VBlank to draw it, which
328 /// means that busy looping is avoided.
329 /// 2. If a frame resulted in empty damage, a timer is queued to fire roughly when a VBlank
330 /// would occur, based on the last presentation time and output refresh interval. Sequence
331 /// is incremented in that timer, before attempting a redraw or sending frame callbacks.
332 pub frame_callback_sequence: u32,
333 /// Solid color buffer for the background that we use instead of clearing to avoid damage
334 /// tracking issues and make screenshots easier.
335 pub background_buffer: SolidColorBuffer,
336 pub lock_render_state: LockRenderState,
337 pub lock_surface: Option<LockSurface>,
338 pub lock_color_buffer: SolidColorBuffer,
339 screen_transition: Option<ScreenTransition>,
340 /// Damage tracker used for the debug damage visualization.
341 pub debug_damage_tracker: OutputDamageTracker,
342}
343
344#[derive(Default)]
345pub enum RedrawState {
346 /// The compositor is idle.
347 #[default]
348 Idle,
349 /// A redraw is queued.
350 Queued,
351 /// We submitted a frame to the KMS and waiting for it to be presented.
352 WaitingForVBlank { redraw_needed: bool },
353 /// We did not submit anything to KMS and made a timer to fire at the estimated VBlank.
354 WaitingForEstimatedVBlank(RegistrationToken),
355 /// A redraw is queued on top of the above.
356 WaitingForEstimatedVBlankAndQueued(RegistrationToken),
357}
358
359pub struct PopupGrabState {
360 pub root: WlSurface,
361 pub grab: PopupGrab<State>,
362}
363
364// The surfaces here are always toplevel surfaces focused as far as niri's logic is concerned, even
365// when popup grabs are active (which means the real keyboard focus is on a popup descending from
366// that toplevel surface).
367#[derive(Debug, Clone, PartialEq, Eq)]
368pub enum KeyboardFocus {
369 // Layout is focused by default if there's nothing else to focus.
370 Layout { surface: Option<WlSurface> },
371 LayerShell { surface: WlSurface },
372 LockScreen { surface: Option<WlSurface> },
373 ScreenshotUi,
374}
375
376#[derive(Default, Clone, PartialEq)]
377pub struct PointerFocus {
378 // Output under pointer.
379 pub output: Option<Output>,
380 // Surface under pointer and its location in global coordinate space.
381 pub surface: Option<(WlSurface, Point<f64, Logical>)>,
382 // If surface belongs to a window, this is that window.
383 pub window: Option<Window>,
384 // If surface belongs to a layer surface, this is that layer surface.
385 pub layer: Option<LayerSurface>,
386}
387
388#[derive(Default)]
389pub enum LockState {
390 #[default]
391 Unlocked,
392 Locking(SessionLocker),
393 Locked(ExtSessionLockV1),
394}
395
396#[derive(PartialEq, Eq)]
397pub enum LockRenderState {
398 /// The output displays a normal session frame.
399 Unlocked,
400 /// The output displays a locked frame.
401 Locked,
402}
403
404// Not related to the one in Smithay.
405//
406// This state keeps track of when a surface last received a frame callback.
407struct SurfaceFrameThrottlingState {
408 /// Output and sequence that the frame callback was last sent at.
409 last_sent_at: RefCell<Option<(Output, u32)>>,
410}
411
412pub enum CenterCoords {
413 Separately,
414 Both,
415}
416
417#[derive(Default)]
418pub struct WindowOffscreenId(pub RefCell<Option<Id>>);
419
420impl RedrawState {
421 fn queue_redraw(self) -> Self {
422 match self {
423 RedrawState::Idle => RedrawState::Queued,
424 RedrawState::WaitingForEstimatedVBlank(token) => {
425 RedrawState::WaitingForEstimatedVBlankAndQueued(token)
426 }
427
428 // A redraw is already queued.
429 value @ (RedrawState::Queued | RedrawState::WaitingForEstimatedVBlankAndQueued(_)) => {
430 value
431 }
432
433 // We're waiting for VBlank, request a redraw afterwards.
434 RedrawState::WaitingForVBlank { .. } => RedrawState::WaitingForVBlank {
435 redraw_needed: true,
436 },
437 }
438 }
439}
440
441impl Default for SurfaceFrameThrottlingState {
442 fn default() -> Self {
443 Self {
444 last_sent_at: RefCell::new(None),
445 }
446 }
447}
448
449impl KeyboardFocus {
450 pub fn surface(&self) -> Option<&WlSurface> {
451 match self {
452 KeyboardFocus::Layout { surface } => surface.as_ref(),
453 KeyboardFocus::LayerShell { surface } => Some(surface),
454 KeyboardFocus::LockScreen { surface } => surface.as_ref(),
455 KeyboardFocus::ScreenshotUi => None,
456 }
457 }
458
459 pub fn into_surface(self) -> Option<WlSurface> {
460 match self {
461 KeyboardFocus::Layout { surface } => surface,
462 KeyboardFocus::LayerShell { surface } => Some(surface),
463 KeyboardFocus::LockScreen { surface } => surface,
464 KeyboardFocus::ScreenshotUi => None,
465 }
466 }
467
468 pub fn is_layout(&self) -> bool {
469 matches!(self, KeyboardFocus::Layout { .. })
470 }
471}
472
473pub struct State {
474 pub backend: Backend,
475 pub niri: Niri,
476}
477
478impl State {
479 pub fn new(
480 config: Config,
481 event_loop: LoopHandle<'static, State>,
482 stop_signal: LoopSignal,
483 display: Display<State>,
484 ) -> Result<Self, Box<dyn std::error::Error>> {
485 let _span = tracy_client::span!("State::new");
486
487 let config = Rc::new(RefCell::new(config));
488
489 let has_display =
490 env::var_os("WAYLAND_DISPLAY").is_some() || env::var_os("DISPLAY").is_some();
491
492 let mut backend = if has_display {
493 let winit = Winit::new(config.clone(), event_loop.clone())?;
494 Backend::Winit(winit)
495 } else {
496 let tty = Tty::new(config.clone(), event_loop.clone())
497 .context("error initializing the TTY backend")?;
498 Backend::Tty(tty)
499 };
500
501 let mut niri = Niri::new(config.clone(), event_loop, stop_signal, display, &backend);
502 backend.init(&mut niri);
503
504 let mut state = Self { backend, niri };
505
506 // Initialize some IPC server state.
507 state.ipc_keyboard_layouts_changed();
508
509 Ok(state)
510 }
511
512 pub fn refresh_and_flush_clients(&mut self) {
513 let _span = tracy_client::span!("State::refresh_and_flush_clients");
514
515 self.refresh();
516
517 self.niri.redraw_queued_outputs(&mut self.backend);
518
519 {
520 let _span = tracy_client::span!("flush_clients");
521 self.niri.display_handle.flush_clients().unwrap();
522 }
523 }
524
525 fn refresh(&mut self) {
526 let _span = tracy_client::span!("State::refresh");
527
528 // Handle commits for surfaces whose blockers cleared this cycle. This should happen before
529 // layout.refresh() since this is where these surfaces handle commits.
530 self.notify_blocker_cleared();
531
532 // These should be called periodically, before flushing the clients.
533 self.niri.layout.refresh();
534 self.niri.cursor_manager.check_cursor_image_surface_alive();
535 self.niri.refresh_pointer_outputs();
536 self.niri.popups.cleanup();
537 self.niri.global_space.refresh();
538 self.niri.refresh_idle_inhibit();
539 self.refresh_popup_grab();
540 self.update_keyboard_focus();
541 self.refresh_pointer_focus();
542 foreign_toplevel::refresh(self);
543 self.niri.refresh_window_rules();
544 self.refresh_ipc_outputs();
545 self.ipc_refresh_layout();
546
547 #[cfg(feature = "xdp-gnome-screencast")]
548 self.niri.refresh_mapped_cast_outputs();
549 }
550
551 fn notify_blocker_cleared(&mut self) {
552 let dh = self.niri.display_handle.clone();
553 while let Ok(client) = self.niri.blocker_cleared_rx.try_recv() {
554 trace!("calling blocker_cleared");
555 self.client_compositor_state(&client)
556 .blocker_cleared(self, &dh);
557 }
558 }
559
560 pub fn move_cursor(&mut self, location: Point<f64, Logical>) {
561 let under = self.niri.surface_under_and_global_space(location);
562 self.niri
563 .maybe_activate_pointer_constraint(location, &under);
564 self.niri.pointer_focus.clone_from(&under);
565
566 let pointer = &self.niri.seat.get_pointer().unwrap();
567 pointer.motion(
568 self,
569 under.surface,
570 &MotionEvent {
571 location,
572 serial: SERIAL_COUNTER.next_serial(),
573 time: get_monotonic_time().as_millis() as u32,
574 },
575 );
576 pointer.frame(self);
577
578 // We moved the pointer, show it.
579 self.niri.pointer_hidden = false;
580
581 // FIXME: granular
582 self.niri.queue_redraw_all();
583 }
584
585 /// Moves cursor within the specified rectangle, only adjusting coordinates if needed.
586 fn move_cursor_to_rect(&mut self, rect: Rectangle<f64, Logical>, mode: CenterCoords) -> bool {
587 let pointer = &self.niri.seat.get_pointer().unwrap();
588 let cur_loc = pointer.current_location();
589 let x_in_bound = cur_loc.x >= rect.loc.x && cur_loc.x <= rect.loc.x + rect.size.w;
590 let y_in_bound = cur_loc.y >= rect.loc.y && cur_loc.y <= rect.loc.y + rect.size.h;
591
592 let p = match mode {
593 CenterCoords::Separately => {
594 if x_in_bound && y_in_bound {
595 return false;
596 } else if y_in_bound {
597 // adjust x
598 Point::from((rect.loc.x + rect.size.w / 2.0, cur_loc.y))
599 } else if x_in_bound {
600 // adjust y
601 Point::from((cur_loc.x, rect.loc.y + rect.size.h / 2.0))
602 } else {
603 // adjust x and y
604 center_f64(rect)
605 }
606 }
607 CenterCoords::Both => {
608 if x_in_bound && y_in_bound {
609 return false;
610 } else {
611 // adjust x and y
612 center_f64(rect)
613 }
614 }
615 };
616
617 self.move_cursor(p);
618 true
619 }
620
621 pub fn move_cursor_to_focused_tile(&mut self, mode: CenterCoords) -> bool {
622 if !self.niri.keyboard_focus.is_layout() {
623 return false;
624 }
625
626 if self.niri.tablet_cursor_location.is_some() {
627 return false;
628 }
629
630 let Some(output) = self.niri.layout.active_output() else {
631 return false;
632 };
633 let output = output.clone();
634 let monitor = self.niri.layout.monitor_for_output(&output).unwrap();
635
636 let mut rv = false;
637 let rect = monitor.active_tile_visual_rectangle();
638
639 if let Some(rect) = rect {
640 let output_geo = self.niri.global_space.output_geometry(&output).unwrap();
641 let mut rect = rect;
642 rect.loc += output_geo.loc.to_f64();
643 rv = self.move_cursor_to_rect(rect, mode);
644 }
645
646 rv
647 }
648
649 pub fn maybe_warp_cursor_to_focus(&mut self) -> bool {
650 if !self.niri.config.borrow().input.warp_mouse_to_focus {
651 return false;
652 }
653
654 self.move_cursor_to_focused_tile(CenterCoords::Separately)
655 }
656
657 pub fn maybe_warp_cursor_to_focus_centered(&mut self) -> bool {
658 if !self.niri.config.borrow().input.warp_mouse_to_focus {
659 return false;
660 }
661
662 self.move_cursor_to_focused_tile(CenterCoords::Both)
663 }
664
665 pub fn refresh_pointer_focus(&mut self) {
666 let _span = tracy_client::span!("Niri::refresh_pointer_focus");
667
668 let pointer = &self.niri.seat.get_pointer().unwrap();
669 let location = pointer.current_location();
670
671 if !self.niri.is_locked() && !self.niri.screenshot_ui.is_open() {
672 // Don't refresh cursor focus during transitions.
673 if let Some((output, _)) = self.niri.output_under(location) {
674 let monitor = self.niri.layout.monitor_for_output(output).unwrap();
675 if monitor.are_transitions_ongoing() {
676 return;
677 }
678 }
679 }
680
681 if !self.update_pointer_focus() {
682 return;
683 }
684
685 pointer.frame(self);
686 // FIXME: granular
687 self.niri.queue_redraw_all();
688 }
689
690 pub fn update_pointer_focus(&mut self) -> bool {
691 let _span = tracy_client::span!("Niri::update_pointer_focus");
692
693 let pointer = &self.niri.seat.get_pointer().unwrap();
694 let location = pointer.current_location();
695 let under = if self.niri.pointer_hidden {
696 PointerFocus::default()
697 } else {
698 self.niri.surface_under_and_global_space(location)
699 };
700
701 // We're not changing the global cursor location here, so if the focus did not change, then
702 // nothing changed.
703 if self.niri.pointer_focus == under {
704 return false;
705 }
706
707 self.niri
708 .maybe_activate_pointer_constraint(location, &under);
709
710 self.niri.pointer_focus.clone_from(&under);
711
712 pointer.motion(
713 self,
714 under.surface,
715 &MotionEvent {
716 location,
717 serial: SERIAL_COUNTER.next_serial(),
718 time: get_monotonic_time().as_millis() as u32,
719 },
720 );
721
722 true
723 }
724
725 pub fn move_cursor_to_output(&mut self, output: &Output) {
726 let geo = self.niri.global_space.output_geometry(output).unwrap();
727 self.move_cursor(center(geo).to_f64());
728 }
729
730 pub fn refresh_popup_grab(&mut self) {
731 let keyboard_grabbed = self.niri.seat.input_method().keyboard_grabbed();
732
733 if let Some(grab) = &mut self.niri.popup_grab {
734 if grab.grab.has_ended() {
735 self.niri.popup_grab = None;
736 } else if keyboard_grabbed {
737 // HACK: remove popup grab if IME grabbed the keyboard, because we can't yet do
738 // popup grabs together with an IME grab.
739 // FIXME: do this properly.
740 grab.grab.ungrab(PopupUngrabStrategy::All);
741 self.niri.seat.get_pointer().unwrap().unset_grab(
742 self,
743 SERIAL_COUNTER.next_serial(),
744 get_monotonic_time().as_millis() as u32,
745 );
746 self.niri.popup_grab = None;
747 }
748 }
749 }
750
751 pub fn update_keyboard_focus(&mut self) {
752 // Clean up on-demand layer surface focus if necessary.
753 if let Some(surface) = &self.niri.layer_shell_on_demand_focus {
754 // Still alive and has on-demand interactivity.
755 let good = surface.alive()
756 && surface.cached_state().keyboard_interactivity
757 == wlr_layer::KeyboardInteractivity::OnDemand;
758 if !good {
759 self.niri.layer_shell_on_demand_focus = None;
760 }
761 }
762
763 // Compute the current focus.
764 let focus = if self.niri.is_locked() {
765 KeyboardFocus::LockScreen {
766 surface: self.niri.lock_surface_focus(),
767 }
768 } else if self.niri.screenshot_ui.is_open() {
769 KeyboardFocus::ScreenshotUi
770 } else if let Some(output) = self.niri.layout.active_output() {
771 let mon = self.niri.layout.monitor_for_output(output).unwrap();
772 let layers = layer_map_for_output(output);
773
774 // Explicitly check for layer-shell popup grabs here, our keyboard focus will stay on
775 // the root layer surface while it has grabs.
776 let layer_grab = self.niri.popup_grab.as_ref().and_then(|g| {
777 layers
778 .layer_for_surface(&g.root, WindowSurfaceType::TOPLEVEL)
779 .map(|l| (&g.root, l.layer()))
780 });
781 let grab_on_layer = |layer: Layer| {
782 layer_grab
783 .and_then(move |(s, l)| if l == layer { Some(s.clone()) } else { None })
784 .map(|surface| KeyboardFocus::LayerShell { surface })
785 };
786
787 let layout_focus = || {
788 self.niri
789 .layout
790 .focus()
791 .map(|win| win.toplevel().wl_surface().clone())
792 .map(|surface| KeyboardFocus::Layout {
793 surface: Some(surface),
794 })
795 };
796 let layer_focus = |surface: &LayerSurface| {
797 let can_receive_exclusive_focus = surface.cached_state().keyboard_interactivity
798 == wlr_layer::KeyboardInteractivity::Exclusive;
799 let is_on_demand_surface =
800 Some(surface) == self.niri.layer_shell_on_demand_focus.as_ref();
801
802 (can_receive_exclusive_focus || is_on_demand_surface)
803 .then(|| surface.wl_surface().clone())
804 .map(|surface| KeyboardFocus::LayerShell { surface })
805 };
806 let on_d_focus = |surface: &LayerSurface| {
807 let is_on_demand_surface =
808 Some(surface) == self.niri.layer_shell_on_demand_focus.as_ref();
809 is_on_demand_surface
810 .then(|| surface.wl_surface().clone())
811 .map(|surface| KeyboardFocus::LayerShell { surface })
812 };
813
814 let mut surface = grab_on_layer(Layer::Overlay);
815 // FIXME: we shouldn't prioritize the top layer grabs over regular overlay input or a
816 // fullscreen layout window. This will need tracking in grab() to avoid handing it out
817 // in the first place. Or a better way to structure this code.
818 surface = surface.or_else(|| grab_on_layer(Layer::Top));
819
820 surface = surface.or_else(|| layers.layers_on(Layer::Overlay).find_map(layer_focus));
821
822 if mon.render_above_top_layer() {
823 surface = surface.or_else(layout_focus);
824 surface = surface.or_else(|| layers.layers_on(Layer::Top).find_map(layer_focus));
825 } else {
826 surface = surface.or_else(|| layers.layers_on(Layer::Top).find_map(layer_focus));
827 surface = surface.or_else(layout_focus);
828 }
829
830 // Bottom and background layers can receive on-demand focus only.
831 surface = surface.or_else(|| layers.layers_on(Layer::Bottom).find_map(on_d_focus));
832 surface = surface.or_else(|| layers.layers_on(Layer::Background).find_map(on_d_focus));
833
834 surface.unwrap_or(KeyboardFocus::Layout { surface: None })
835 } else {
836 KeyboardFocus::Layout { surface: None }
837 };
838
839 let keyboard = self.niri.seat.get_keyboard().unwrap();
840 if self.niri.keyboard_focus != focus {
841 trace!(
842 "keyboard focus changed from {:?} to {:?}",
843 self.niri.keyboard_focus,
844 focus
845 );
846
847 // Tell the windows their new focus state for window rule purposes.
848 if let KeyboardFocus::Layout {
849 surface: Some(surface),
850 } = &self.niri.keyboard_focus
851 {
852 if let Some((mapped, _)) = self.niri.layout.find_window_and_output_mut(surface) {
853 mapped.set_is_focused(false);
854 }
855 }
856 if let KeyboardFocus::Layout {
857 surface: Some(surface),
858 } = &focus
859 {
860 if let Some((mapped, _)) = self.niri.layout.find_window_and_output_mut(surface) {
861 mapped.set_is_focused(true);
862 }
863 }
864
865 if let Some(grab) = self.niri.popup_grab.as_mut() {
866 if Some(&grab.root) != focus.surface() {
867 trace!(
868 "grab root {:?} is not the new focus {:?}, ungrabbing",
869 grab.root,
870 focus
871 );
872
873 grab.grab.ungrab(PopupUngrabStrategy::All);
874 keyboard.unset_grab(self);
875 self.niri.seat.get_pointer().unwrap().unset_grab(
876 self,
877 SERIAL_COUNTER.next_serial(),
878 get_monotonic_time().as_millis() as u32,
879 );
880 self.niri.popup_grab = None;
881 }
882 }
883
884 if self.niri.config.borrow().input.keyboard.track_layout == TrackLayout::Window {
885 let current_layout =
886 keyboard.with_xkb_state(self, |context| context.active_layout());
887
888 let mut new_layout = current_layout;
889 // Store the currently active layout for the surface.
890 if let Some(current_focus) = self.niri.keyboard_focus.surface() {
891 with_states(current_focus, |data| {
892 let cell = data
893 .data_map
894 .get_or_insert::<Cell<KeyboardLayout>, _>(Cell::default);
895 cell.set(current_layout);
896 });
897 }
898
899 if let Some(focus) = focus.surface() {
900 new_layout = with_states(focus, |data| {
901 let cell = data.data_map.get_or_insert::<Cell<KeyboardLayout>, _>(|| {
902 // The default layout is effectively the first layout in the
903 // keymap, so use it for new windows.
904 Cell::new(KeyboardLayout::default())
905 });
906 cell.get()
907 });
908 }
909 if new_layout != current_layout && focus.surface().is_some() {
910 keyboard.set_focus(self, None, SERIAL_COUNTER.next_serial());
911 keyboard.with_xkb_state(self, |mut context| {
912 context.set_layout(new_layout);
913 });
914
915 if let Some(server) = &self.niri.ipc_server {
916 server.keyboard_layout_switched(new_layout.0 as u8);
917 }
918 }
919 }
920
921 self.niri.keyboard_focus.clone_from(&focus);
922 keyboard.set_focus(self, focus.into_surface(), SERIAL_COUNTER.next_serial());
923
924 // FIXME: can be more granular.
925 self.niri.queue_redraw_all();
926 }
927 }
928
929 pub fn reload_config(&mut self, path: PathBuf) {
930 let _span = tracy_client::span!("State::reload_config");
931
932 let mut config = match Config::load(&path) {
933 Ok(config) => config,
934 Err(err) => {
935 warn!("{:?}", err.context("error loading config"));
936 self.niri.config_error_notification.show();
937 self.niri.queue_redraw_all();
938 return;
939 }
940 };
941
942 self.niri.config_error_notification.hide();
943
944 // Find & orphan removed named workspaces.
945 let mut removed_workspaces: Vec<String> = vec![];
946 for ws in &self.niri.config.borrow().workspaces {
947 if !config.workspaces.iter().any(|w| w.name == ws.name) {
948 removed_workspaces.push(ws.name.0.clone());
949 }
950 }
951 for name in removed_workspaces {
952 self.niri.layout.unname_workspace(&name);
953 }
954
955 self.niri.layout.update_config(&config);
956
957 // Create new named workspaces.
958 for ws_config in &config.workspaces {
959 self.niri.layout.ensure_named_workspace(ws_config);
960 }
961
962 let slowdown = if config.animations.off {
963 0.
964 } else {
965 config.animations.slowdown.clamp(0., 100.)
966 };
967 animation::ANIMATION_SLOWDOWN.store(slowdown, Ordering::Relaxed);
968
969 *CHILD_ENV.write().unwrap() = mem::take(&mut config.environment);
970
971 let mut reload_xkb = None;
972 let mut libinput_config_changed = false;
973 let mut output_config_changed = false;
974 let mut preserved_output_config = None;
975 let mut window_rules_changed = false;
976 let mut debug_config_changed = false;
977 let mut shaders_changed = false;
978 let mut old_config = self.niri.config.borrow_mut();
979
980 // Reload the cursor.
981 if config.cursor != old_config.cursor {
982 self.niri
983 .cursor_manager
984 .reload(&config.cursor.xcursor_theme, config.cursor.xcursor_size);
985 self.niri.cursor_texture_cache.clear();
986 }
987
988 // We need &mut self to reload the xkb config, so just store it here.
989 if config.input.keyboard.xkb != old_config.input.keyboard.xkb {
990 reload_xkb = Some(config.input.keyboard.xkb.clone());
991 }
992
993 // Reload the repeat info.
994 if config.input.keyboard.repeat_rate != old_config.input.keyboard.repeat_rate
995 || config.input.keyboard.repeat_delay != old_config.input.keyboard.repeat_delay
996 {
997 let keyboard = self.niri.seat.get_keyboard().unwrap();
998 keyboard.change_repeat_info(
999 config.input.keyboard.repeat_rate.into(),
1000 config.input.keyboard.repeat_delay.into(),
1001 );
1002 }
1003
1004 if config.input.touchpad != old_config.input.touchpad
1005 || config.input.mouse != old_config.input.mouse
1006 || config.input.trackpoint != old_config.input.trackpoint
1007 {
1008 libinput_config_changed = true;
1009 }
1010
1011 if config.outputs != self.niri.config_file_output_config {
1012 output_config_changed = true;
1013 self.niri
1014 .config_file_output_config
1015 .clone_from(&config.outputs);
1016 } else {
1017 // Output config did not change from the last disk load, so we need to preserve the
1018 // transient changes.
1019 preserved_output_config = Some(mem::take(&mut old_config.outputs));
1020 }
1021
1022 if config.binds != old_config.binds {
1023 self.niri.hotkey_overlay.on_hotkey_config_updated();
1024 self.niri.mods_with_wheel_binds =
1025 mods_with_wheel_binds(self.backend.mod_key(), &config.binds);
1026 self.niri.mods_with_finger_scroll_binds =
1027 mods_with_finger_scroll_binds(self.backend.mod_key(), &config.binds);
1028 }
1029
1030 if config.window_rules != old_config.window_rules {
1031 window_rules_changed = true;
1032 }
1033
1034 if config.animations.window_resize.custom_shader
1035 != old_config.animations.window_resize.custom_shader
1036 {
1037 let src = config.animations.window_resize.custom_shader.as_deref();
1038 self.backend.with_primary_renderer(|renderer| {
1039 shaders::set_custom_resize_program(renderer, src);
1040 });
1041 shaders_changed = true;
1042 }
1043
1044 if config.animations.window_close.custom_shader
1045 != old_config.animations.window_close.custom_shader
1046 {
1047 let src = config.animations.window_close.custom_shader.as_deref();
1048 self.backend.with_primary_renderer(|renderer| {
1049 shaders::set_custom_close_program(renderer, src);
1050 });
1051 shaders_changed = true;
1052 }
1053
1054 if config.animations.window_open.custom_shader
1055 != old_config.animations.window_open.custom_shader
1056 {
1057 let src = config.animations.window_open.custom_shader.as_deref();
1058 self.backend.with_primary_renderer(|renderer| {
1059 shaders::set_custom_open_program(renderer, src);
1060 });
1061 shaders_changed = true;
1062 }
1063
1064 if config.debug != old_config.debug {
1065 debug_config_changed = true;
1066 }
1067
1068 *old_config = config;
1069
1070 if let Some(outputs) = preserved_output_config {
1071 old_config.outputs = outputs;
1072 }
1073
1074 // Release the borrow.
1075 drop(old_config);
1076
1077 // Now with a &mut self we can reload the xkb config.
1078 if let Some(xkb) = reload_xkb {
1079 let keyboard = self.niri.seat.get_keyboard().unwrap();
1080 if let Err(err) = keyboard.set_xkb_config(self, xkb.to_xkb_config()) {
1081 warn!("error updating xkb config: {err:?}");
1082 }
1083
1084 self.ipc_keyboard_layouts_changed();
1085 }
1086
1087 if libinput_config_changed {
1088 let config = self.niri.config.borrow();
1089 for mut device in self.niri.devices.iter().cloned() {
1090 apply_libinput_settings(&config.input, &mut device);
1091 }
1092 }
1093
1094 if output_config_changed {
1095 self.reload_output_config();
1096 }
1097
1098 if debug_config_changed {
1099 self.backend.on_debug_config_changed();
1100 }
1101
1102 if window_rules_changed {
1103 self.niri.recompute_window_rules();
1104 }
1105
1106 if shaders_changed {
1107 self.niri.layout.update_shaders();
1108 }
1109
1110 // Can't really update xdg-decoration settings since we have to hide the globals for CSD
1111 // due to the SDL2 bug... I don't imagine clients are prepared for the xdg-decoration
1112 // global suddenly appearing? Either way, right now it's live-reloaded in a sense that new
1113 // clients will use the new xdg-decoration setting.
1114
1115 self.niri.queue_redraw_all();
1116 }
1117
1118 pub fn reload_output_config(&mut self) {
1119 let mut resized_outputs = vec![];
1120 let mut recolored_outputs = vec![];
1121
1122 for output in self.niri.global_space.outputs() {
1123 let name = output.name();
1124 let config = self.niri.config.borrow_mut();
1125 let config = config.outputs.find(&name);
1126
1127 let scale = config
1128 .and_then(|c| c.scale)
1129 .map(|s| s.0)
1130 .unwrap_or_else(|| {
1131 let size_mm = output.physical_properties().size;
1132 let resolution = output.current_mode().unwrap().size;
1133 guess_monitor_scale(size_mm, resolution)
1134 });
1135 let scale = closest_representable_scale(scale.clamp(0.1, 10.));
1136
1137 let mut transform = config
1138 .map(|c| ipc_transform_to_smithay(c.transform))
1139 .unwrap_or(Transform::Normal);
1140 // FIXME: fix winit damage on other transforms.
1141 if name == "winit" {
1142 transform = Transform::Flipped180;
1143 }
1144
1145 if output.current_scale().fractional_scale() != scale
1146 || output.current_transform() != transform
1147 {
1148 output.change_current_state(
1149 None,
1150 Some(transform),
1151 Some(output::Scale::Fractional(scale)),
1152 None,
1153 );
1154 self.niri.ipc_outputs_changed = true;
1155 resized_outputs.push(output.clone());
1156 }
1157
1158 let mut background_color = config
1159 .map(|c| c.background_color)
1160 .unwrap_or(DEFAULT_BACKGROUND_COLOR)
1161 .to_array_unpremul();
1162 background_color[3] = 1.;
1163 let background_color = Color32F::from(background_color);
1164
1165 if let Some(state) = self.niri.output_state.get_mut(output) {
1166 if state.background_buffer.color() != background_color {
1167 state.background_buffer.set_color(background_color);
1168 recolored_outputs.push(output.clone());
1169 }
1170 }
1171 }
1172
1173 for output in resized_outputs {
1174 self.niri.output_resized(&output);
1175 }
1176
1177 for output in recolored_outputs {
1178 self.niri.queue_redraw(&output);
1179 }
1180
1181 self.backend.on_output_config_changed(&mut self.niri);
1182
1183 self.niri.reposition_outputs(None);
1184
1185 if let Some(touch) = self.niri.seat.get_touch() {
1186 touch.cancel(self);
1187 }
1188
1189 let config = self.niri.config.borrow().outputs.clone();
1190 self.niri.output_management_state.on_config_changed(config);
1191 }
1192
1193 pub fn apply_transient_output_config(&mut self, name: &str, action: niri_ipc::OutputAction) {
1194 {
1195 let mut config = self.niri.config.borrow_mut();
1196 let config = if let Some(config) = config.outputs.find_mut(name) {
1197 config
1198 } else {
1199 config.outputs.0.push(niri_config::Output {
1200 name: String::from(name),
1201 ..Default::default()
1202 });
1203 config.outputs.0.last_mut().unwrap()
1204 };
1205
1206 match action {
1207 niri_ipc::OutputAction::Off => config.off = true,
1208 niri_ipc::OutputAction::On => config.off = false,
1209 niri_ipc::OutputAction::Mode { mode } => {
1210 config.mode = match mode {
1211 niri_ipc::ModeToSet::Automatic => None,
1212 niri_ipc::ModeToSet::Specific(mode) => Some(mode),
1213 }
1214 }
1215 niri_ipc::OutputAction::Scale { scale } => {
1216 config.scale = match scale {
1217 niri_ipc::ScaleToSet::Automatic => None,
1218 niri_ipc::ScaleToSet::Specific(scale) => Some(FloatOrInt(scale)),
1219 }
1220 }
1221 niri_ipc::OutputAction::Transform { transform } => config.transform = transform,
1222 niri_ipc::OutputAction::Position { position } => {
1223 config.position = match position {
1224 niri_ipc::PositionToSet::Automatic => None,
1225 niri_ipc::PositionToSet::Specific(position) => {
1226 Some(niri_config::Position {
1227 x: position.x,
1228 y: position.y,
1229 })
1230 }
1231 }
1232 }
1233 niri_ipc::OutputAction::Vrr { vrr } => {
1234 config.variable_refresh_rate = if vrr.vrr {
1235 Some(niri_config::Vrr {
1236 on_demand: vrr.on_demand,
1237 })
1238 } else {
1239 None
1240 }
1241 }
1242 }
1243 }
1244
1245 self.reload_output_config();
1246 }
1247
1248 pub fn refresh_ipc_outputs(&mut self) {
1249 if !self.niri.ipc_outputs_changed {
1250 return;
1251 }
1252 self.niri.ipc_outputs_changed = false;
1253
1254 let _span = tracy_client::span!("State::refresh_ipc_outputs");
1255
1256 for ipc_output in self.backend.ipc_outputs().lock().unwrap().values_mut() {
1257 let logical = self
1258 .niri
1259 .global_space
1260 .outputs()
1261 .find(|output| output.name() == ipc_output.name)
1262 .map(logical_output);
1263 ipc_output.logical = logical;
1264 }
1265
1266 #[cfg(feature = "dbus")]
1267 self.niri.on_ipc_outputs_changed();
1268
1269 let new_config = self.backend.ipc_outputs().lock().unwrap().clone();
1270 self.niri.output_management_state.notify_changes(new_config);
1271 }
1272
1273 pub fn open_screenshot_ui(&mut self) {
1274 if self.niri.is_locked() || self.niri.screenshot_ui.is_open() {
1275 return;
1276 }
1277
1278 let default_output = self
1279 .niri
1280 .output_under_cursor()
1281 .or_else(|| self.niri.layout.active_output().cloned());
1282 let Some(default_output) = default_output else {
1283 return;
1284 };
1285
1286 self.niri.update_render_elements(None);
1287
1288 let Some(screenshots) = self
1289 .backend
1290 .with_primary_renderer(|renderer| self.niri.capture_screenshots(renderer).collect())
1291 else {
1292 return;
1293 };
1294
1295 // Now that we captured the screenshots, clear grabs like drag-and-drop, etc.
1296 self.niri.seat.get_pointer().unwrap().unset_grab(
1297 self,
1298 SERIAL_COUNTER.next_serial(),
1299 get_monotonic_time().as_millis() as u32,
1300 );
1301
1302 self.backend.with_primary_renderer(|renderer| {
1303 self.niri
1304 .screenshot_ui
1305 .open(renderer, screenshots, default_output)
1306 });
1307
1308 self.niri
1309 .cursor_manager
1310 .set_cursor_image(CursorImageStatus::Named(CursorIcon::Crosshair));
1311 self.niri.queue_redraw_all();
1312 }
1313
1314 #[cfg(feature = "xdp-gnome-screencast")]
1315 pub fn on_pw_msg(&mut self, msg: PwToNiri) {
1316 match msg {
1317 PwToNiri::StopCast { session_id } => self.niri.stop_cast(session_id),
1318 PwToNiri::Redraw(target) => match target {
1319 CastTarget::Output(weak) => {
1320 if let Some(output) = weak.upgrade() {
1321 self.niri.queue_redraw(&output);
1322 }
1323 }
1324 CastTarget::Window { id } => {
1325 self.backend.with_primary_renderer(|renderer| {
1326 // FIXME: target presentation time at the time of window commit?
1327 self.niri
1328 .render_window_for_screen_cast(renderer, id, get_monotonic_time());
1329 });
1330 }
1331 },
1332 }
1333 }
1334
1335 #[cfg(feature = "xdp-gnome-screencast")]
1336 pub fn on_screen_cast_msg(&mut self, msg: ScreenCastToNiri) {
1337 use crate::dbus::mutter_screen_cast::StreamTargetId;
1338
1339 match msg {
1340 ScreenCastToNiri::StartCast {
1341 session_id,
1342 target,
1343 cursor_mode,
1344 signal_ctx,
1345 } => {
1346 let _span = tracy_client::span!("StartCast");
1347
1348 debug!(session_id, "StartCast");
1349
1350 let gbm = match self.backend.gbm_device() {
1351 Some(gbm) => gbm,
1352 None => {
1353 debug!("no GBM device available");
1354 return;
1355 }
1356 };
1357
1358 let Some(pw) = &self.niri.pipewire else {
1359 error!("screencasting must be disabled if PipeWire is missing");
1360 return;
1361 };
1362
1363 let (target, size, refresh, alpha) = match target {
1364 StreamTargetId::Output { name } => {
1365 let global_space = &self.niri.global_space;
1366 let output = global_space.outputs().find(|out| out.name() == name);
1367 let Some(output) = output else {
1368 warn!("error starting screencast: requested output is missing");
1369 self.niri.stop_cast(session_id);
1370 return;
1371 };
1372
1373 let mode = output.current_mode().unwrap();
1374 let transform = output.current_transform();
1375 let size = transform.transform_size(mode.size);
1376 let refresh = mode.refresh as u32;
1377 (CastTarget::Output(output.downgrade()), size, refresh, false)
1378 }
1379 StreamTargetId::Window { id } => {
1380 let mut window = None;
1381 self.niri.layout.with_windows(|mapped, _, _| {
1382 if mapped.id().get() != id {
1383 return;
1384 }
1385
1386 window = Some(mapped.window.clone());
1387 });
1388
1389 let Some(window) = window else {
1390 warn!("error starting screencast: requested window is missing");
1391 self.niri.stop_cast(session_id);
1392 return;
1393 };
1394
1395 // Use the cached output since it will be present even if the output was
1396 // currently disconnected.
1397 let Some(output) = self.niri.mapped_cast_output.get(&window) else {
1398 warn!("error starting screencast: requested window is missing");
1399 self.niri.stop_cast(session_id);
1400 return;
1401 };
1402
1403 let scale = Scale::from(output.current_scale().fractional_scale());
1404 let bbox = window.bbox_with_popups().to_physical_precise_up(scale);
1405 let refresh = output.current_mode().unwrap().refresh as u32;
1406
1407 (CastTarget::Window { id }, bbox.size, refresh, true)
1408 }
1409 };
1410
1411 let render_formats = self
1412 .backend
1413 .with_primary_renderer(|renderer| {
1414 renderer.egl_context().dmabuf_render_formats().clone()
1415 })
1416 .unwrap_or_default();
1417
1418 let res = pw.start_cast(
1419 gbm,
1420 render_formats,
1421 session_id,
1422 target,
1423 size,
1424 refresh,
1425 alpha,
1426 cursor_mode,
1427 signal_ctx,
1428 );
1429 match res {
1430 Ok(cast) => {
1431 self.niri.casts.push(cast);
1432 }
1433 Err(err) => {
1434 warn!("error starting screencast: {err:?}");
1435 self.niri.stop_cast(session_id);
1436 }
1437 }
1438 }
1439 ScreenCastToNiri::StopCast { session_id } => self.niri.stop_cast(session_id),
1440 }
1441 }
1442
1443 #[cfg(feature = "dbus")]
1444 pub fn on_screen_shot_msg(
1445 &mut self,
1446 to_screenshot: &async_channel::Sender<NiriToScreenshot>,
1447 msg: ScreenshotToNiri,
1448 ) {
1449 let ScreenshotToNiri::TakeScreenshot { include_cursor } = msg;
1450 let _span = tracy_client::span!("TakeScreenshot");
1451
1452 let rv = self.backend.with_primary_renderer(|renderer| {
1453 let on_done = {
1454 let to_screenshot = to_screenshot.clone();
1455 move |path| {
1456 let msg = NiriToScreenshot::ScreenshotResult(Some(path));
1457 if let Err(err) = to_screenshot.send_blocking(msg) {
1458 warn!("error sending path to screenshot: {err:?}");
1459 }
1460 }
1461 };
1462
1463 let res = self
1464 .niri
1465 .screenshot_all_outputs(renderer, include_cursor, on_done);
1466
1467 if let Err(err) = res {
1468 warn!("error taking a screenshot: {err:?}");
1469
1470 let msg = NiriToScreenshot::ScreenshotResult(None);
1471 if let Err(err) = to_screenshot.send_blocking(msg) {
1472 warn!("error sending None to screenshot: {err:?}");
1473 }
1474 }
1475 });
1476
1477 if rv.is_none() {
1478 let msg = NiriToScreenshot::ScreenshotResult(None);
1479 if let Err(err) = to_screenshot.send_blocking(msg) {
1480 warn!("error sending None to screenshot: {err:?}");
1481 }
1482 }
1483 }
1484
1485 #[cfg(feature = "dbus")]
1486 pub fn on_introspect_msg(
1487 &mut self,
1488 to_introspect: &async_channel::Sender<NiriToIntrospect>,
1489 msg: IntrospectToNiri,
1490 ) {
1491 use smithay::wayland::shell::xdg::XdgToplevelSurfaceData;
1492
1493 let IntrospectToNiri::GetWindows = msg;
1494 let _span = tracy_client::span!("GetWindows");
1495
1496 let mut windows = HashMap::new();
1497
1498 self.niri.layout.with_windows(|mapped, _, _| {
1499 let wl_surface = mapped
1500 .window
1501 .toplevel()
1502 .expect("no X11 support")
1503 .wl_surface();
1504
1505 let id = mapped.id().get();
1506 let props = with_states(wl_surface, |states| {
1507 let role = states
1508 .data_map
1509 .get::<XdgToplevelSurfaceData>()
1510 .unwrap()
1511 .lock()
1512 .unwrap();
1513
1514 gnome_shell_introspect::WindowProperties {
1515 title: role.title.clone().unwrap_or_default(),
1516 app_id: role.app_id.clone().unwrap_or_default(),
1517 }
1518 });
1519
1520 windows.insert(id, props);
1521 });
1522
1523 let msg = NiriToIntrospect::Windows(windows);
1524 if let Err(err) = to_introspect.send_blocking(msg) {
1525 warn!("error sending windows to introspect: {err:?}");
1526 }
1527 }
1528}
1529
1530impl Niri {
1531 pub fn new(
1532 config: Rc<RefCell<Config>>,
1533 event_loop: LoopHandle<'static, State>,
1534 stop_signal: LoopSignal,
1535 display: Display<State>,
1536 backend: &Backend,
1537 ) -> Self {
1538 let _span = tracy_client::span!("Niri::new");
1539
1540 let (executor, scheduler) = calloop::futures::executor().unwrap();
1541 event_loop.insert_source(executor, |_, _, _| ()).unwrap();
1542
1543 let display_handle = display.handle();
1544 let config_ = config.borrow();
1545 let config_file_output_config = config_.outputs.clone();
1546
1547 let layout = Layout::new(&config_);
1548
1549 let (blocker_cleared_tx, blocker_cleared_rx) = mpsc::channel();
1550
1551 let compositor_state = CompositorState::new_v6::<State>(&display_handle);
1552 let xdg_shell_state = XdgShellState::new_with_capabilities::<State>(
1553 &display_handle,
1554 [WmCapabilities::Fullscreen],
1555 );
1556 let xdg_decoration_state =
1557 XdgDecorationState::new_with_filter::<State, _>(&display_handle, |client| {
1558 client
1559 .get_data::<ClientState>()
1560 .unwrap()
1561 .can_view_decoration_globals
1562 });
1563 let kde_decoration_state = KdeDecorationState::new_with_filter::<State, _>(
1564 &display_handle,
1565 // If we want CSD we will hide the global.
1566 KdeDecorationsMode::Server,
1567 |client| {
1568 client
1569 .get_data::<ClientState>()
1570 .unwrap()
1571 .can_view_decoration_globals
1572 },
1573 );
1574 let layer_shell_state =
1575 WlrLayerShellState::new_with_filter::<State, _>(&display_handle, |client| {
1576 !client.get_data::<ClientState>().unwrap().restricted
1577 });
1578 let session_lock_state =
1579 SessionLockManagerState::new::<State, _>(&display_handle, |client| {
1580 !client.get_data::<ClientState>().unwrap().restricted
1581 });
1582 let shm_state = ShmState::new::<State>(
1583 &display_handle,
1584 vec![wl_shm::Format::Xbgr8888, wl_shm::Format::Abgr8888],
1585 );
1586 let output_manager_state =
1587 OutputManagerState::new_with_xdg_output::<State>(&display_handle);
1588 let dmabuf_state = DmabufState::new();
1589 let fractional_scale_manager_state =
1590 FractionalScaleManagerState::new::<State>(&display_handle);
1591 let mut seat_state = SeatState::new();
1592 let tablet_state = TabletManagerState::new::<State>(&display_handle);
1593 let pointer_gestures_state = PointerGesturesState::new::<State>(&display_handle);
1594 let relative_pointer_state = RelativePointerManagerState::new::<State>(&display_handle);
1595 let pointer_constraints_state = PointerConstraintsState::new::<State>(&display_handle);
1596 let idle_notifier_state = IdleNotifierState::new(&display_handle, event_loop.clone());
1597 let idle_inhibit_manager_state = IdleInhibitManagerState::new::<State>(&display_handle);
1598 let data_device_state = DataDeviceState::new::<State>(&display_handle);
1599 let primary_selection_state = PrimarySelectionState::new::<State>(&display_handle);
1600 let data_control_state = DataControlState::new::<State, _>(
1601 &display_handle,
1602 Some(&primary_selection_state),
1603 |client| !client.get_data::<ClientState>().unwrap().restricted,
1604 );
1605 let presentation_state =
1606 PresentationState::new::<State>(&display_handle, Monotonic::ID as u32);
1607 let security_context_state =
1608 SecurityContextState::new::<State, _>(&display_handle, |client| {
1609 !client.get_data::<ClientState>().unwrap().restricted
1610 });
1611
1612 let text_input_state = TextInputManagerState::new::<State>(&display_handle);
1613 let input_method_state =
1614 InputMethodManagerState::new::<State, _>(&display_handle, |client| {
1615 !client.get_data::<ClientState>().unwrap().restricted
1616 });
1617 let virtual_keyboard_state =
1618 VirtualKeyboardManagerState::new::<State, _>(&display_handle, |client| {
1619 !client.get_data::<ClientState>().unwrap().restricted
1620 });
1621
1622 let foreign_toplevel_state =
1623 ForeignToplevelManagerState::new::<State, _>(&display_handle, |client| {
1624 !client.get_data::<ClientState>().unwrap().restricted
1625 });
1626 let mut output_management_state =
1627 OutputManagementManagerState::new::<State, _>(&display_handle, |client| {
1628 !client.get_data::<ClientState>().unwrap().restricted
1629 });
1630 output_management_state.on_config_changed(config_.outputs.clone());
1631 let screencopy_state = ScreencopyManagerState::new::<State, _>(&display_handle, |client| {
1632 !client.get_data::<ClientState>().unwrap().restricted
1633 });
1634 let viewporter_state = ViewporterState::new::<State>(&display_handle);
1635 let xdg_foreign_state = XdgForeignState::new::<State>(&display_handle);
1636
1637 let is_tty = matches!(backend, Backend::Tty(_));
1638 let gamma_control_manager_state =
1639 GammaControlManagerState::new::<State, _>(&display_handle, move |client| {
1640 is_tty && !client.get_data::<ClientState>().unwrap().restricted
1641 });
1642 let activation_state = XdgActivationState::new::<State>(&display_handle);
1643 let mutter_x11_interop_state =
1644 MutterX11InteropManagerState::new::<State, _>(&display_handle, move |_| true);
1645
1646 let mut seat: Seat<State> = seat_state.new_wl_seat(&display_handle, backend.seat_name());
1647 seat.add_keyboard(
1648 config_.input.keyboard.xkb.to_xkb_config(),
1649 config_.input.keyboard.repeat_delay.into(),
1650 config_.input.keyboard.repeat_rate.into(),
1651 )
1652 .unwrap();
1653 seat.add_pointer();
1654
1655 let cursor_shape_manager_state = CursorShapeManagerState::new::<State>(&display_handle);
1656 let cursor_manager =
1657 CursorManager::new(&config_.cursor.xcursor_theme, config_.cursor.xcursor_size);
1658
1659 let mods_with_wheel_binds = mods_with_wheel_binds(backend.mod_key(), &config_.binds);
1660 let mods_with_finger_scroll_binds =
1661 mods_with_finger_scroll_binds(backend.mod_key(), &config_.binds);
1662
1663 let screenshot_ui = ScreenshotUi::new(config.clone());
1664 let config_error_notification = ConfigErrorNotification::new(config.clone());
1665
1666 let mut hotkey_overlay = HotkeyOverlay::new(config.clone(), backend.mod_key());
1667 if !config_.hotkey_overlay.skip_at_startup {
1668 hotkey_overlay.show();
1669 }
1670
1671 let exit_confirm_dialog = match ExitConfirmDialog::new() {
1672 Ok(x) => Some(x),
1673 Err(err) => {
1674 warn!("error creating the exit confirm dialog: {err:?}");
1675 None
1676 }
1677 };
1678
1679 event_loop
1680 .insert_source(
1681 Timer::from_duration(Duration::from_secs(1)),
1682 |_, _, state| {
1683 state.niri.send_frame_callbacks_on_fallback_timer();
1684 TimeoutAction::ToDuration(Duration::from_secs(1))
1685 },
1686 )
1687 .unwrap();
1688
1689 let socket_source = ListeningSocketSource::new_auto().unwrap();
1690 let socket_name = socket_source.socket_name().to_os_string();
1691 event_loop
1692 .insert_source(socket_source, move |client, _, state| {
1693 let config = state.niri.config.borrow();
1694 let data = Arc::new(ClientState {
1695 compositor_state: Default::default(),
1696 can_view_decoration_globals: config.prefer_no_csd,
1697 restricted: false,
1698 });
1699
1700 if let Err(err) = state.niri.display_handle.insert_client(client, data) {
1701 warn!("error inserting client: {err}");
1702 }
1703 })
1704 .unwrap();
1705
1706 let ipc_server = match IpcServer::start(&event_loop, &socket_name.to_string_lossy()) {
1707 Ok(server) => Some(server),
1708 Err(err) => {
1709 warn!("error starting IPC server: {err:?}");
1710 None
1711 }
1712 };
1713
1714 let pipewire = match PipeWire::new(&event_loop) {
1715 Ok(pipewire) => Some(pipewire),
1716 Err(err) => {
1717 warn!("error connecting to PipeWire, screencasting will not work: {err:?}");
1718 None
1719 }
1720 };
1721
1722 let display_source = Generic::new(display, Interest::READ, Mode::Level);
1723 event_loop
1724 .insert_source(display_source, |_, display, state| {
1725 // SAFETY: we don't drop the display.
1726 unsafe {
1727 display.get_mut().dispatch_clients(state).unwrap();
1728 }
1729 Ok(PostAction::Continue)
1730 })
1731 .unwrap();
1732
1733 event_loop
1734 .insert_source(
1735 Timer::from_duration(Duration::from_secs(60)),
1736 |_, _, state| {
1737 let _span = tracy_client::span!("startup timeout");
1738 state.niri.is_at_startup = false;
1739 state.niri.recompute_window_rules();
1740 TimeoutAction::Drop
1741 },
1742 )
1743 .unwrap();
1744
1745 drop(config_);
1746 Self {
1747 config,
1748 config_file_output_config,
1749
1750 event_loop,
1751 scheduler,
1752 stop_signal,
1753 socket_name,
1754 display_handle,
1755 start_time: Instant::now(),
1756 is_at_startup: true,
1757
1758 layout,
1759 global_space: Space::default(),
1760 output_state: HashMap::new(),
1761 output_by_name: HashMap::new(),
1762 unmapped_windows: HashMap::new(),
1763 root_surface: HashMap::new(),
1764 dmabuf_pre_commit_hook: HashMap::new(),
1765 blocker_cleared_tx,
1766 blocker_cleared_rx,
1767 monitors_active: true,
1768
1769 devices: HashSet::new(),
1770 tablets: HashMap::new(),
1771 touch: HashSet::new(),
1772
1773 compositor_state,
1774 xdg_shell_state,
1775 xdg_decoration_state,
1776 kde_decoration_state,
1777 layer_shell_state,
1778 session_lock_state,
1779 foreign_toplevel_state,
1780 output_management_state,
1781 screencopy_state,
1782 viewporter_state,
1783 xdg_foreign_state,
1784 text_input_state,
1785 input_method_state,
1786 virtual_keyboard_state,
1787 shm_state,
1788 output_manager_state,
1789 dmabuf_state,
1790 fractional_scale_manager_state,
1791 seat_state,
1792 tablet_state,
1793 pointer_gestures_state,
1794 relative_pointer_state,
1795 pointer_constraints_state,
1796 idle_notifier_state,
1797 idle_inhibit_manager_state,
1798 data_device_state,
1799 primary_selection_state,
1800 data_control_state,
1801 popups: PopupManager::default(),
1802 popup_grab: None,
1803 suppressed_keys: HashSet::new(),
1804 bind_cooldown_timers: HashMap::new(),
1805 bind_repeat_timer: Option::default(),
1806 presentation_state,
1807 security_context_state,
1808 gamma_control_manager_state,
1809 activation_state,
1810 mutter_x11_interop_state,
1811
1812 seat,
1813 keyboard_focus: KeyboardFocus::Layout { surface: None },
1814 layer_shell_on_demand_focus: None,
1815 idle_inhibiting_surfaces: HashSet::new(),
1816 is_fdo_idle_inhibited: Arc::new(AtomicBool::new(false)),
1817 cursor_manager,
1818 cursor_texture_cache: Default::default(),
1819 cursor_shape_manager_state,
1820 dnd_icon: None,
1821 pointer_focus: PointerFocus::default(),
1822 pointer_hidden: false,
1823 pointer_grab_ongoing: false,
1824 tablet_cursor_location: None,
1825 gesture_swipe_3f_cumulative: None,
1826 vertical_wheel_tracker: ScrollTracker::new(120),
1827 horizontal_wheel_tracker: ScrollTracker::new(120),
1828 mods_with_wheel_binds,
1829
1830 // 10 is copied from Clutter: DISCRETE_SCROLL_STEP.
1831 vertical_finger_scroll_tracker: ScrollTracker::new(10),
1832 horizontal_finger_scroll_tracker: ScrollTracker::new(10),
1833 mods_with_finger_scroll_binds,
1834
1835 lock_state: LockState::Unlocked,
1836
1837 screenshot_ui,
1838 config_error_notification,
1839 hotkey_overlay,
1840 exit_confirm_dialog,
1841
1842 debug_draw_opaque_regions: false,
1843 debug_draw_damage: false,
1844
1845 #[cfg(feature = "dbus")]
1846 dbus: None,
1847 #[cfg(feature = "dbus")]
1848 inhibit_power_key_fd: None,
1849
1850 ipc_server,
1851 ipc_outputs_changed: false,
1852
1853 pipewire,
1854 casts: vec![],
1855
1856 #[cfg(feature = "xdp-gnome-screencast")]
1857 mapped_cast_output: HashMap::new(),
1858 }
1859 }
1860
1861 #[cfg(feature = "dbus")]
1862 pub fn inhibit_power_key(&mut self) -> anyhow::Result<()> {
1863 let conn = zbus::blocking::ConnectionBuilder::system()?.build()?;
1864
1865 let message = conn.call_method(
1866 Some("org.freedesktop.login1"),
1867 "/org/freedesktop/login1",
1868 Some("org.freedesktop.login1.Manager"),
1869 "Inhibit",
1870 &("handle-power-key", "niri", "Power key handling", "block"),
1871 )?;
1872
1873 let fd = message.body()?;
1874 self.inhibit_power_key_fd = Some(fd);
1875
1876 Ok(())
1877 }
1878
1879 /// Repositions all outputs, optionally adding a new output.
1880 pub fn reposition_outputs(&mut self, new_output: Option<&Output>) {
1881 let _span = tracy_client::span!("Niri::reposition_outputs");
1882
1883 #[derive(Debug)]
1884 struct Data {
1885 output: Output,
1886 name: String,
1887 position: Option<Point<i32, Logical>>,
1888 config: Option<niri_config::Position>,
1889 }
1890
1891 let config = self.config.borrow();
1892 let mut outputs = vec![];
1893 for output in self.global_space.outputs().chain(new_output) {
1894 let name = output.name();
1895 let position = self.global_space.output_geometry(output).map(|geo| geo.loc);
1896 let config = config.outputs.find(&name).and_then(|c| c.position);
1897
1898 outputs.push(Data {
1899 output: output.clone(),
1900 name,
1901 position,
1902 config,
1903 });
1904 }
1905 drop(config);
1906
1907 for Data { output, .. } in &outputs {
1908 self.global_space.unmap_output(output);
1909 }
1910
1911 // Connectors can appear in udev in any order. If we sort by name then we get output
1912 // positioning that does not depend on the order they appeared.
1913 //
1914 // All outputs must have different (connector) names.
1915 outputs.sort_unstable_by(|a, b| Ord::cmp(&a.name, &b.name));
1916
1917 // Place all outputs with explicitly configured position first, then the unconfigured ones.
1918 outputs.sort_by_key(|d| d.config.is_none());
1919
1920 trace!(
1921 "placing outputs in order: {:?}",
1922 outputs.iter().map(|d| &d.name)
1923 );
1924
1925 for data in outputs.into_iter() {
1926 let Data {
1927 output,
1928 name,
1929 position,
1930 config,
1931 } = data;
1932
1933 let size = output_size(&output).to_i32_round();
1934
1935 let new_position = config
1936 .map(|pos| Point::from((pos.x, pos.y)))
1937 .filter(|pos| {
1938 // Ensure that the requested position does not overlap any existing output.
1939 let target_geom = Rectangle::from_loc_and_size(*pos, size);
1940
1941 let overlap = self
1942 .global_space
1943 .outputs()
1944 .map(|output| self.global_space.output_geometry(output).unwrap())
1945 .find(|geom| geom.overlaps(target_geom));
1946
1947 if let Some(overlap) = overlap {
1948 warn!(
1949 "output {name} at x={} y={} sized {}x{} \
1950 overlaps an existing output at x={} y={} sized {}x{}, \
1951 falling back to automatic placement",
1952 pos.x,
1953 pos.y,
1954 size.w,
1955 size.h,
1956 overlap.loc.x,
1957 overlap.loc.y,
1958 overlap.size.w,
1959 overlap.size.h,
1960 );
1961
1962 false
1963 } else {
1964 true
1965 }
1966 })
1967 .unwrap_or_else(|| {
1968 let x = self
1969 .global_space
1970 .outputs()
1971 .map(|output| self.global_space.output_geometry(output).unwrap())
1972 .map(|geom| geom.loc.x + geom.size.w)
1973 .max()
1974 .unwrap_or(0);
1975
1976 Point::from((x, 0))
1977 });
1978
1979 self.global_space.map_output(&output, new_position);
1980
1981 // By passing new_output as an Option, rather than mapping it into a bogus location
1982 // in global_space, we ensure that this branch always runs for it.
1983 if Some(new_position) != position {
1984 debug!(
1985 "putting output {name} at x={} y={}",
1986 new_position.x, new_position.y
1987 );
1988 output.change_current_state(None, None, None, Some(new_position));
1989 self.ipc_outputs_changed = true;
1990 self.queue_redraw(&output);
1991 }
1992 }
1993 }
1994
1995 pub fn add_output(&mut self, output: Output, refresh_interval: Option<Duration>, vrr: bool) {
1996 let global = output.create_global::<State>(&self.display_handle);
1997
1998 let name = output.name();
1999
2000 let config = self.config.borrow();
2001 let c = config.outputs.find(&name);
2002 let scale = c.and_then(|c| c.scale).map(|s| s.0).unwrap_or_else(|| {
2003 let size_mm = output.physical_properties().size;
2004 let resolution = output.current_mode().unwrap().size;
2005 guess_monitor_scale(size_mm, resolution)
2006 });
2007 let scale = closest_representable_scale(scale.clamp(0.1, 10.));
2008
2009 let mut transform = c
2010 .map(|c| ipc_transform_to_smithay(c.transform))
2011 .unwrap_or(Transform::Normal);
2012
2013 let mut background_color = c
2014 .map(|c| c.background_color)
2015 .unwrap_or(DEFAULT_BACKGROUND_COLOR)
2016 .to_array_unpremul();
2017 background_color[3] = 1.;
2018
2019 // FIXME: fix winit damage on other transforms.
2020 if name == "winit" {
2021 transform = Transform::Flipped180;
2022 }
2023 drop(config);
2024
2025 // Set scale and transform before adding to the layout since that will read the output size.
2026 output.change_current_state(
2027 None,
2028 Some(transform),
2029 Some(output::Scale::Fractional(scale)),
2030 None,
2031 );
2032
2033 self.layout.add_output(output.clone());
2034
2035 let lock_render_state = if self.is_locked() {
2036 // We haven't rendered anything yet so it's as good as locked.
2037 LockRenderState::Locked
2038 } else {
2039 LockRenderState::Unlocked
2040 };
2041
2042 let size = output_size(&output).to_i32_round();
2043 let state = OutputState {
2044 global,
2045 redraw_state: RedrawState::Idle,
2046 on_demand_vrr_enabled: false,
2047 unfinished_animations_remain: false,
2048 frame_clock: FrameClock::new(refresh_interval, vrr),
2049 last_drm_sequence: None,
2050 frame_callback_sequence: 0,
2051 background_buffer: SolidColorBuffer::new(size, background_color),
2052 lock_render_state,
2053 lock_surface: None,
2054 lock_color_buffer: SolidColorBuffer::new(size, CLEAR_COLOR_LOCKED),
2055 screen_transition: None,
2056 debug_damage_tracker: OutputDamageTracker::from_output(&output),
2057 };
2058 let rv = self.output_state.insert(output.clone(), state);
2059 assert!(rv.is_none(), "output was already tracked");
2060 let rv = self.output_by_name.insert(name, output.clone());
2061 assert!(rv.is_none(), "output was already tracked");
2062
2063 // Must be last since it will call queue_redraw(output) which needs things to be filled-in.
2064 self.reposition_outputs(Some(&output));
2065 }
2066
2067 pub fn remove_output(&mut self, output: &Output) {
2068 for layer in layer_map_for_output(output).layers() {
2069 layer.layer_surface().send_close();
2070 }
2071
2072 self.layout.remove_output(output);
2073 self.global_space.unmap_output(output);
2074 self.reposition_outputs(None);
2075 self.gamma_control_manager_state.output_removed(output);
2076
2077 let state = self.output_state.remove(output).unwrap();
2078 self.output_by_name.remove(&output.name()).unwrap();
2079
2080 match state.redraw_state {
2081 RedrawState::Idle => (),
2082 RedrawState::Queued => (),
2083 RedrawState::WaitingForVBlank { .. } => (),
2084 RedrawState::WaitingForEstimatedVBlank(token) => self.event_loop.remove(token),
2085 RedrawState::WaitingForEstimatedVBlankAndQueued(token) => self.event_loop.remove(token),
2086 }
2087
2088 #[cfg(feature = "xdp-gnome-screencast")]
2089 self.stop_casts_for_target(CastTarget::Output(output.downgrade()));
2090
2091 self.remove_screencopy_output(output);
2092
2093 // Disable the output global and remove some time later to give the clients some time to
2094 // process it.
2095 let global = state.global;
2096 self.display_handle.disable_global::<State>(global.clone());
2097 self.event_loop
2098 .insert_source(
2099 Timer::from_duration(Duration::from_secs(10)),
2100 move |_, _, state| {
2101 state
2102 .niri
2103 .display_handle
2104 .remove_global::<State>(global.clone());
2105 TimeoutAction::Drop
2106 },
2107 )
2108 .unwrap();
2109
2110 match mem::take(&mut self.lock_state) {
2111 LockState::Locking(confirmation) => {
2112 // We're locking and an output was removed, check if the requirements are now met.
2113 let all_locked = self
2114 .output_state
2115 .values()
2116 .all(|state| state.lock_render_state == LockRenderState::Locked);
2117
2118 if all_locked {
2119 let lock = confirmation.ext_session_lock().clone();
2120 confirmation.lock();
2121 self.lock_state = LockState::Locked(lock);
2122 } else {
2123 // Still waiting.
2124 self.lock_state = LockState::Locking(confirmation);
2125 }
2126 }
2127 lock_state => self.lock_state = lock_state,
2128 }
2129
2130 if self.screenshot_ui.close() {
2131 self.cursor_manager
2132 .set_cursor_image(CursorImageStatus::default_named());
2133 self.queue_redraw_all();
2134 }
2135 }
2136
2137 pub fn output_resized(&mut self, output: &Output) {
2138 let output_size = output_size(output).to_i32_round();
2139 let is_locked = self.is_locked();
2140
2141 layer_map_for_output(output).arrange();
2142 self.layout.update_output_size(output);
2143
2144 if let Some(state) = self.output_state.get_mut(output) {
2145 state.background_buffer.resize(output_size);
2146
2147 state.lock_color_buffer.resize(output_size);
2148 if is_locked {
2149 if let Some(lock_surface) = &state.lock_surface {
2150 configure_lock_surface(lock_surface, output);
2151 }
2152 }
2153 }
2154
2155 // If the output size changed with an open screenshot UI, close the screenshot UI.
2156 if let Some((old_size, old_scale, old_transform)) = self.screenshot_ui.output_size(output) {
2157 let transform = output.current_transform();
2158 let output_mode = output.current_mode().unwrap();
2159 let size = transform.transform_size(output_mode.size);
2160 let scale = output.current_scale().fractional_scale();
2161 // FIXME: scale changes and transform flips shouldn't matter but they currently do since
2162 // I haven't quite figured out how to draw the screenshot textures in
2163 // physical coordinates.
2164 if old_size != size || old_scale != scale || old_transform != transform {
2165 self.screenshot_ui.close();
2166 self.cursor_manager
2167 .set_cursor_image(CursorImageStatus::default_named());
2168 self.queue_redraw_all();
2169 return;
2170 }
2171 }
2172
2173 self.queue_redraw(output);
2174 }
2175
2176 pub fn deactivate_monitors(&mut self, backend: &mut Backend) {
2177 if !self.monitors_active {
2178 return;
2179 }
2180
2181 self.monitors_active = false;
2182 backend.set_monitors_active(false);
2183 }
2184
2185 pub fn activate_monitors(&mut self, backend: &mut Backend) {
2186 if self.monitors_active {
2187 return;
2188 }
2189
2190 self.monitors_active = true;
2191 backend.set_monitors_active(true);
2192
2193 self.queue_redraw_all();
2194 }
2195
2196 pub fn output_under(&self, pos: Point<f64, Logical>) -> Option<(&Output, Point<f64, Logical>)> {
2197 let output = self.global_space.output_under(pos).next()?;
2198 let pos_within_output = pos
2199 - self
2200 .global_space
2201 .output_geometry(output)
2202 .unwrap()
2203 .loc
2204 .to_f64();
2205
2206 Some((output, pos_within_output))
2207 }
2208
2209 /// Returns the window under the position to be activated.
2210 ///
2211 /// The cursor may be inside the window's activation region, but not within the window's input
2212 /// region.
2213 pub fn window_under(&self, pos: Point<f64, Logical>) -> Option<&Mapped> {
2214 if self.is_locked() || self.screenshot_ui.is_open() {
2215 return None;
2216 }
2217
2218 let (output, pos_within_output) = self.output_under(pos)?;
2219
2220 // Check if some layer-shell surface is on top.
2221 let layers = layer_map_for_output(output);
2222 let layer_under = |layer| layers.layer_under(layer, pos_within_output).is_some();
2223 if layer_under(Layer::Overlay) {
2224 return None;
2225 }
2226
2227 let mon = self.layout.monitor_for_output(output).unwrap();
2228 if !mon.render_above_top_layer() && layer_under(Layer::Top) {
2229 return None;
2230 }
2231
2232 let (window, _loc) = self.layout.window_under(output, pos_within_output)?;
2233 Some(window)
2234 }
2235
2236 /// Returns the window under the cursor to be activated.
2237 ///
2238 /// The cursor may be inside the window's activation region, but not within the window's input
2239 /// region.
2240 pub fn window_under_cursor(&self) -> Option<&Mapped> {
2241 let pos = self.seat.get_pointer().unwrap().current_location();
2242 self.window_under(pos)
2243 }
2244
2245 /// Returns the surface under cursor and its position in the global space.
2246 ///
2247 /// Pointer needs location in global space, and focused window location compatible with that
2248 /// global space. We don't have a global space for all windows, but this function converts the
2249 /// window location temporarily to the current global space.
2250 pub fn surface_under_and_global_space(&mut self, pos: Point<f64, Logical>) -> PointerFocus {
2251 let mut rv = PointerFocus::default();
2252
2253 let Some((output, pos_within_output)) = self.output_under(pos) else {
2254 return rv;
2255 };
2256 rv.output = Some(output.clone());
2257 let output_pos_in_global_space = self.global_space.output_geometry(output).unwrap().loc;
2258
2259 if self.is_locked() {
2260 let Some(state) = self.output_state.get(output) else {
2261 return rv;
2262 };
2263 let Some(surface) = state.lock_surface.as_ref() else {
2264 return rv;
2265 };
2266
2267 rv.surface = under_from_surface_tree(
2268 surface.wl_surface(),
2269 pos_within_output,
2270 // We put lock surfaces at (0, 0).
2271 (0, 0),
2272 WindowSurfaceType::ALL,
2273 )
2274 .map(|(surface, pos_within_output)| {
2275 (
2276 surface,
2277 (pos_within_output + output_pos_in_global_space).to_f64(),
2278 )
2279 });
2280
2281 return rv;
2282 }
2283
2284 if self.screenshot_ui.is_open() {
2285 return rv;
2286 }
2287
2288 let layers = layer_map_for_output(output);
2289 let layer_surface_under = |layer| {
2290 layers
2291 .layer_under(layer, pos_within_output)
2292 .and_then(|layer| {
2293 let layer_pos_within_output =
2294 layers.layer_geometry(layer).unwrap().loc.to_f64();
2295 layer
2296 .surface_under(
2297 pos_within_output - layer_pos_within_output,
2298 WindowSurfaceType::ALL,
2299 )
2300 .map(|(surface, pos_within_layer)| {
2301 (
2302 (surface, pos_within_layer.to_f64() + layer_pos_within_output),
2303 layer,
2304 )
2305 })
2306 })
2307 .map(|(s, l)| (s, (None, Some(l.clone()))))
2308 };
2309
2310 let window_under = || {
2311 self.layout
2312 .window_under(output, pos_within_output)
2313 .and_then(|(mapped, win_pos_within_output)| {
2314 let win_pos_within_output = win_pos_within_output?;
2315 let window = &mapped.window;
2316 window
2317 .surface_under(
2318 pos_within_output - win_pos_within_output,
2319 WindowSurfaceType::ALL,
2320 )
2321 .map(|(s, pos_within_window)| {
2322 (s, pos_within_window.to_f64() + win_pos_within_output)
2323 })
2324 .map(|s| (s, (Some(window.clone()), None)))
2325 })
2326 };
2327
2328 let mon = self.layout.monitor_for_output(output).unwrap();
2329
2330 let mut under = layer_surface_under(Layer::Overlay);
2331
2332 if mon.render_above_top_layer() {
2333 under = under
2334 .or_else(window_under)
2335 .or_else(|| layer_surface_under(Layer::Top));
2336 } else {
2337 under = under
2338 .or_else(|| layer_surface_under(Layer::Top))
2339 .or_else(window_under);
2340 }
2341
2342 let Some(((surface, surface_pos_within_output), (window, layer))) = under
2343 .or_else(|| layer_surface_under(Layer::Bottom))
2344 .or_else(|| layer_surface_under(Layer::Background))
2345 else {
2346 return rv;
2347 };
2348
2349 let surface_loc_in_global_space =
2350 surface_pos_within_output + output_pos_in_global_space.to_f64();
2351
2352 rv.surface = Some((surface, surface_loc_in_global_space));
2353 rv.window = window;
2354 rv.layer = layer;
2355 rv
2356 }
2357
2358 pub fn output_under_cursor(&self) -> Option<Output> {
2359 let pos = self.seat.get_pointer().unwrap().current_location();
2360 self.global_space.output_under(pos).next().cloned()
2361 }
2362
2363 pub fn output_left(&self) -> Option<Output> {
2364 let active = self.layout.active_output()?;
2365 let active_geo = self.global_space.output_geometry(active).unwrap();
2366 let extended_geo = Rectangle::from_loc_and_size(
2367 (i32::MIN / 2, active_geo.loc.y),
2368 (i32::MAX, active_geo.size.h),
2369 );
2370
2371 self.global_space
2372 .outputs()
2373 .map(|output| (output, self.global_space.output_geometry(output).unwrap()))
2374 .filter(|(_, geo)| center(*geo).x < center(active_geo).x && geo.overlaps(extended_geo))
2375 .min_by_key(|(_, geo)| center(active_geo).x - center(*geo).x)
2376 .map(|(output, _)| output)
2377 .cloned()
2378 }
2379
2380 pub fn output_right(&self) -> Option<Output> {
2381 let active = self.layout.active_output()?;
2382 let active_geo = self.global_space.output_geometry(active).unwrap();
2383 let extended_geo = Rectangle::from_loc_and_size(
2384 (i32::MIN / 2, active_geo.loc.y),
2385 (i32::MAX, active_geo.size.h),
2386 );
2387
2388 self.global_space
2389 .outputs()
2390 .map(|output| (output, self.global_space.output_geometry(output).unwrap()))
2391 .filter(|(_, geo)| center(*geo).x > center(active_geo).x && geo.overlaps(extended_geo))
2392 .min_by_key(|(_, geo)| center(*geo).x - center(active_geo).x)
2393 .map(|(output, _)| output)
2394 .cloned()
2395 }
2396
2397 pub fn output_up(&self) -> Option<Output> {
2398 let active = self.layout.active_output()?;
2399 let active_geo = self.global_space.output_geometry(active).unwrap();
2400 let extended_geo = Rectangle::from_loc_and_size(
2401 (active_geo.loc.x, i32::MIN / 2),
2402 (active_geo.size.w, i32::MAX),
2403 );
2404
2405 self.global_space
2406 .outputs()
2407 .map(|output| (output, self.global_space.output_geometry(output).unwrap()))
2408 .filter(|(_, geo)| center(*geo).y < center(active_geo).y && geo.overlaps(extended_geo))
2409 .min_by_key(|(_, geo)| center(active_geo).y - center(*geo).y)
2410 .map(|(output, _)| output)
2411 .cloned()
2412 }
2413
2414 pub fn output_by_name(&self, name: &str) -> Option<Output> {
2415 self.global_space
2416 .outputs()
2417 .find(|output| output.name().eq_ignore_ascii_case(name))
2418 .cloned()
2419 }
2420
2421 pub fn find_output_and_workspace_index(
2422 &self,
2423 workspace_reference: WorkspaceReference,
2424 ) -> Option<(Option<Output>, usize)> {
2425 let workspace_name = match workspace_reference {
2426 WorkspaceReference::Index(index) => {
2427 return Some((None, index.saturating_sub(1) as usize));
2428 }
2429 WorkspaceReference::Name(name) => name,
2430 };
2431
2432 let (target_workspace_index, target_workspace) =
2433 self.layout.find_workspace_by_name(&workspace_name)?;
2434
2435 // FIXME: when we do fixes for no connected outputs, this will need fixing too.
2436 let active_workspace = self.layout.active_workspace()?;
2437
2438 if target_workspace.current_output() == active_workspace.current_output() {
2439 return Some((None, target_workspace_index));
2440 }
2441 let target_output = target_workspace.current_output()?;
2442
2443 Some((Some(target_output.clone()), target_workspace_index))
2444 }
2445
2446 pub fn output_down(&self) -> Option<Output> {
2447 let active = self.layout.active_output()?;
2448 let active_geo = self.global_space.output_geometry(active).unwrap();
2449 let extended_geo = Rectangle::from_loc_and_size(
2450 (active_geo.loc.x, i32::MIN / 2),
2451 (active_geo.size.w, i32::MAX),
2452 );
2453
2454 self.global_space
2455 .outputs()
2456 .map(|output| (output, self.global_space.output_geometry(output).unwrap()))
2457 .filter(|(_, geo)| center(active_geo).y < center(*geo).y && geo.overlaps(extended_geo))
2458 .min_by_key(|(_, geo)| center(*geo).y - center(active_geo).y)
2459 .map(|(output, _)| output)
2460 .cloned()
2461 }
2462
2463 pub fn output_for_tablet(&self) -> Option<&Output> {
2464 let config = self.config.borrow();
2465 let map_to_output = config.input.tablet.map_to_output.as_ref();
2466 map_to_output.and_then(|name| self.output_by_name.get(name))
2467 }
2468
2469 pub fn output_for_touch(&self) -> Option<&Output> {
2470 let config = self.config.borrow();
2471 let map_to_output = config.input.touch.map_to_output.as_ref();
2472 map_to_output
2473 .and_then(|name| self.output_by_name.get(name))
2474 .or_else(|| self.global_space.outputs().next())
2475 }
2476
2477 pub fn output_for_root(&self, root: &WlSurface) -> Option<&Output> {
2478 // Check the main layout.
2479 let win_out = self.layout.find_window_and_output(root);
2480 let layout_output = win_out.map(|(_, output)| output);
2481
2482 // Check layer-shell.
2483 let has_layer_surface = |o: &&Output| {
2484 layer_map_for_output(o)
2485 .layer_for_surface(root, WindowSurfaceType::TOPLEVEL)
2486 .is_some()
2487 };
2488 let layer_shell_output = || self.layout.outputs().find(has_layer_surface);
2489
2490 layout_output.or_else(layer_shell_output)
2491 }
2492
2493 pub fn lock_surface_focus(&self) -> Option<WlSurface> {
2494 let output_under_cursor = self.output_under_cursor();
2495 let output = output_under_cursor
2496 .as_ref()
2497 .or_else(|| self.layout.active_output())
2498 .or_else(|| self.global_space.outputs().next())?;
2499
2500 let state = self.output_state.get(output)?;
2501 state.lock_surface.as_ref().map(|s| s.wl_surface()).cloned()
2502 }
2503
2504 /// Schedules an immediate redraw on all outputs if one is not already scheduled.
2505 pub fn queue_redraw_all(&mut self) {
2506 for state in self.output_state.values_mut() {
2507 state.redraw_state = mem::take(&mut state.redraw_state).queue_redraw();
2508 }
2509 }
2510
2511 /// Schedules an immediate redraw if one is not already scheduled.
2512 pub fn queue_redraw(&mut self, output: &Output) {
2513 let state = self.output_state.get_mut(output).unwrap();
2514 state.redraw_state = mem::take(&mut state.redraw_state).queue_redraw();
2515 }
2516
2517 pub fn redraw_queued_outputs(&mut self, backend: &mut Backend) {
2518 let _span = tracy_client::span!("Niri::redraw_queued_outputs");
2519
2520 while let Some((output, _)) = self.output_state.iter().find(|(_, state)| {
2521 matches!(
2522 state.redraw_state,
2523 RedrawState::Queued | RedrawState::WaitingForEstimatedVBlankAndQueued(_)
2524 )
2525 }) {
2526 trace!("redrawing output");
2527 let output = output.clone();
2528 self.redraw(backend, &output);
2529 }
2530 }
2531
2532 pub fn pointer_element<R: NiriRenderer>(
2533 &self,
2534 renderer: &mut R,
2535 output: &Output,
2536 ) -> Vec<OutputRenderElements<R>> {
2537 if self.pointer_hidden {
2538 return vec![];
2539 }
2540
2541 let _span = tracy_client::span!("Niri::pointer_element");
2542 let output_scale = output.current_scale();
2543 let output_pos = self.global_space.output_geometry(output).unwrap().loc;
2544
2545 // Check whether we need to draw the tablet cursor or the regular cursor.
2546 let pointer_pos = self
2547 .tablet_cursor_location
2548 .unwrap_or_else(|| self.seat.get_pointer().unwrap().current_location());
2549 let pointer_pos = pointer_pos - output_pos.to_f64();
2550
2551 // Get the render cursor to draw.
2552 let cursor_scale = output_scale.integer_scale();
2553 let render_cursor = self.cursor_manager.get_render_cursor(cursor_scale);
2554
2555 let output_scale = Scale::from(output.current_scale().fractional_scale());
2556
2557 let (mut pointer_elements, pointer_pos) = match render_cursor {
2558 RenderCursor::Hidden => (vec![], pointer_pos.to_physical_precise_round(output_scale)),
2559 RenderCursor::Surface { surface, hotspot } => {
2560 let pointer_pos =
2561 (pointer_pos - hotspot.to_f64()).to_physical_precise_round(output_scale);
2562
2563 let pointer_elements = render_elements_from_surface_tree(
2564 renderer,
2565 &surface,
2566 pointer_pos,
2567 output_scale,
2568 1.,
2569 Kind::Cursor,
2570 );
2571
2572 (pointer_elements, pointer_pos)
2573 }
2574 RenderCursor::Named {
2575 icon,
2576 scale,
2577 cursor,
2578 } => {
2579 let (idx, frame) = cursor.frame(self.start_time.elapsed().as_millis() as u32);
2580 let hotspot = XCursor::hotspot(frame).to_logical(scale);
2581 let pointer_pos =
2582 (pointer_pos - hotspot.to_f64()).to_physical_precise_round(output_scale);
2583
2584 let texture = self.cursor_texture_cache.get(icon, scale, &cursor, idx);
2585 let mut pointer_elements = vec![];
2586 let pointer_element = match MemoryRenderBufferRenderElement::from_buffer(
2587 renderer,
2588 pointer_pos.to_f64(),
2589 &texture,
2590 None,
2591 None,
2592 None,
2593 Kind::Cursor,
2594 ) {
2595 Ok(element) => Some(element),
2596 Err(err) => {
2597 warn!("error importing a cursor texture: {err:?}");
2598 None
2599 }
2600 };
2601 if let Some(element) = pointer_element {
2602 pointer_elements.push(OutputRenderElements::NamedPointer(element));
2603 }
2604
2605 (pointer_elements, pointer_pos)
2606 }
2607 };
2608
2609 if let Some(dnd_icon) = &self.dnd_icon {
2610 pointer_elements.extend(render_elements_from_surface_tree(
2611 renderer,
2612 dnd_icon,
2613 pointer_pos,
2614 output_scale,
2615 1.,
2616 Kind::Unspecified,
2617 ));
2618 }
2619
2620 pointer_elements
2621 }
2622
2623 pub fn refresh_pointer_outputs(&mut self) {
2624 if self.pointer_hidden {
2625 return;
2626 }
2627
2628 let _span = tracy_client::span!("Niri::refresh_pointer_outputs");
2629
2630 // Check whether we need to draw the tablet cursor or the regular cursor.
2631 let pointer_pos = self
2632 .tablet_cursor_location
2633 .unwrap_or_else(|| self.seat.get_pointer().unwrap().current_location());
2634
2635 match self.cursor_manager.cursor_image().clone() {
2636 CursorImageStatus::Surface(ref surface) => {
2637 let hotspot = with_states(surface, |states| {
2638 states
2639 .data_map
2640 .get::<Mutex<CursorImageAttributes>>()
2641 .unwrap()
2642 .lock()
2643 .unwrap()
2644 .hotspot
2645 });
2646
2647 let surface_pos = pointer_pos.to_i32_round() - hotspot;
2648 let bbox = bbox_from_surface_tree(surface, surface_pos);
2649
2650 let dnd = self
2651 .dnd_icon
2652 .as_ref()
2653 .map(|surface| (surface, bbox_from_surface_tree(surface, surface_pos)));
2654
2655 // FIXME we basically need to pick the largest scale factor across the overlapping
2656 // outputs, this is how it's usually done in clients as well.
2657 let mut cursor_scale = 1.;
2658 let mut cursor_transform = Transform::Normal;
2659 let mut dnd_scale = 1.;
2660 let mut dnd_transform = Transform::Normal;
2661 for output in self.global_space.outputs() {
2662 let geo = self.global_space.output_geometry(output).unwrap();
2663
2664 // Compute pointer surface overlap.
2665 if let Some(mut overlap) = geo.intersection(bbox) {
2666 overlap.loc -= surface_pos;
2667 cursor_scale =
2668 f64::max(cursor_scale, output.current_scale().fractional_scale());
2669 // FIXME: using the largest overlapping or "primary" output transform would
2670 // make more sense here.
2671 cursor_transform = output.current_transform();
2672 output_update(output, Some(overlap), surface);
2673 } else {
2674 output_update(output, None, surface);
2675 }
2676
2677 // Compute DnD icon surface overlap.
2678 if let Some((surface, bbox)) = dnd {
2679 if let Some(mut overlap) = geo.intersection(bbox) {
2680 overlap.loc -= surface_pos;
2681 dnd_scale =
2682 f64::max(dnd_scale, output.current_scale().fractional_scale());
2683 // FIXME: using the largest overlapping or "primary" output transform
2684 // would make more sense here.
2685 dnd_transform = output.current_transform();
2686 output_update(output, Some(overlap), surface);
2687 } else {
2688 output_update(output, None, surface);
2689 }
2690 }
2691 }
2692
2693 with_states(surface, |data| {
2694 send_scale_transform(
2695 surface,
2696 data,
2697 output::Scale::Fractional(cursor_scale),
2698 cursor_transform,
2699 )
2700 });
2701 if let Some((surface, _)) = dnd {
2702 with_states(surface, |data| {
2703 send_scale_transform(
2704 surface,
2705 data,
2706 output::Scale::Fractional(dnd_scale),
2707 dnd_transform,
2708 );
2709 });
2710 }
2711 }
2712 cursor_image => {
2713 // There's no cursor surface, but there might be a DnD icon.
2714 let Some(surface) = &self.dnd_icon else {
2715 return;
2716 };
2717
2718 let icon = if let CursorImageStatus::Named(icon) = cursor_image {
2719 icon
2720 } else {
2721 Default::default()
2722 };
2723
2724 let mut dnd_scale = 1.;
2725 let mut dnd_transform = Transform::Normal;
2726 for output in self.global_space.outputs() {
2727 let geo = self.global_space.output_geometry(output).unwrap();
2728
2729 // The default cursor is rendered at the right scale for each output, which
2730 // means that it may have a different hotspot for each output.
2731 let output_scale = output.current_scale().integer_scale();
2732 let cursor = self
2733 .cursor_manager
2734 .get_cursor_with_name(icon, output_scale)
2735 .unwrap_or_else(|| self.cursor_manager.get_default_cursor(output_scale));
2736
2737 // For simplicity, we always use frame 0 for this computation. Let's hope the
2738 // hotspot doesn't change between frames.
2739 let hotspot = XCursor::hotspot(&cursor.frames()[0]).to_logical(output_scale);
2740
2741 let surface_pos = pointer_pos.to_i32_round() - hotspot;
2742 let bbox = bbox_from_surface_tree(surface, surface_pos);
2743
2744 if let Some(mut overlap) = geo.intersection(bbox) {
2745 overlap.loc -= surface_pos;
2746 dnd_scale = f64::max(dnd_scale, output.current_scale().fractional_scale());
2747 // FIXME: using the largest overlapping or "primary" output transform would
2748 // make more sense here.
2749 dnd_transform = output.current_transform();
2750 output_update(output, Some(overlap), surface);
2751 } else {
2752 output_update(output, None, surface);
2753 }
2754 }
2755
2756 with_states(surface, |data| {
2757 send_scale_transform(
2758 surface,
2759 data,
2760 output::Scale::Fractional(dnd_scale),
2761 dnd_transform,
2762 );
2763 });
2764 }
2765 }
2766 }
2767
2768 pub fn refresh_idle_inhibit(&mut self) {
2769 let _span = tracy_client::span!("Niri::refresh_idle_inhibit");
2770
2771 self.idle_inhibiting_surfaces.retain(|s| s.is_alive());
2772
2773 let is_inhibited = self.is_fdo_idle_inhibited.load(Ordering::SeqCst)
2774 || self.idle_inhibiting_surfaces.iter().any(|surface| {
2775 with_states(surface, |states| {
2776 surface_primary_scanout_output(surface, states).is_some()
2777 })
2778 });
2779 self.idle_notifier_state.set_is_inhibited(is_inhibited);
2780 }
2781
2782 pub fn refresh_window_rules(&mut self) {
2783 let _span = tracy_client::span!("Niri::refresh_window_rules");
2784
2785 let config = self.config.borrow();
2786 let window_rules = &config.window_rules;
2787
2788 let mut windows = vec![];
2789 let mut outputs = HashSet::new();
2790 self.layout.with_windows_mut(|mapped, output| {
2791 if mapped.recompute_window_rules_if_needed(window_rules, self.is_at_startup) {
2792 windows.push(mapped.window.clone());
2793
2794 if let Some(output) = output {
2795 outputs.insert(output.clone());
2796 }
2797 }
2798 });
2799 drop(config);
2800
2801 for win in windows {
2802 self.layout.update_window(&win, None);
2803 win.toplevel()
2804 .expect("no X11 support")
2805 .send_pending_configure();
2806 }
2807 for output in outputs {
2808 self.queue_redraw(&output);
2809 }
2810 }
2811
2812 #[cfg(feature = "xdp-gnome-screencast")]
2813 pub fn refresh_mapped_cast_outputs(&mut self) {
2814 use std::collections::hash_map::Entry;
2815
2816 let mut seen = HashSet::new();
2817 let mut output_changed = vec![];
2818
2819 self.layout.with_windows(|mapped, output, _| {
2820 seen.insert(mapped.window.clone());
2821
2822 let Some(output) = output else {
2823 return;
2824 };
2825
2826 match self.mapped_cast_output.entry(mapped.window.clone()) {
2827 Entry::Occupied(mut entry) => {
2828 if entry.get() != output {
2829 entry.insert(output.clone());
2830 output_changed.push((mapped.id(), output.clone()));
2831 }
2832 }
2833 Entry::Vacant(entry) => {
2834 entry.insert(output.clone());
2835 }
2836 }
2837 });
2838
2839 self.mapped_cast_output.retain(|win, _| seen.contains(win));
2840
2841 let mut to_stop = vec![];
2842 for (id, out) in output_changed {
2843 let refresh = out.current_mode().unwrap().refresh as u32;
2844 let target = CastTarget::Window { id: id.get() };
2845 for cast in self.casts.iter_mut().filter(|cast| cast.target == target) {
2846 if let Err(err) = cast.set_refresh(refresh) {
2847 warn!("error changing cast FPS: {err:?}");
2848 to_stop.push(cast.session_id);
2849 };
2850 }
2851 }
2852
2853 for session_id in to_stop {
2854 self.stop_cast(session_id);
2855 }
2856 }
2857
2858 pub fn update_render_elements(&mut self, output: Option<&Output>) {
2859 self.layout.update_render_elements(output);
2860
2861 for (out, state) in self.output_state.iter_mut() {
2862 if output.map_or(true, |output| out == output) {
2863 let scale = Scale::from(out.current_scale().fractional_scale());
2864 let transform = out.current_transform();
2865
2866 if let Some(transition) = &mut state.screen_transition {
2867 transition.update_render_elements(scale, transform);
2868 }
2869 }
2870 }
2871 }
2872
2873 pub fn render<R: NiriRenderer>(
2874 &self,
2875 renderer: &mut R,
2876 output: &Output,
2877 include_pointer: bool,
2878 mut target: RenderTarget,
2879 ) -> Vec<OutputRenderElements<R>> {
2880 let _span = tracy_client::span!("Niri::render");
2881
2882 if target == RenderTarget::Output {
2883 if let Some(preview) = self.config.borrow().debug.preview_render {
2884 target = match preview {
2885 PreviewRender::Screencast => RenderTarget::Screencast,
2886 PreviewRender::ScreenCapture => RenderTarget::ScreenCapture,
2887 };
2888 }
2889 }
2890
2891 let output_scale = Scale::from(output.current_scale().fractional_scale());
2892
2893 // The pointer goes on the top.
2894 let mut elements = vec![];
2895 if include_pointer {
2896 elements = self.pointer_element(renderer, output);
2897 }
2898
2899 // Next, the screen transition texture.
2900 {
2901 let state = self.output_state.get(output).unwrap();
2902 if let Some(transition) = &state.screen_transition {
2903 elements.push(transition.render(target).into());
2904 }
2905 }
2906
2907 // Next, the exit confirm dialog.
2908 if let Some(dialog) = &self.exit_confirm_dialog {
2909 if let Some(element) = dialog.render(renderer, output) {
2910 elements.push(element.into());
2911 }
2912 }
2913
2914 // Next, the config error notification too.
2915 if let Some(element) = self.config_error_notification.render(renderer, output) {
2916 elements.push(element.into());
2917 }
2918
2919 // If the session is locked, draw the lock surface.
2920 if self.is_locked() {
2921 let state = self.output_state.get(output).unwrap();
2922 if let Some(surface) = state.lock_surface.as_ref() {
2923 elements.extend(render_elements_from_surface_tree(
2924 renderer,
2925 surface.wl_surface(),
2926 (0, 0),
2927 output_scale,
2928 1.,
2929 Kind::Unspecified,
2930 ));
2931 }
2932
2933 // Draw the solid color background.
2934 elements.push(
2935 SolidColorRenderElement::from_buffer(
2936 &state.lock_color_buffer,
2937 (0, 0),
2938 output_scale,
2939 1.,
2940 Kind::Unspecified,
2941 )
2942 .into(),
2943 );
2944
2945 if self.debug_draw_opaque_regions {
2946 draw_opaque_regions(&mut elements, output_scale);
2947 }
2948 return elements;
2949 }
2950
2951 // Prepare the background element.
2952 let state = self.output_state.get(output).unwrap();
2953 let background = SolidColorRenderElement::from_buffer(
2954 &state.background_buffer,
2955 (0, 0),
2956 output_scale,
2957 1.,
2958 Kind::Unspecified,
2959 )
2960 .into();
2961
2962 // If the screenshot UI is open, draw it.
2963 if self.screenshot_ui.is_open() {
2964 elements.extend(
2965 self.screenshot_ui
2966 .render_output(output, target)
2967 .into_iter()
2968 .map(OutputRenderElements::from),
2969 );
2970
2971 // Add the background for outputs that were connected while the screenshot UI was open.
2972 elements.push(background);
2973
2974 if self.debug_draw_opaque_regions {
2975 draw_opaque_regions(&mut elements, output_scale);
2976 }
2977 return elements;
2978 }
2979
2980 // Draw the hotkey overlay on top.
2981 if let Some(element) = self.hotkey_overlay.render(renderer, output) {
2982 elements.push(element.into());
2983 }
2984
2985 // Get monitor elements.
2986 let mon = self.layout.monitor_for_output(output).unwrap();
2987 let monitor_elements = mon.render_elements(renderer, target);
2988
2989 // Get layer-shell elements.
2990 let layer_map = layer_map_for_output(output);
2991 let mut extend_from_layer = |elements: &mut Vec<OutputRenderElements<R>>, layer| {
2992 let iter = layer_map
2993 .layers_on(layer)
2994 .filter_map(|surface| {
2995 layer_map
2996 .layer_geometry(surface)
2997 .map(|geo| (geo.loc, surface))
2998 })
2999 .flat_map(|(loc, surface)| {
3000 surface
3001 .render_elements(
3002 renderer,
3003 loc.to_physical_precise_round(output_scale),
3004 output_scale,
3005 1.,
3006 )
3007 .into_iter()
3008 .map(OutputRenderElements::Wayland)
3009 });
3010 elements.extend(iter);
3011 };
3012
3013 // The upper layer-shell elements go next.
3014 extend_from_layer(&mut elements, Layer::Overlay);
3015
3016 // Then the regular monitor elements and the top layer in varying order.
3017 if mon.render_above_top_layer() {
3018 elements.extend(monitor_elements.into_iter().map(OutputRenderElements::from));
3019 extend_from_layer(&mut elements, Layer::Top);
3020 } else {
3021 extend_from_layer(&mut elements, Layer::Top);
3022 elements.extend(monitor_elements.into_iter().map(OutputRenderElements::from));
3023 }
3024
3025 // Then the lower layer-shell elements.
3026 extend_from_layer(&mut elements, Layer::Bottom);
3027 extend_from_layer(&mut elements, Layer::Background);
3028
3029 // Then the background.
3030 elements.push(background);
3031
3032 if self.debug_draw_opaque_regions {
3033 draw_opaque_regions(&mut elements, output_scale);
3034 }
3035
3036 elements
3037 }
3038
3039 fn redraw(&mut self, backend: &mut Backend, output: &Output) {
3040 let _span = tracy_client::span!("Niri::redraw");
3041
3042 // Verify our invariant.
3043 let state = self.output_state.get_mut(output).unwrap();
3044 assert!(matches!(
3045 state.redraw_state,
3046 RedrawState::Queued | RedrawState::WaitingForEstimatedVBlankAndQueued(_)
3047 ));
3048
3049 let target_presentation_time = state.frame_clock.next_presentation_time();
3050
3051 let mut res = RenderResult::Skipped;
3052 if self.monitors_active {
3053 // Update from the config and advance the animations.
3054 self.layout.advance_animations(target_presentation_time);
3055
3056 if let Some(transition) = &mut state.screen_transition {
3057 transition.advance_animations(target_presentation_time);
3058 if transition.is_done() {
3059 state.screen_transition = None;
3060 }
3061 }
3062
3063 state.unfinished_animations_remain = self
3064 .layout
3065 .monitor_for_output(output)
3066 .unwrap()
3067 .are_animations_ongoing();
3068
3069 self.config_error_notification
3070 .advance_animations(target_presentation_time);
3071 state.unfinished_animations_remain |=
3072 self.config_error_notification.are_animations_ongoing();
3073
3074 self.screenshot_ui
3075 .advance_animations(target_presentation_time);
3076 state.unfinished_animations_remain |= self.screenshot_ui.are_animations_ongoing();
3077
3078 // Also keep redrawing if the current cursor is animated.
3079 state.unfinished_animations_remain |= self
3080 .cursor_manager
3081 .is_current_cursor_animated(output.current_scale().integer_scale());
3082
3083 // Also keep redrawing during a screen transition.
3084 state.unfinished_animations_remain |= state.screen_transition.is_some();
3085
3086 self.update_render_elements(Some(output));
3087
3088 // Render.
3089 res = backend.render(self, output, target_presentation_time);
3090 }
3091
3092 let is_locked = self.is_locked();
3093 let state = self.output_state.get_mut(output).unwrap();
3094
3095 if res == RenderResult::Skipped {
3096 // Update the redraw state on failed render.
3097 state.redraw_state = if let RedrawState::WaitingForEstimatedVBlank(token)
3098 | RedrawState::WaitingForEstimatedVBlankAndQueued(token) =
3099 state.redraw_state
3100 {
3101 RedrawState::WaitingForEstimatedVBlank(token)
3102 } else {
3103 RedrawState::Idle
3104 };
3105 }
3106
3107 // Update the lock render state on successful render, or if monitors are inactive. When
3108 // monitors are inactive on a TTY, they have no framebuffer attached, so no sensitive data
3109 // from a last render will be visible.
3110 if res != RenderResult::Skipped || !self.monitors_active {
3111 state.lock_render_state = if is_locked {
3112 LockRenderState::Locked
3113 } else {
3114 LockRenderState::Unlocked
3115 };
3116 }
3117
3118 // If we're in process of locking the session, check if the requirements were met.
3119 match mem::take(&mut self.lock_state) {
3120 LockState::Locking(confirmation) => {
3121 if state.lock_render_state == LockRenderState::Unlocked {
3122 // We needed to render a locked frame on this output but failed.
3123 self.unlock();
3124 } else {
3125 // Check if all outputs are now locked.
3126 let all_locked = self
3127 .output_state
3128 .values()
3129 .all(|state| state.lock_render_state == LockRenderState::Locked);
3130
3131 if all_locked {
3132 // All outputs are locked, report success.
3133 let lock = confirmation.ext_session_lock().clone();
3134 confirmation.lock();
3135 self.lock_state = LockState::Locked(lock);
3136 } else {
3137 // Still waiting for other outputs.
3138 self.lock_state = LockState::Locking(confirmation);
3139 }
3140 }
3141 }
3142 lock_state => self.lock_state = lock_state,
3143 }
3144
3145 self.refresh_on_demand_vrr(backend, output);
3146
3147 // Send the frame callbacks.
3148 //
3149 // FIXME: The logic here could be a bit smarter. Currently, during an animation, the
3150 // surfaces that are visible for the very last frame (e.g. because the camera is moving
3151 // away) will receive frame callbacks, and the surfaces that are invisible but will become
3152 // visible next frame will not receive frame callbacks (so they will show stale contents for
3153 // one frame). We could advance the animations for the next frame and send frame callbacks
3154 // according to the expected new positions.
3155 //
3156 // However, this should probably be restricted to sending frame callbacks to more surfaces,
3157 // to err on the safe side.
3158 self.send_frame_callbacks(output);
3159 backend.with_primary_renderer(|renderer| {
3160 #[cfg(feature = "xdp-gnome-screencast")]
3161 {
3162 // Render and send to PipeWire screencast streams.
3163 self.render_for_screen_cast(renderer, output, target_presentation_time);
3164
3165 // FIXME: when a window is hidden, it should probably still receive frame callbacks
3166 // and get rendered for screen cast. This is currently
3167 // unimplemented, but happens to work by chance, since output
3168 // redrawing is more eager than it should be.
3169 self.render_windows_for_screen_cast(renderer, output, target_presentation_time);
3170 }
3171
3172 self.render_for_screencopy_with_damage(renderer, output);
3173 });
3174 }
3175
3176 pub fn refresh_on_demand_vrr(&mut self, backend: &mut Backend, output: &Output) {
3177 let _span = tracy_client::span!("Niri::refresh_on_demand_vrr");
3178 let Some(on_demand) = self
3179 .config
3180 .borrow()
3181 .outputs
3182 .find(&output.name())
3183 .map(|output| output.is_vrr_on_demand())
3184 else {
3185 warn!("error getting output config for {}", output.name());
3186 return;
3187 };
3188 if !on_demand {
3189 return;
3190 }
3191
3192 let current = self.layout.windows_for_output(output).any(|mapped| {
3193 mapped.rules().variable_refresh_rate == Some(true) && {
3194 let mut visible = false;
3195 mapped.window.with_surfaces(|surface, states| {
3196 if !visible
3197 && surface_primary_scanout_output(surface, states).as_ref() == Some(output)
3198 {
3199 visible = true;
3200 }
3201 });
3202 visible
3203 }
3204 });
3205
3206 backend.set_output_on_demand_vrr(self, output, current);
3207 }
3208
3209 pub fn update_primary_scanout_output(
3210 &self,
3211 output: &Output,
3212 render_element_states: &RenderElementStates,
3213 ) {
3214 // FIXME: potentially tweak the compare function. The default one currently always prefers a
3215 // higher refresh-rate output, which is not always desirable (i.e. with a very small
3216 // overlap).
3217 //
3218 // While we only have cursors and DnD icons crossing output boundaries though, it doesn't
3219 // matter all that much.
3220 if let CursorImageStatus::Surface(surface) = &self.cursor_manager.cursor_image() {
3221 with_surface_tree_downward(
3222 surface,
3223 (),
3224 |_, _, _| TraversalAction::DoChildren(()),
3225 |surface, states, _| {
3226 update_surface_primary_scanout_output(
3227 surface,
3228 output,
3229 states,
3230 render_element_states,
3231 default_primary_scanout_output_compare,
3232 );
3233 },
3234 |_, _, _| true,
3235 );
3236 }
3237
3238 if let Some(surface) = &self.dnd_icon {
3239 with_surface_tree_downward(
3240 surface,
3241 (),
3242 |_, _, _| TraversalAction::DoChildren(()),
3243 |surface, states, _| {
3244 update_surface_primary_scanout_output(
3245 surface,
3246 output,
3247 states,
3248 render_element_states,
3249 default_primary_scanout_output_compare,
3250 );
3251 },
3252 |_, _, _| true,
3253 );
3254 }
3255
3256 // We're only updating the current output's windows and layer surfaces. This should be fine
3257 // as in niri they can only be rendered on a single output at a time.
3258 //
3259 // The reason to do this at all is that it keeps track of whether the surface is visible or
3260 // not in a unified way with the pointer surfaces, which makes the logic elsewhere simpler.
3261
3262 for mapped in self.layout.windows_for_output(output) {
3263 let win = &mapped.window;
3264 let offscreen_id = win
3265 .user_data()
3266 .get_or_insert(WindowOffscreenId::default)
3267 .0
3268 .borrow();
3269 let offscreen_id = offscreen_id.as_ref();
3270
3271 win.with_surfaces(|surface, states| {
3272 let surface_primary_scanout_output = states
3273 .data_map
3274 .get_or_insert_threadsafe(Mutex::<PrimaryScanoutOutput>::default);
3275 surface_primary_scanout_output
3276 .lock()
3277 .unwrap()
3278 .update_from_render_element_states(
3279 offscreen_id.cloned().unwrap_or_else(|| surface.into()),
3280 output,
3281 render_element_states,
3282 |_, _, output, _| output,
3283 );
3284 });
3285 }
3286
3287 for surface in layer_map_for_output(output).layers() {
3288 surface.with_surfaces(|surface, states| {
3289 update_surface_primary_scanout_output(
3290 surface,
3291 output,
3292 states,
3293 render_element_states,
3294 // Layer surfaces are shown only on one output at a time.
3295 |_, _, output, _| output,
3296 );
3297 });
3298 }
3299
3300 if let Some(surface) = &self.output_state[output].lock_surface {
3301 with_surface_tree_downward(
3302 surface.wl_surface(),
3303 (),
3304 |_, _, _| TraversalAction::DoChildren(()),
3305 |surface, states, _| {
3306 update_surface_primary_scanout_output(
3307 surface,
3308 output,
3309 states,
3310 render_element_states,
3311 default_primary_scanout_output_compare,
3312 );
3313 },
3314 |_, _, _| true,
3315 );
3316 }
3317 }
3318
3319 pub fn send_dmabuf_feedbacks(
3320 &self,
3321 output: &Output,
3322 feedback: &SurfaceDmabufFeedback,
3323 render_element_states: &RenderElementStates,
3324 ) {
3325 let _span = tracy_client::span!("Niri::send_dmabuf_feedbacks");
3326
3327 // We can unconditionally send the current output's feedback to regular and layer-shell
3328 // surfaces, as they can only be displayed on a single output at a time. Even if a surface
3329 // is currently invisible, this is the DMABUF feedback that it should know about.
3330 for mapped in self.layout.windows_for_output(output) {
3331 mapped.window.send_dmabuf_feedback(
3332 output,
3333 |_, _| Some(output.clone()),
3334 |surface, _| {
3335 select_dmabuf_feedback(
3336 surface,
3337 render_element_states,
3338 &feedback.render,
3339 &feedback.scanout,
3340 )
3341 },
3342 );
3343 }
3344
3345 for surface in layer_map_for_output(output).layers() {
3346 surface.send_dmabuf_feedback(
3347 output,
3348 |_, _| Some(output.clone()),
3349 |surface, _| {
3350 select_dmabuf_feedback(
3351 surface,
3352 render_element_states,
3353 &feedback.render,
3354 &feedback.scanout,
3355 )
3356 },
3357 );
3358 }
3359
3360 if let Some(surface) = &self.output_state[output].lock_surface {
3361 send_dmabuf_feedback_surface_tree(
3362 surface.wl_surface(),
3363 output,
3364 |_, _| Some(output.clone()),
3365 |surface, _| {
3366 select_dmabuf_feedback(
3367 surface,
3368 render_element_states,
3369 &feedback.render,
3370 &feedback.scanout,
3371 )
3372 },
3373 );
3374 }
3375
3376 if let Some(surface) = &self.dnd_icon {
3377 send_dmabuf_feedback_surface_tree(
3378 surface,
3379 output,
3380 surface_primary_scanout_output,
3381 |surface, _| {
3382 select_dmabuf_feedback(
3383 surface,
3384 render_element_states,
3385 &feedback.render,
3386 &feedback.scanout,
3387 )
3388 },
3389 );
3390 }
3391
3392 if let CursorImageStatus::Surface(surface) = &self.cursor_manager.cursor_image() {
3393 send_dmabuf_feedback_surface_tree(
3394 surface,
3395 output,
3396 surface_primary_scanout_output,
3397 |surface, _| {
3398 select_dmabuf_feedback(
3399 surface,
3400 render_element_states,
3401 &feedback.render,
3402 &feedback.scanout,
3403 )
3404 },
3405 );
3406 }
3407 }
3408
3409 pub fn send_frame_callbacks(&self, output: &Output) {
3410 let _span = tracy_client::span!("Niri::send_frame_callbacks");
3411
3412 let state = self.output_state.get(output).unwrap();
3413 let sequence = state.frame_callback_sequence;
3414
3415 let should_send = |surface: &WlSurface, states: &SurfaceData| {
3416 // Do the standard primary scanout output check. For pointer surfaces it deduplicates
3417 // the frame callbacks across potentially multiple outputs, and for regular windows and
3418 // layer-shell surfaces it avoids sending frame callbacks to invisible surfaces.
3419 let current_primary_output = surface_primary_scanout_output(surface, states);
3420 if current_primary_output.as_ref() != Some(output) {
3421 return None;
3422 }
3423
3424 // Next, check the throttling status.
3425 let frame_throttling_state = states
3426 .data_map
3427 .get_or_insert(SurfaceFrameThrottlingState::default);
3428 let mut last_sent_at = frame_throttling_state.last_sent_at.borrow_mut();
3429
3430 let mut send = true;
3431
3432 // If we already sent a frame callback to this surface this output refresh
3433 // cycle, don't send one again to prevent empty-damage commit busy loops.
3434 if let Some((last_output, last_sequence)) = &*last_sent_at {
3435 if last_output == output && *last_sequence == sequence {
3436 send = false;
3437 }
3438 }
3439
3440 if send {
3441 *last_sent_at = Some((output.clone(), sequence));
3442 Some(output.clone())
3443 } else {
3444 None
3445 }
3446 };
3447
3448 let frame_callback_time = get_monotonic_time();
3449
3450 for mapped in self.layout.windows_for_output(output) {
3451 mapped.window.send_frame(
3452 output,
3453 frame_callback_time,
3454 FRAME_CALLBACK_THROTTLE,
3455 should_send,
3456 );
3457 }
3458
3459 for surface in layer_map_for_output(output).layers() {
3460 surface.send_frame(
3461 output,
3462 frame_callback_time,
3463 FRAME_CALLBACK_THROTTLE,
3464 should_send,
3465 );
3466 }
3467
3468 if let Some(surface) = &self.output_state[output].lock_surface {
3469 send_frames_surface_tree(
3470 surface.wl_surface(),
3471 output,
3472 frame_callback_time,
3473 FRAME_CALLBACK_THROTTLE,
3474 should_send,
3475 );
3476 }
3477
3478 if let Some(surface) = &self.dnd_icon {
3479 send_frames_surface_tree(
3480 surface,
3481 output,
3482 frame_callback_time,
3483 FRAME_CALLBACK_THROTTLE,
3484 should_send,
3485 );
3486 }
3487
3488 if let CursorImageStatus::Surface(surface) = self.cursor_manager.cursor_image() {
3489 send_frames_surface_tree(
3490 surface,
3491 output,
3492 frame_callback_time,
3493 FRAME_CALLBACK_THROTTLE,
3494 should_send,
3495 );
3496 }
3497 }
3498
3499 pub fn send_frame_callbacks_on_fallback_timer(&self) {
3500 let _span = tracy_client::span!("Niri::send_frame_callbacks_on_fallback_timer");
3501
3502 // Make up a bogus output; we don't care about it here anyway, just the throttling timer.
3503 let output = Output::new(
3504 String::new(),
3505 PhysicalProperties {
3506 size: Size::from((0, 0)),
3507 subpixel: Subpixel::Unknown,
3508 make: String::new(),
3509 model: String::new(),
3510 },
3511 );
3512 let output = &output;
3513
3514 let frame_callback_time = get_monotonic_time();
3515
3516 self.layout.with_windows(|mapped, _, _| {
3517 mapped.window.send_frame(
3518 output,
3519 frame_callback_time,
3520 FRAME_CALLBACK_THROTTLE,
3521 |_, _| None,
3522 );
3523 });
3524
3525 for (output, state) in self.output_state.iter() {
3526 for surface in layer_map_for_output(output).layers() {
3527 surface.send_frame(
3528 output,
3529 frame_callback_time,
3530 FRAME_CALLBACK_THROTTLE,
3531 |_, _| None,
3532 );
3533 }
3534
3535 if let Some(surface) = &state.lock_surface {
3536 send_frames_surface_tree(
3537 surface.wl_surface(),
3538 output,
3539 frame_callback_time,
3540 FRAME_CALLBACK_THROTTLE,
3541 |_, _| None,
3542 );
3543 }
3544 }
3545
3546 if let Some(surface) = &self.dnd_icon {
3547 send_frames_surface_tree(
3548 surface,
3549 output,
3550 frame_callback_time,
3551 FRAME_CALLBACK_THROTTLE,
3552 |_, _| None,
3553 );
3554 }
3555
3556 if let CursorImageStatus::Surface(surface) = self.cursor_manager.cursor_image() {
3557 send_frames_surface_tree(
3558 surface,
3559 output,
3560 frame_callback_time,
3561 FRAME_CALLBACK_THROTTLE,
3562 |_, _| None,
3563 );
3564 }
3565 }
3566
3567 pub fn take_presentation_feedbacks(
3568 &mut self,
3569 output: &Output,
3570 render_element_states: &RenderElementStates,
3571 ) -> OutputPresentationFeedback {
3572 let mut feedback = OutputPresentationFeedback::new(output);
3573
3574 if let CursorImageStatus::Surface(surface) = &self.cursor_manager.cursor_image() {
3575 take_presentation_feedback_surface_tree(
3576 surface,
3577 &mut feedback,
3578 surface_primary_scanout_output,
3579 |surface, _| {
3580 surface_presentation_feedback_flags_from_states(surface, render_element_states)
3581 },
3582 );
3583 }
3584
3585 if let Some(surface) = &self.dnd_icon {
3586 take_presentation_feedback_surface_tree(
3587 surface,
3588 &mut feedback,
3589 surface_primary_scanout_output,
3590 |surface, _| {
3591 surface_presentation_feedback_flags_from_states(surface, render_element_states)
3592 },
3593 );
3594 }
3595
3596 for mapped in self.layout.windows_for_output(output) {
3597 mapped.window.take_presentation_feedback(
3598 &mut feedback,
3599 surface_primary_scanout_output,
3600 |surface, _| {
3601 surface_presentation_feedback_flags_from_states(surface, render_element_states)
3602 },
3603 )
3604 }
3605
3606 for surface in layer_map_for_output(output).layers() {
3607 surface.take_presentation_feedback(
3608 &mut feedback,
3609 surface_primary_scanout_output,
3610 |surface, _| {
3611 surface_presentation_feedback_flags_from_states(surface, render_element_states)
3612 },
3613 );
3614 }
3615
3616 if let Some(surface) = &self.output_state[output].lock_surface {
3617 take_presentation_feedback_surface_tree(
3618 surface.wl_surface(),
3619 &mut feedback,
3620 surface_primary_scanout_output,
3621 |surface, _| {
3622 surface_presentation_feedback_flags_from_states(surface, render_element_states)
3623 },
3624 );
3625 }
3626
3627 feedback
3628 }
3629
3630 #[cfg(feature = "xdp-gnome-screencast")]
3631 fn render_for_screen_cast(
3632 &mut self,
3633 renderer: &mut GlesRenderer,
3634 output: &Output,
3635 target_presentation_time: Duration,
3636 ) {
3637 let _span = tracy_client::span!("Niri::render_for_screen_cast");
3638
3639 let target = CastTarget::Output(output.downgrade());
3640
3641 let size = output.current_mode().unwrap().size;
3642 let transform = output.current_transform();
3643 let size = transform.transform_size(size);
3644
3645 let scale = Scale::from(output.current_scale().fractional_scale());
3646
3647 let mut elements = None;
3648 let mut casts_to_stop = vec![];
3649
3650 let mut casts = mem::take(&mut self.casts);
3651 for cast in &mut casts {
3652 if !cast.is_active.get() {
3653 continue;
3654 }
3655
3656 if cast.target != target {
3657 continue;
3658 }
3659
3660 match cast.ensure_size(size) {
3661 Ok(CastSizeChange::Ready) => (),
3662 Ok(CastSizeChange::Pending) => continue,
3663 Err(err) => {
3664 warn!("error updating stream size, stopping screencast: {err:?}");
3665 casts_to_stop.push(cast.session_id);
3666 }
3667 }
3668
3669 if cast.check_time_and_schedule(&self.event_loop, output, target_presentation_time) {
3670 continue;
3671 }
3672
3673 // FIXME: Hidden / embedded / metadata cursor
3674 let elements = elements.get_or_insert_with(|| {
3675 self.render(renderer, output, true, RenderTarget::Screencast)
3676 });
3677
3678 if cast.dequeue_buffer_and_render(renderer, elements, size, scale) {
3679 cast.last_frame_time = target_presentation_time;
3680 }
3681 }
3682 self.casts = casts;
3683
3684 for id in casts_to_stop {
3685 self.stop_cast(id);
3686 }
3687 }
3688
3689 #[cfg(feature = "xdp-gnome-screencast")]
3690 fn render_windows_for_screen_cast(
3691 &mut self,
3692 renderer: &mut GlesRenderer,
3693 output: &Output,
3694 target_presentation_time: Duration,
3695 ) {
3696 let _span = tracy_client::span!("Niri::render_windows_for_screen_cast");
3697
3698 let scale = Scale::from(output.current_scale().fractional_scale());
3699
3700 let mut casts_to_stop = vec![];
3701
3702 let mut casts = mem::take(&mut self.casts);
3703 for cast in &mut casts {
3704 if !cast.is_active.get() {
3705 continue;
3706 }
3707
3708 let CastTarget::Window { id } = cast.target else {
3709 continue;
3710 };
3711
3712 let mut windows = self.layout.windows_for_output(output);
3713 let Some(mapped) = windows.find(|win| win.id().get() == id) else {
3714 continue;
3715 };
3716
3717 let bbox = mapped
3718 .window
3719 .bbox_with_popups()
3720 .to_physical_precise_up(scale);
3721
3722 match cast.ensure_size(bbox.size) {
3723 Ok(CastSizeChange::Ready) => (),
3724 Ok(CastSizeChange::Pending) => continue,
3725 Err(err) => {
3726 warn!("error updating stream size, stopping screencast: {err:?}");
3727 casts_to_stop.push(cast.session_id);
3728 }
3729 }
3730
3731 if cast.check_time_and_schedule(&self.event_loop, output, target_presentation_time) {
3732 continue;
3733 }
3734
3735 // FIXME: pointer.
3736 let elements: Vec<_> = mapped.render_for_screen_cast(renderer, scale).collect();
3737
3738 if cast.dequeue_buffer_and_render(renderer, &elements, bbox.size, scale) {
3739 cast.last_frame_time = target_presentation_time;
3740 }
3741 }
3742 self.casts = casts;
3743
3744 for id in casts_to_stop {
3745 self.stop_cast(id);
3746 }
3747 }
3748
3749 #[cfg(feature = "xdp-gnome-screencast")]
3750 fn render_window_for_screen_cast(
3751 &mut self,
3752 renderer: &mut GlesRenderer,
3753 window_id: u64,
3754 target_presentation_time: Duration,
3755 ) {
3756 let _span = tracy_client::span!("Niri::render_window_for_screen_cast");
3757
3758 let mut window = None;
3759 self.layout.with_windows(|mapped, _, _| {
3760 if mapped.id().get() != window_id {
3761 return;
3762 }
3763
3764 window = Some(mapped.window.clone());
3765 });
3766
3767 let Some(window) = window else {
3768 return;
3769 };
3770
3771 // Use the cached output since it will be present even if the output was
3772 // currently disconnected.
3773 let Some(output) = self.mapped_cast_output.get(&window) else {
3774 return;
3775 };
3776
3777 let mut windows = self.layout.windows_for_output(output);
3778 let mapped = windows
3779 .find(|mapped| mapped.id().get() == window_id)
3780 .unwrap();
3781
3782 let scale = Scale::from(output.current_scale().fractional_scale());
3783 let bbox = mapped
3784 .window
3785 .bbox_with_popups()
3786 .to_physical_precise_up(scale);
3787
3788 let mut elements = None;
3789 let mut casts_to_stop = vec![];
3790
3791 let mut casts = mem::take(&mut self.casts);
3792 for cast in &mut casts {
3793 if !cast.is_active.get() {
3794 continue;
3795 }
3796
3797 if cast.target != (CastTarget::Window { id: window_id }) {
3798 continue;
3799 }
3800
3801 match cast.ensure_size(bbox.size) {
3802 Ok(CastSizeChange::Ready) => (),
3803 Ok(CastSizeChange::Pending) => continue,
3804 Err(err) => {
3805 warn!("error updating stream size, stopping screencast: {err:?}");
3806 casts_to_stop.push(cast.session_id);
3807 }
3808 }
3809
3810 if cast.check_time_and_schedule(&self.event_loop, output, target_presentation_time) {
3811 continue;
3812 }
3813
3814 let elements = elements.get_or_insert_with(|| {
3815 // FIXME: pointer.
3816 mapped
3817 .render_for_screen_cast(renderer, scale)
3818 .rev()
3819 .collect::<Vec<_>>()
3820 });
3821
3822 if cast.dequeue_buffer_and_render(renderer, elements, bbox.size, scale) {
3823 cast.last_frame_time = target_presentation_time;
3824 }
3825 }
3826 self.casts = casts;
3827
3828 drop(windows);
3829
3830 for id in casts_to_stop {
3831 self.stop_cast(id);
3832 }
3833 }
3834
3835 pub fn render_for_screencopy_with_damage(
3836 &mut self,
3837 renderer: &mut GlesRenderer,
3838 output: &Output,
3839 ) {
3840 let _span = tracy_client::span!("Niri::render_for_screencopy_with_damage");
3841
3842 let mut screencopy_state = mem::take(&mut self.screencopy_state);
3843 let elements = OnceCell::new();
3844
3845 for queue in screencopy_state.queues_mut() {
3846 let (damage_tracker, screencopy) = queue.split();
3847 if let Some(screencopy) = screencopy {
3848 if screencopy.output() == output {
3849 let elements = elements.get_or_init(|| {
3850 self.render(renderer, output, true, RenderTarget::ScreenCapture)
3851 });
3852 // FIXME: skip elements if not including pointers
3853 let render_result = Self::render_for_screencopy_internal(
3854 renderer,
3855 output,
3856 elements,
3857 true,
3858 damage_tracker,
3859 screencopy,
3860 );
3861 match render_result {
3862 Ok((sync, damages)) => {
3863 if let Some(damages) = damages {
3864 // Convert from Physical coordinates back to Buffer coordinates.
3865 let transform = output.current_transform();
3866 let physical_size =
3867 transform.transform_size(screencopy.buffer_size());
3868 let damages = damages.iter().map(|dmg| {
3869 dmg.to_logical(1).to_buffer(
3870 1,
3871 transform.invert(),
3872 &physical_size.to_logical(1),
3873 )
3874 });
3875
3876 screencopy.damage(damages);
3877 queue.pop().submit_after_sync(false, sync, &self.event_loop);
3878 } else {
3879 trace!("no damage found, waiting till next redraw");
3880 }
3881 }
3882 Err(err) => {
3883 // Recreate damage tracker to report full damage next check.
3884 *damage_tracker =
3885 OutputDamageTracker::new((0, 0), 1.0, Transform::Normal);
3886 queue.pop();
3887 warn!("error rendering for screencopy: {err:?}");
3888 }
3889 }
3890 };
3891 }
3892 }
3893
3894 self.screencopy_state = screencopy_state;
3895 }
3896
3897 pub fn render_for_screencopy_without_damage(
3898 &mut self,
3899 renderer: &mut GlesRenderer,
3900 manager: &ZwlrScreencopyManagerV1,
3901 screencopy: Screencopy,
3902 ) -> anyhow::Result<()> {
3903 let _span = tracy_client::span!("Niri::render_for_screencopy");
3904
3905 let output = screencopy.output();
3906 ensure!(
3907 self.output_state.contains_key(output),
3908 "screencopy output missing"
3909 );
3910
3911 self.update_render_elements(Some(output));
3912
3913 let elements = self.render(
3914 renderer,
3915 output,
3916 screencopy.overlay_cursor(),
3917 RenderTarget::ScreenCapture,
3918 );
3919 let Some(queue) = self.screencopy_state.get_queue_mut(manager) else {
3920 bail!("screencopy manager destroyed already");
3921 };
3922 let damage_tracker = queue.split().0;
3923
3924 let render_result = Self::render_for_screencopy_internal(
3925 renderer,
3926 output,
3927 &elements,
3928 false,
3929 damage_tracker,
3930 &screencopy,
3931 );
3932
3933 let res = render_result
3934 .map(|(sync, _damage)| screencopy.submit_after_sync(false, sync, &self.event_loop));
3935
3936 if res.is_err() {
3937 // Recreate damage tracker to report full damage next check.
3938 *damage_tracker = OutputDamageTracker::new((0, 0), 1.0, Transform::Normal);
3939 }
3940
3941 res
3942 }
3943
3944 #[allow(clippy::type_complexity)]
3945 fn render_for_screencopy_internal<'a>(
3946 renderer: &mut GlesRenderer,
3947 output: &Output,
3948 elements: &[OutputRenderElements<GlesRenderer>],
3949 with_damage: bool,
3950 damage_tracker: &'a mut OutputDamageTracker,
3951 screencopy: &Screencopy,
3952 ) -> anyhow::Result<(Option<SyncPoint>, Option<&'a Vec<Rectangle<i32, Physical>>>)> {
3953 let OutputModeSource::Static {
3954 size: last_size,
3955 scale: last_scale,
3956 transform: last_transform,
3957 } = damage_tracker.mode().clone()
3958 else {
3959 unreachable!("damage tracker must have static mode");
3960 };
3961
3962 let size = screencopy.buffer_size();
3963 let scale: Scale<f64> = output.current_scale().fractional_scale().into();
3964 let transform = output.current_transform();
3965
3966 if size != last_size || scale != last_scale || transform != last_transform {
3967 *damage_tracker = OutputDamageTracker::new(size, scale, transform);
3968 }
3969
3970 let region_loc = screencopy.region_loc();
3971 let elements = elements
3972 .iter()
3973 .map(|element| {
3974 RelocateRenderElement::from_element(
3975 element,
3976 region_loc.upscale(-1),
3977 Relocate::Relative,
3978 )
3979 })
3980 .collect::<Vec<_>>();
3981
3982 // Just checked damage tracker has static mode
3983 let damages = damage_tracker.damage_output(1, &elements).unwrap().0;
3984 if with_damage && damages.is_none() {
3985 return Ok((None, None));
3986 }
3987
3988 let elements = elements.iter().rev();
3989
3990 let sync = match screencopy.buffer() {
3991 ScreencopyBuffer::Dmabuf(dmabuf) => {
3992 let sync =
3993 render_to_dmabuf(renderer, dmabuf.clone(), size, scale, transform, elements)
3994 .context("error rendering to screencopy dmabuf")?;
3995 Some(sync)
3996 }
3997 ScreencopyBuffer::Shm(wl_buffer) => {
3998 render_to_shm(renderer, wl_buffer, size, scale, transform, elements)
3999 .context("error rendering to screencopy shm buffer")?;
4000 None
4001 }
4002 };
4003
4004 if let Err(err) = renderer.unbind() {
4005 warn!("error unbinding after rendering for screencopy: {err:?}");
4006 }
4007
4008 Ok((sync, damages))
4009 }
4010
4011 #[cfg(feature = "xdp-gnome-screencast")]
4012 fn stop_cast(&mut self, session_id: usize) {
4013 let _span = tracy_client::span!("Niri::stop_cast");
4014
4015 debug!(session_id, "StopCast");
4016
4017 for i in (0..self.casts.len()).rev() {
4018 let cast = &self.casts[i];
4019 if cast.session_id != session_id {
4020 continue;
4021 }
4022
4023 let cast = self.casts.swap_remove(i);
4024 if let Err(err) = cast.stream.disconnect() {
4025 warn!("error disconnecting stream: {err:?}");
4026 }
4027 }
4028
4029 let dbus = &self.dbus.as_ref().unwrap();
4030 let server = dbus.conn_screen_cast.as_ref().unwrap().object_server();
4031 let path = format!("/org/gnome/Mutter/ScreenCast/Session/u{}", session_id);
4032 if let Ok(iface) = server.interface::<_, mutter_screen_cast::Session>(path) {
4033 let _span = tracy_client::span!("invoking Session::stop");
4034
4035 async_io::block_on(async move {
4036 iface
4037 .get()
4038 .stop(&server, iface.signal_context().clone())
4039 .await
4040 });
4041 }
4042 }
4043
4044 #[cfg(feature = "xdp-gnome-screencast")]
4045 pub fn stop_casts_for_target(&mut self, target: CastTarget) {
4046 let _span = tracy_client::span!("Niri::stop_casts_for_target");
4047
4048 // This is O(N^2) but it shouldn't be a problem I think.
4049 let ids: Vec<_> = self
4050 .casts
4051 .iter()
4052 .filter(|cast| cast.target == target)
4053 .map(|cast| cast.session_id)
4054 .collect();
4055
4056 for id in ids {
4057 self.stop_cast(id);
4058 }
4059 }
4060
4061 pub fn remove_screencopy_output(&mut self, output: &Output) {
4062 let _span = tracy_client::span!("Niri::remove_screencopy_output");
4063 for queue in self.screencopy_state.queues_mut() {
4064 queue.remove_output(output);
4065 }
4066 }
4067
4068 pub fn debug_toggle_damage(&mut self) {
4069 self.debug_draw_damage = !self.debug_draw_damage;
4070
4071 if self.debug_draw_damage {
4072 for (output, state) in &mut self.output_state {
4073 state.debug_damage_tracker = OutputDamageTracker::from_output(output);
4074 }
4075 }
4076
4077 self.queue_redraw_all();
4078 }
4079
4080 pub fn capture_screenshots<'a>(
4081 &'a self,
4082 renderer: &'a mut GlesRenderer,
4083 ) -> impl Iterator<Item = (Output, [OutputScreenshot; 3])> + 'a {
4084 self.global_space.outputs().cloned().filter_map(|output| {
4085 let size = output.current_mode().unwrap().size;
4086 let transform = output.current_transform();
4087 let size = transform.transform_size(size);
4088
4089 let scale = Scale::from(output.current_scale().fractional_scale());
4090 let targets = [
4091 RenderTarget::Output,
4092 RenderTarget::Screencast,
4093 RenderTarget::ScreenCapture,
4094 ];
4095 let screenshot = targets.map(|target| {
4096 let elements = self.render::<GlesRenderer>(renderer, &output, false, target);
4097 let elements = elements.iter().rev();
4098
4099 let res = render_to_texture(
4100 renderer,
4101 size,
4102 scale,
4103 Transform::Normal,
4104 Fourcc::Abgr8888,
4105 elements,
4106 );
4107 if let Err(err) = &res {
4108 warn!("error rendering output {}: {err:?}", output.name());
4109 }
4110 let res_output = res.ok();
4111
4112 let pointer = self.pointer_element(renderer, &output);
4113 let res_pointer = if pointer.is_empty() {
4114 None
4115 } else {
4116 let res = render_to_encompassing_texture(
4117 renderer,
4118 scale,
4119 Transform::Normal,
4120 Fourcc::Abgr8888,
4121 &pointer,
4122 );
4123 if let Err(err) = &res {
4124 warn!("error rendering pointer for {}: {err:?}", output.name());
4125 }
4126 res.ok()
4127 };
4128
4129 res_output.map(|(texture, _)| {
4130 OutputScreenshot::from_textures(
4131 renderer,
4132 scale,
4133 texture,
4134 res_pointer.map(|(texture, _, geo)| (texture, geo)),
4135 )
4136 })
4137 });
4138
4139 if screenshot.iter().any(|res| res.is_none()) {
4140 return None;
4141 }
4142
4143 let screenshot = screenshot.map(|res| res.unwrap());
4144 Some((output, screenshot))
4145 })
4146 }
4147
4148 pub fn screenshot(
4149 &mut self,
4150 renderer: &mut GlesRenderer,
4151 output: &Output,
4152 ) -> anyhow::Result<()> {
4153 let _span = tracy_client::span!("Niri::screenshot");
4154
4155 self.update_render_elements(Some(output));
4156
4157 let size = output.current_mode().unwrap().size;
4158 let transform = output.current_transform();
4159 let size = transform.transform_size(size);
4160
4161 let scale = Scale::from(output.current_scale().fractional_scale());
4162 let elements =
4163 self.render::<GlesRenderer>(renderer, output, true, RenderTarget::ScreenCapture);
4164 let elements = elements.iter().rev();
4165 let pixels = render_to_vec(
4166 renderer,
4167 size,
4168 scale,
4169 Transform::Normal,
4170 Fourcc::Abgr8888,
4171 elements,
4172 )?;
4173
4174 self.save_screenshot(size, pixels)
4175 .context("error saving screenshot")
4176 }
4177
4178 pub fn screenshot_window(
4179 &self,
4180 renderer: &mut GlesRenderer,
4181 output: &Output,
4182 mapped: &Mapped,
4183 ) -> anyhow::Result<()> {
4184 let _span = tracy_client::span!("Niri::screenshot_window");
4185
4186 let scale = Scale::from(output.current_scale().fractional_scale());
4187 let alpha = if mapped.is_fullscreen() {
4188 1.
4189 } else {
4190 mapped.rules().opacity.unwrap_or(1.).clamp(0., 1.)
4191 };
4192 // FIXME: pointer.
4193 let elements = mapped.render(
4194 renderer,
4195 mapped.window.geometry().loc.to_f64(),
4196 scale,
4197 alpha,
4198 RenderTarget::ScreenCapture,
4199 );
4200 let geo = elements
4201 .iter()
4202 .map(|ele| ele.geometry(scale))
4203 .reduce(|a, b| a.merge(b))
4204 .unwrap_or_default();
4205
4206 let elements = elements.iter().rev().map(|elem| {
4207 RelocateRenderElement::from_element(elem, geo.loc.upscale(-1), Relocate::Relative)
4208 });
4209 let pixels = render_to_vec(
4210 renderer,
4211 geo.size,
4212 scale,
4213 Transform::Normal,
4214 Fourcc::Abgr8888,
4215 elements,
4216 )?;
4217
4218 self.save_screenshot(geo.size, pixels)
4219 .context("error saving screenshot")
4220 }
4221
4222 pub fn save_screenshot(
4223 &self,
4224 size: Size<i32, Physical>,
4225 pixels: Vec<u8>,
4226 ) -> anyhow::Result<()> {
4227 let path = match make_screenshot_path(&self.config.borrow()) {
4228 Ok(path) => path,
4229 Err(err) => {
4230 warn!("error making screenshot path: {err:?}");
4231 None
4232 }
4233 };
4234
4235 // Prepare to set the encoded image as our clipboard selection. This must be done from the
4236 // main thread.
4237 let (tx, rx) = calloop::channel::sync_channel::<Arc<[u8]>>(1);
4238 self.event_loop
4239 .insert_source(rx, move |event, _, state| match event {
4240 calloop::channel::Event::Msg(buf) => {
4241 set_data_device_selection(
4242 &state.niri.display_handle,
4243 &state.niri.seat,
4244 vec![String::from("image/png")],
4245 buf.clone(),
4246 );
4247 }
4248 calloop::channel::Event::Closed => (),
4249 })
4250 .unwrap();
4251
4252 // Encode and save the image in a thread as it's slow.
4253 thread::spawn(move || {
4254 let mut buf = vec![];
4255
4256 let w = std::io::Cursor::new(&mut buf);
4257 if let Err(err) = write_png_rgba8(w, size.w as u32, size.h as u32, &pixels) {
4258 warn!("error encoding screenshot image: {err:?}");
4259 return;
4260 }
4261
4262 let buf: Arc<[u8]> = Arc::from(buf.into_boxed_slice());
4263 let _ = tx.send(buf.clone());
4264
4265 let mut image_path = None;
4266
4267 if let Some(path) = path {
4268 debug!("saving screenshot to {path:?}");
4269
4270 if let Some(parent) = path.parent() {
4271 if let Err(err) = std::fs::create_dir(parent) {
4272 if err.kind() != std::io::ErrorKind::AlreadyExists {
4273 warn!("error creating screenshot directory: {err:?}");
4274 }
4275 }
4276 }
4277
4278 match std::fs::write(&path, buf) {
4279 Ok(()) => image_path = Some(path),
4280 Err(err) => {
4281 warn!("error saving screenshot image: {err:?}");
4282 }
4283 }
4284 } else {
4285 debug!("not saving screenshot to disk");
4286 }
4287
4288 #[cfg(feature = "dbus")]
4289 crate::utils::show_screenshot_notification(image_path);
4290 #[cfg(not(feature = "dbus"))]
4291 drop(image_path);
4292 });
4293
4294 Ok(())
4295 }
4296
4297 #[cfg(feature = "dbus")]
4298 pub fn screenshot_all_outputs(
4299 &mut self,
4300 renderer: &mut GlesRenderer,
4301 include_pointer: bool,
4302 on_done: impl FnOnce(PathBuf) + Send + 'static,
4303 ) -> anyhow::Result<()> {
4304 let _span = tracy_client::span!("Niri::screenshot_all_outputs");
4305
4306 self.update_render_elements(None);
4307
4308 let outputs: Vec<_> = self.global_space.outputs().cloned().collect();
4309
4310 // FIXME: support multiple outputs, needs fixing multi-scale handling and cropping.
4311 anyhow::ensure!(outputs.len() == 1);
4312
4313 let output = outputs.into_iter().next().unwrap();
4314 let geom = self.global_space.output_geometry(&output).unwrap();
4315
4316 let output_scale = output.current_scale().integer_scale();
4317 let geom = geom.to_physical(output_scale);
4318
4319 let size = geom.size;
4320 let transform = output.current_transform();
4321 let size = transform.transform_size(size);
4322
4323 let elements = self.render::<GlesRenderer>(
4324 renderer,
4325 &output,
4326 include_pointer,
4327 RenderTarget::ScreenCapture,
4328 );
4329 let elements = elements.iter().rev();
4330 let pixels = render_to_vec(
4331 renderer,
4332 size,
4333 Scale::from(f64::from(output_scale)),
4334 Transform::Normal,
4335 Fourcc::Abgr8888,
4336 elements,
4337 )?;
4338
4339 let path = make_screenshot_path(&self.config.borrow())
4340 .ok()
4341 .flatten()
4342 .unwrap_or_else(|| {
4343 let mut path = env::temp_dir();
4344 path.push("screenshot.png");
4345 path
4346 });
4347 debug!("saving screenshot to {path:?}");
4348
4349 thread::spawn(move || {
4350 let file = match std::fs::File::create(&path) {
4351 Ok(file) => file,
4352 Err(err) => {
4353 warn!("error creating file: {err:?}");
4354 return;
4355 }
4356 };
4357
4358 let w = std::io::BufWriter::new(file);
4359 if let Err(err) = write_png_rgba8(w, size.w as u32, size.h as u32, &pixels) {
4360 warn!("error encoding screenshot image: {err:?}");
4361 return;
4362 }
4363
4364 on_done(path);
4365 });
4366
4367 Ok(())
4368 }
4369
4370 pub fn is_locked(&self) -> bool {
4371 !matches!(self.lock_state, LockState::Unlocked)
4372 }
4373
4374 pub fn lock(&mut self, confirmation: SessionLocker) {
4375 // Check if another client is in the process of locking.
4376 if matches!(self.lock_state, LockState::Locking(_)) {
4377 info!("refusing lock as another client is currently locking");
4378 return;
4379 }
4380
4381 // Check if we're already locked with an active client.
4382 if let LockState::Locked(lock) = &self.lock_state {
4383 if lock.is_alive() {
4384 info!("refusing lock as already locked with an active client");
4385 return;
4386 }
4387
4388 // If the client had died, continue with the new lock.
4389 }
4390
4391 info!("locking session");
4392
4393 self.screenshot_ui.close();
4394 self.cursor_manager
4395 .set_cursor_image(CursorImageStatus::default_named());
4396
4397 self.lock_state = LockState::Locking(confirmation);
4398 self.queue_redraw_all();
4399 }
4400
4401 pub fn unlock(&mut self) {
4402 info!("unlocking session");
4403
4404 self.lock_state = LockState::Unlocked;
4405 for output_state in self.output_state.values_mut() {
4406 output_state.lock_surface = None;
4407 }
4408 self.queue_redraw_all();
4409 }
4410
4411 pub fn new_lock_surface(&mut self, surface: LockSurface, output: &Output) {
4412 if !self.is_locked() {
4413 error!("tried to add a lock surface on an unlocked session");
4414 return;
4415 }
4416
4417 let Some(output_state) = self.output_state.get_mut(output) else {
4418 error!("missing output state");
4419 return;
4420 };
4421
4422 output_state.lock_surface = Some(surface);
4423 }
4424
4425 pub fn maybe_activate_pointer_constraint(
4426 &self,
4427 new_pos: Point<f64, Logical>,
4428 new_under: &PointerFocus,
4429 ) {
4430 let Some((surface, surface_loc)) = &new_under.surface else {
4431 return;
4432 };
4433 if self.pointer_grab_ongoing {
4434 return;
4435 }
4436 let pointer = &self.seat.get_pointer().unwrap();
4437 with_pointer_constraint(surface, pointer, |constraint| {
4438 let Some(constraint) = constraint else { return };
4439
4440 if constraint.is_active() {
4441 return;
4442 }
4443
4444 // Constraint does not apply if not within region.
4445 if let Some(region) = constraint.region() {
4446 let new_pos_within_surface = new_pos - *surface_loc;
4447 if !region.contains(new_pos_within_surface.to_i32_round()) {
4448 return;
4449 }
4450 }
4451
4452 constraint.activate();
4453 });
4454 }
4455
4456 pub fn focus_layer_surface_if_on_demand(&mut self, surface: Option<LayerSurface>) {
4457 if let Some(surface) = surface {
4458 if surface.cached_state().keyboard_interactivity
4459 == wlr_layer::KeyboardInteractivity::OnDemand
4460 {
4461 if self.layer_shell_on_demand_focus.as_ref() != Some(&surface) {
4462 self.layer_shell_on_demand_focus = Some(surface);
4463
4464 // FIXME: granular.
4465 self.queue_redraw_all();
4466 }
4467
4468 return;
4469 }
4470 }
4471
4472 // Something else got clicked, clear on-demand layer-shell focus.
4473 if self.layer_shell_on_demand_focus.is_some() {
4474 self.layer_shell_on_demand_focus = None;
4475
4476 // FIXME: granular.
4477 self.queue_redraw_all();
4478 }
4479 }
4480
4481 #[cfg(feature = "dbus")]
4482 pub fn on_ipc_outputs_changed(&self) {
4483 let _span = tracy_client::span!("Niri::on_ipc_outputs_changed");
4484
4485 let Some(dbus) = &self.dbus else { return };
4486 let Some(conn_display_config) = dbus.conn_display_config.clone() else {
4487 return;
4488 };
4489
4490 let res = thread::Builder::new()
4491 .name("DisplayConfig MonitorsChanged Emitter".to_owned())
4492 .spawn(move || {
4493 use crate::dbus::mutter_display_config::DisplayConfig;
4494 let _span = tracy_client::span!("MonitorsChanged");
4495 let iface = match conn_display_config
4496 .object_server()
4497 .interface::<_, DisplayConfig>("/org/gnome/Mutter/DisplayConfig")
4498 {
4499 Ok(iface) => iface,
4500 Err(err) => {
4501 warn!("error getting DisplayConfig interface: {err:?}");
4502 return;
4503 }
4504 };
4505
4506 async_io::block_on(async move {
4507 if let Err(err) = DisplayConfig::monitors_changed(iface.signal_context()).await
4508 {
4509 warn!("error emitting MonitorsChanged: {err:?}");
4510 }
4511 });
4512 });
4513
4514 if let Err(err) = res {
4515 warn!("error spawning a thread to send MonitorsChanged: {err:?}");
4516 }
4517 }
4518
4519 pub fn handle_focus_follows_mouse(&mut self, new_focus: &PointerFocus) {
4520 let Some(ffm) = self.config.borrow().input.focus_follows_mouse else {
4521 return;
4522 };
4523
4524 let pointer = &self.seat.get_pointer().unwrap();
4525 if pointer.is_grabbed() {
4526 return;
4527 }
4528
4529 // Recompute the current pointer focus because we don't update it during animations.
4530 let current_focus = self.surface_under_and_global_space(pointer.current_location());
4531
4532 if let Some(output) = &new_focus.output {
4533 if current_focus.output.as_ref() != Some(output) {
4534 self.layout.focus_output(output);
4535 }
4536 }
4537
4538 if let Some(window) = &new_focus.window {
4539 if current_focus.window.as_ref() != Some(window) {
4540 if let Some(threshold) = ffm.max_scroll_amount {
4541 if self.layout.scroll_amount_to_activate(window) > threshold.0 {
4542 return;
4543 }
4544 }
4545
4546 self.layout.activate_window(window);
4547 self.layer_shell_on_demand_focus = None;
4548 }
4549 }
4550
4551 if let Some(layer) = &new_focus.layer {
4552 if current_focus.layer.as_ref() != Some(layer) {
4553 self.layer_shell_on_demand_focus = Some(layer.clone());
4554 }
4555 }
4556 }
4557
4558 pub fn do_screen_transition(&mut self, renderer: &mut GlesRenderer, delay_ms: Option<u16>) {
4559 let _span = tracy_client::span!("Niri::do_screen_transition");
4560
4561 self.update_render_elements(None);
4562
4563 let textures: Vec<_> = self
4564 .output_state
4565 .keys()
4566 .cloned()
4567 .filter_map(|output| {
4568 let size = output.current_mode().unwrap().size;
4569 let transform = output.current_transform();
4570
4571 let scale = Scale::from(output.current_scale().fractional_scale());
4572 let targets = [
4573 RenderTarget::Output,
4574 RenderTarget::Screencast,
4575 RenderTarget::ScreenCapture,
4576 ];
4577 let textures = targets.map(|target| {
4578 let elements = self.render::<GlesRenderer>(renderer, &output, false, target);
4579 let elements = elements.iter().rev();
4580
4581 let res = render_to_texture(
4582 renderer,
4583 size,
4584 scale,
4585 transform,
4586 Fourcc::Abgr8888,
4587 elements,
4588 );
4589
4590 if let Err(err) = &res {
4591 warn!("error rendering output {}: {err:?}", output.name());
4592 }
4593
4594 res
4595 });
4596
4597 if textures.iter().any(|res| res.is_err()) {
4598 return None;
4599 }
4600
4601 let textures = textures.map(|res| {
4602 let texture = res.unwrap().0;
4603 TextureBuffer::from_texture(
4604 renderer,
4605 texture,
4606 scale,
4607 transform,
4608 Vec::new(), // We want windows below to get frame callbacks.
4609 )
4610 });
4611
4612 Some((output, textures))
4613 })
4614 .collect();
4615
4616 let delay = delay_ms.map_or(screen_transition::DELAY, |d| {
4617 Duration::from_millis(u64::from(d))
4618 });
4619 let start_at = get_monotonic_time() + delay;
4620 for (output, from_texture) in textures {
4621 let state = self.output_state.get_mut(&output).unwrap();
4622 state.screen_transition = Some(ScreenTransition::new(from_texture, start_at));
4623 }
4624
4625 // We don't actually need to queue a redraw because the point is to freeze the screen for a
4626 // bit, and even if the delay was zero, we're drawing the same contents anyway.
4627 }
4628
4629 pub fn recompute_window_rules(&mut self) {
4630 let _span = tracy_client::span!("Niri::recompute_window_rules");
4631
4632 let changed = {
4633 let window_rules = &self.config.borrow().window_rules;
4634
4635 for unmapped in self.unmapped_windows.values_mut() {
4636 let new_rules = ResolvedWindowRules::compute(
4637 window_rules,
4638 WindowRef::Unmapped(unmapped),
4639 self.is_at_startup,
4640 );
4641 if let InitialConfigureState::Configured { rules, .. } = &mut unmapped.state {
4642 *rules = new_rules;
4643 }
4644 }
4645
4646 let mut windows = vec![];
4647 self.layout.with_windows_mut(|mapped, _| {
4648 if mapped.recompute_window_rules(window_rules, self.is_at_startup) {
4649 windows.push(mapped.window.clone());
4650 }
4651 });
4652 let changed = !windows.is_empty();
4653 for win in windows {
4654 self.layout.update_window(&win, None);
4655 }
4656 changed
4657 };
4658
4659 if changed {
4660 // FIXME: granular.
4661 self.queue_redraw_all();
4662 }
4663 }
4664}
4665
4666pub struct ClientState {
4667 pub compositor_state: CompositorClientState,
4668 pub can_view_decoration_globals: bool,
4669 /// Whether this client is denied from the restricted protocols such as security-context.
4670 pub restricted: bool,
4671}
4672
4673impl ClientData for ClientState {
4674 fn initialized(&self, _client_id: ClientId) {}
4675 fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {}
4676}
4677
4678niri_render_elements! {
4679 OutputRenderElements<R> => {
4680 Monitor = MonitorRenderElement<R>,
4681 Wayland = WaylandSurfaceRenderElement<R>,
4682 NamedPointer = MemoryRenderBufferRenderElement<R>,
4683 SolidColor = SolidColorRenderElement,
4684 ScreenshotUi = ScreenshotUiRenderElement,
4685 Texture = PrimaryGpuTextureRenderElement,
4686 // Used for the CPU-rendered panels.
4687 RelocatedMemoryBuffer = RelocateRenderElement<MemoryRenderBufferRenderElement<R>>,
4688 }
4689}