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