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