forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB53500dcTahinli1 month ago2998 commits

mod.rs5098 lines, 175.4 KiBHistoryRawDownload
1//! Window layout logic.
2//!
3//! Niri implements scrollable tiling with dynamic workspaces. The scrollable tiling is mostly
4//! orthogonal to any particular workspace system, though outputs living in separate coordinate
5//! spaces suggest per-output workspaces.
6//!
7//! I chose a dynamic workspace system because I think it works very well. In particular, it works
8//! naturally across outputs getting added and removed, since workspaces can move between outputs
9//! as necessary.
10//!
11//! In the layout, one output (the first one to be added) is designated as *primary*. This is where
12//! workspaces from disconnected outputs will move. Currently, the primary output has no other
13//! distinction from other outputs.
14//!
15//! Where possible, niri tries to follow these principles with regards to outputs:
16//!
17//! 1. Disconnecting and reconnecting the same output must not change the layout.
18//! * This includes both secondary outputs and the primary output.
19//! 2. Connecting an output must not change the layout for any workspaces that were never on that
20//! output.
21//!
22//! Therefore, we implement the following logic: every workspace keeps track of its ordered
23//! original output candidates. When an output disconnects, its workspaces move to the first
24//! connected candidate or the (potentially new) primary output. When a higher-priority candidate
25//! connects, matching workspaces move to it.
26//!
27//! In order to avoid surprising behavior, if the user creates or moves any new windows onto a
28//! workspace, it forgets its original output, and its current output becomes its original output.
29//! Imagine a scenario: the user works with a laptop and a monitor at home, then takes their laptop
30//! with them, disconnecting the monitor, and keeps working as normal, using the second monitor's
31//! workspace just like any other. Then they come back, reconnect the second monitor, and now we
32//! don't want an unassuming workspace to end up on it.
33
34use std::collections::HashMap;
35use std::mem;
36use std::rc::Rc;
37use std::time::Duration;
38
39use monitor::{InsertHint, InsertPosition, InsertWorkspace, MonitorAddWindowTarget};
40use niri_config::utils::MergeWith as _;
41use niri_config::{
42 Config, CornerRadius, LayoutPart, PresetSize, Workspace as WorkspaceConfig, WorkspaceReference,
43};
44use niri_ipc::{ColumnDisplay, PositionChange, SizeChange, WindowLayout};
45use scrolling::{Column, ColumnWidth};
46use smithay::backend::renderer::element::surface::WaylandSurfaceRenderElement;
47use smithay::backend::renderer::element::utils::RescaleRenderElement;
48use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
49use smithay::output::{self, Output};
50use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
51use smithay::utils::{Logical, Point, Rectangle, Scale, Serial, Size, Transform};
52use tile::{Tile, TileRenderElement};
53use workspace::{WorkspaceAddWindowTarget, WorkspaceId};
54
55pub use self::monitor::MonitorRenderElement;
56use self::monitor::{Monitor, WorkspaceSwitch};
57use self::workspace::{OutputId, Workspace};
58use crate::animation::{Animation, Clock};
59use crate::input::swipe_tracker::SwipeTracker;
60use crate::layout::scrolling::ScrollDirection;
61use crate::niri_render_elements;
62use crate::render_helpers::background_effect::BackgroundEffectElement;
63use crate::render_helpers::offscreen::OffscreenData;
64use crate::render_helpers::renderer::NiriRenderer;
65use crate::render_helpers::snapshot::RenderSnapshot;
66use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
67use crate::render_helpers::texture::TextureBuffer;
68use crate::render_helpers::xray::{Xray, XrayPos};
69use crate::render_helpers::{BakedBuffer, RenderCtx};
70use crate::rubber_band::RubberBand;
71use crate::utils::transaction::{Transaction, TransactionBlocker};
72use crate::utils::{
73 ensure_min_max_size_maybe_zero, output_matches_name, output_size,
74 round_logical_in_physical_max1, ResizeEdge,
75};
76use crate::window::ResolvedWindowRules;
77
78pub mod closing_window;
79pub mod floating;
80pub mod focus_ring;
81pub mod insert_hint_element;
82pub mod monitor;
83pub mod opening_window;
84pub mod scrolling;
85pub mod shadow;
86pub mod tab_indicator;
87pub mod tile;
88pub mod workspace;
89
90#[cfg(test)]
91mod tests;
92
93/// Size changes up to this many pixels don't animate.
94pub const RESIZE_ANIMATION_THRESHOLD: f64 = 10.;
95
96/// Pointer needs to move this far to pull a window from the layout.
97const INTERACTIVE_MOVE_START_THRESHOLD: f64 = 256. * 256.;
98
99/// Opacity of interactively moved tiles targeting the scrolling layout.
100const INTERACTIVE_MOVE_ALPHA: f64 = 0.75;
101
102/// Amount of touchpad movement to toggle the overview.
103const OVERVIEW_GESTURE_MOVEMENT: f64 = 300.;
104
105const OVERVIEW_GESTURE_RUBBER_BAND: RubberBand = RubberBand {
106 stiffness: 0.5,
107 limit: 0.05,
108};
109
110/// Size-relative units.
111pub struct SizeFrac;
112
113niri_render_elements! {
114 LayoutElementRenderElement<R> => {
115 Wayland = WaylandSurfaceRenderElement<R>,
116 SolidColor = SolidColorRenderElement,
117 BackgroundEffect = BackgroundEffectElement,
118 }
119}
120
121pub type LayoutElementRenderSnapshot =
122 RenderSnapshot<BakedBuffer<TextureBuffer<GlesTexture>>, BakedBuffer<SolidColorBuffer>>;
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum SizingMode {
126 Normal,
127 Maximized,
128 Fullscreen,
129}
130
131pub trait LayoutElement {
132 /// Type that can be used as a unique ID of this element.
133 type Id: PartialEq + std::fmt::Debug + Clone;
134
135 /// Unique ID of this element.
136 fn id(&self) -> &Self::Id;
137
138 /// Updates the config for the element.
139 fn update_config(&mut self, blur_config: niri_config::Blur) {
140 let _ = blur_config;
141 }
142
143 /// Visual size of the element.
144 ///
145 /// This is what the user would consider the size, i.e. excluding CSD shadows and whatnot.
146 /// Corresponds to the Wayland window geometry size.
147 fn size(&self) -> Size<i32, Logical>;
148
149 /// Returns the location of the element's buffer relative to the element's visual geometry.
150 ///
151 /// I.e. if the element has CSD shadows, its buffer location will have negative coordinates.
152 fn buf_loc(&self) -> Point<i32, Logical>;
153
154 /// Checks whether a point is in the element's input region.
155 ///
156 /// The point is relative to the element's visual geometry.
157 fn is_in_input_region(&self, point: Point<f64, Logical>) -> bool;
158
159 /// Renders the element at the given visual location.
160 ///
161 /// The element should be rendered in such a way that its visual geometry ends up at the given
162 /// location.
163 fn render<R: NiriRenderer>(
164 &self,
165 mut ctx: RenderCtx<R>,
166 location: Point<f64, Logical>,
167 scale: Scale<f64>,
168 alpha: f32,
169 xray_pos: XrayPos,
170 push: &mut dyn FnMut(LayoutElementRenderElement<R>),
171 ) {
172 self.render_popups(ctx.r(), location, scale, alpha, xray_pos, push);
173 self.render_normal(ctx.r(), location, scale, alpha, push);
174 }
175
176 /// Renders the non-popup parts of the element.
177 fn render_normal<R: NiriRenderer>(
178 &self,
179 ctx: RenderCtx<R>,
180 location: Point<f64, Logical>,
181 scale: Scale<f64>,
182 alpha: f32,
183 push: &mut dyn FnMut(LayoutElementRenderElement<R>),
184 ) {
185 let _ = (ctx, location, scale, alpha, push);
186 }
187
188 /// Renders the popups of the element.
189 fn render_popups<R: NiriRenderer>(
190 &self,
191 ctx: RenderCtx<R>,
192 location: Point<f64, Logical>,
193 scale: Scale<f64>,
194 alpha: f32,
195 xray_pos: XrayPos,
196 push: &mut dyn FnMut(LayoutElementRenderElement<R>),
197 ) {
198 let _ = (ctx, location, scale, alpha, xray_pos, push);
199 }
200
201 /// Renders the background effect behind the main surface of the element.
202 #[allow(clippy::too_many_arguments)]
203 fn render_background_effect(
204 &self,
205 _ctx: RenderCtx<GlesRenderer>,
206 _geometry: Rectangle<f64, Logical>,
207 _scale: f64,
208 _clip_to_geometry: bool,
209 _surface_anim_scale: Scale<f64>,
210 _radius: CornerRadius,
211 _xray_pos: XrayPos,
212 _push: &mut dyn FnMut(BackgroundEffectElement),
213 ) {
214 }
215
216 /// Requests the element to change its size.
217 ///
218 /// The size request is stored and will be continuously sent to the element on any further
219 /// state changes.
220 fn request_size(
221 &mut self,
222 size: Size<i32, Logical>,
223 mode: SizingMode,
224 animate: bool,
225 transaction: Option<Transaction>,
226 );
227
228 /// Requests the element to change size once, clearing the request afterwards.
229 fn request_size_once(&mut self, size: Size<i32, Logical>, animate: bool) {
230 self.request_size(size, SizingMode::Normal, animate, None);
231 }
232
233 fn min_size(&self) -> Size<i32, Logical>;
234 fn max_size(&self) -> Size<i32, Logical>;
235 fn is_wl_surface(&self, wl_surface: &WlSurface) -> bool;
236 fn has_ssd(&self) -> bool;
237 fn set_preferred_scale_transform(&self, scale: output::Scale, transform: Transform);
238 fn output_enter(&self, output: &Output);
239 fn output_leave(&self, output: &Output);
240 fn set_offscreen_data(&self, data: Option<OffscreenData>);
241 fn set_activated(&mut self, active: bool);
242 fn set_active_in_column(&mut self, active: bool);
243 fn set_floating(&mut self, floating: bool);
244 fn set_bounds(&self, bounds: Size<i32, Logical>);
245 fn is_ignoring_opacity_window_rule(&self) -> bool;
246
247 fn is_urgent(&self) -> bool;
248
249 fn configure_intent(&self) -> ConfigureIntent;
250 fn send_pending_configure(&mut self);
251
252 /// The element's current sizing mode.
253 ///
254 /// This will *not* switch immediately after a [`LayoutElement::request_size()`] call.
255 fn sizing_mode(&self) -> SizingMode;
256
257 /// The sizing mode that we're requesting the element to assume.
258 ///
259 /// This *will* switch immediately after a [`LayoutElement::request_size()`] call.
260 fn pending_sizing_mode(&self) -> SizingMode;
261
262 /// Size previously requested through [`LayoutElement::request_size()`].
263 fn requested_size(&self) -> Option<Size<i32, Logical>>;
264
265 /// Non-fullscreen size that we expect this window has or will shortly have.
266 ///
267 /// This can be different from [`requested_size()`](LayoutElement::requested_size()). For
268 /// example, for floating windows this will generally return the current window size, rather
269 /// than the last size that we requested, since we want floating windows to be able to change
270 /// size freely. But not always: if we just requested a floating window to resize and it hasn't
271 /// responded to it yet, this will return the newly requested size.
272 ///
273 /// This function should never return a 0 size component. `None` means there's no known
274 /// expected size (for example, the window is fullscreen).
275 ///
276 /// The default impl is for testing only, it will not preserve the window's own size changes.
277 fn expected_size(&self) -> Option<Size<i32, Logical>> {
278 if self.sizing_mode().is_fullscreen() {
279 return None;
280 }
281
282 let mut requested = self.requested_size().unwrap_or_default();
283 let current = self.size();
284 if requested.w == 0 {
285 requested.w = current.w;
286 }
287 if requested.h == 0 {
288 requested.h = current.h;
289 }
290 Some(requested)
291 }
292
293 fn is_windowed_fullscreen(&self) -> bool {
294 false
295 }
296 fn is_pending_windowed_fullscreen(&self) -> bool {
297 false
298 }
299 fn request_windowed_fullscreen(&mut self, value: bool) {
300 let _ = value;
301 }
302
303 /// The effective geometry corner radius for this element.
304 ///
305 /// Returns zero when the element is in windowed fullscreen, since fullscreen windows have
306 /// square corners.
307 ///
308 /// This method only handles windowed fullscreen and not maximized/real fullscreen. This is
309 /// because windowed fullscreen is handled by the element itself, whereas other sizing modes
310 /// are handled externally by the Tile, so the corner radius changes for those modes is also
311 /// handled externally.
312 fn geometry_corner_radius(&self) -> CornerRadius {
313 let rules = self.rules();
314
315 // When windows think they're fullscreen, they square their corners.
316 //
317 // However, if the user is clipping the window to geometry, they are likely going for
318 // consistent corner radius, and want this radius to remain in windowed fullscreen.
319 if self.is_windowed_fullscreen() && rules.clip_to_geometry != Some(true) {
320 return CornerRadius::default();
321 }
322
323 rules.geometry_corner_radius.unwrap_or_default()
324 }
325
326 fn is_child_of(&self, parent: &Self) -> bool;
327
328 fn rules(&self) -> &ResolvedWindowRules;
329
330 /// Runs periodic clean-up tasks.
331 fn refresh(&self);
332
333 fn take_animation_snapshot(&mut self) -> Option<LayoutElementRenderSnapshot>;
334
335 fn set_interactive_resize(&mut self, data: Option<InteractiveResizeData>);
336 fn cancel_interactive_resize(&mut self);
337 fn interactive_resize_data(&self) -> Option<InteractiveResizeData>;
338
339 fn on_commit(&mut self, serial: Serial);
340}
341
342#[derive(Debug)]
343pub struct Layout<W: LayoutElement> {
344 /// Monitors and workspaes in the layout.
345 monitor_set: MonitorSet<W>,
346 /// Whether the layout should draw as active.
347 ///
348 /// This normally indicates that the layout has keyboard focus, but not always. E.g. when the
349 /// screenshot UI is open, it keeps the layout drawing as active.
350 is_active: bool,
351 /// Map from monitor name to id of its last active workspace.
352 ///
353 /// This data is stored upon monitor removal and is used to restore the active workspace when
354 /// the monitor is reconnected.
355 ///
356 /// The workspace id does not necessarily point to a valid workspace. If it doesn't, then it is
357 /// simply ignored.
358 last_active_workspace_id: HashMap<String, WorkspaceId>,
359 /// Ongoing interactive move.
360 interactive_move: Option<InteractiveMoveState<W>>,
361 /// Ongoing drag-and-drop operation.
362 dnd: Option<DndData<W>>,
363 /// Clock for driving animations.
364 clock: Clock,
365 /// Time that we last updated render elements for.
366 update_render_elements_time: Duration,
367 /// Whether the overview is open.
368 ///
369 /// This is a boolean flag that controls things like where input goes to. The actual animation
370 /// is controlled by overview_progress.
371 overview_open: bool,
372 /// The overview zoom progress.
373 overview_progress: Option<OverviewProgress>,
374 /// Configurable properties of the layout.
375 options: Rc<Options>,
376}
377
378#[derive(Debug)]
379enum MonitorSet<W: LayoutElement> {
380 /// At least one output is connected.
381 Normal {
382 /// Connected monitors.
383 monitors: Vec<Monitor<W>>,
384 /// Index of the primary monitor.
385 primary_idx: usize,
386 /// Index of the active monitor.
387 active_monitor_idx: usize,
388 },
389 /// No outputs are connected, and these are the workspaces.
390 NoOutputs {
391 /// The workspaces.
392 workspaces: Vec<Workspace<W>>,
393 },
394}
395
396#[derive(Debug, Default, Clone, PartialEq)]
397pub struct Options {
398 pub layout: niri_config::Layout,
399 pub animations: niri_config::Animations,
400 pub gestures: niri_config::Gestures,
401 pub overview: niri_config::Overview,
402 pub blur: niri_config::Blur,
403 // Debug flags.
404 pub disable_resize_throttling: bool,
405 pub disable_transactions: bool,
406 pub deactivate_unfocused_windows: bool,
407}
408
409#[allow(clippy::large_enum_variant)]
410#[derive(Debug)]
411enum InteractiveMoveState<W: LayoutElement> {
412 /// Initial rubberbanding; the window remains in the layout.
413 Starting {
414 /// The window we're moving.
415 window_id: W::Id,
416 /// Current pointer delta from the starting location.
417 pointer_delta: Point<f64, Logical>,
418 /// Pointer location within the visual window geometry as ratio from geometry size.
419 ///
420 /// This helps the pointer remain inside the window as it resizes.
421 pointer_ratio_within_window: (f64, f64),
422 },
423 /// Moving; the window is no longer in the layout.
424 Moving(InteractiveMoveData<W>),
425}
426
427#[derive(Debug)]
428struct InteractiveMoveData<W: LayoutElement> {
429 /// The window being moved.
430 pub(self) tile: Tile<W>,
431 /// Output where the window is currently located/rendered.
432 pub(self) output: Output,
433 /// Current pointer position within output.
434 pub(self) pointer_pos_within_output: Point<f64, Logical>,
435 /// Window column width.
436 pub(self) width: ColumnWidth,
437 /// Whether the window column was full-width.
438 pub(self) is_full_width: bool,
439 /// Whether the window targets the floating layout.
440 pub(self) is_floating: bool,
441 /// Pointer location within the visual window geometry as ratio from geometry size.
442 ///
443 /// This helps the pointer remain inside the window as it resizes.
444 pub(self) pointer_ratio_within_window: (f64, f64),
445 /// Config overrides for the output where the window is currently located.
446 ///
447 /// Cached here to be accessible while an output is removed.
448 pub(self) output_config: Option<niri_config::LayoutPart>,
449 /// Config overrides for the workspace where the window is currently located.
450 ///
451 /// To avoid sudden window changes when starting an interactive move, it will remember the
452 /// config overrides for the workspace where the move originated from. As soon as the window
453 /// moves over some different workspace though, this override will reset.
454 pub(self) workspace_config: Option<(WorkspaceId, niri_config::LayoutPart)>,
455}
456
457#[derive(Debug)]
458pub struct DndData<W: LayoutElement> {
459 /// Output where the pointer is currently located.
460 output: Output,
461 /// Current pointer position within output.
462 pointer_pos_within_output: Point<f64, Logical>,
463 /// Ongoing DnD hold to activate something.
464 hold: Option<DndHold<W>>,
465}
466
467#[derive(Debug)]
468struct DndHold<W: LayoutElement> {
469 /// Time when we started holding on the target.
470 start_time: Duration,
471 target: DndHoldTarget<W::Id>,
472}
473
474#[derive(Debug, PartialEq, Eq)]
475enum DndHoldTarget<WindowId> {
476 Window(WindowId),
477 Workspace(WorkspaceId),
478}
479
480#[derive(Debug, Clone, Copy)]
481pub struct InteractiveResizeData {
482 pub(self) edges: ResizeEdge,
483}
484
485#[derive(Debug, Clone, Copy)]
486pub enum ConfigureIntent {
487 /// A configure is not needed (no changes to server pending state).
488 NotNeeded,
489 /// A configure is throttled (due to resizing too fast for example).
490 Throttled,
491 /// Can send the configure if it isn't throttled externally (only size changed).
492 CanSend,
493 /// Should send the configure regardless of external throttling (something other than size
494 /// changed).
495 ShouldSend,
496}
497
498/// Tile that was just removed from the layout.
499pub struct RemovedTile<W: LayoutElement> {
500 tile: Tile<W>,
501 /// Width of the column the tile was in.
502 width: ColumnWidth,
503 /// Whether the column the tile was in was full-width.
504 is_full_width: bool,
505 /// Whether the tile was floating.
506 is_floating: bool,
507}
508
509/// Whether to activate a newly added window.
510#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
511pub enum ActivateWindow {
512 /// Activate unconditionally.
513 Yes,
514 /// Activate based on heuristics.
515 #[default]
516 Smart,
517 /// Do not activate.
518 No,
519}
520
521/// Where to put a newly added window.
522#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
523pub enum AddWindowTarget<'a, W: LayoutElement> {
524 /// No particular preference.
525 #[default]
526 Auto,
527 /// On this output.
528 Output(&'a Output),
529 /// On this workspace.
530 Workspace(WorkspaceId),
531 /// Next to this existing window.
532 NextTo(&'a W::Id),
533}
534
535/// Type of the window hit from `window_under()`.
536#[derive(Debug, Clone, Copy, PartialEq)]
537pub enum HitType {
538 /// The hit is within a window's input region and can be used for sending events to it.
539 Input {
540 /// Position of the window's buffer.
541 win_pos: Point<f64, Logical>,
542 },
543 /// The hit can activate a window, but it is not in the input region so cannot send events.
544 ///
545 /// For example, this could be clicking on a tile border outside the window.
546 Activate {
547 /// Whether the hit was on the tab indicator.
548 is_tab_indicator: bool,
549 },
550}
551
552#[derive(Debug)]
553enum OverviewProgress {
554 Animation(Animation),
555 Gesture(OverviewGesture),
556 Open,
557}
558
559#[derive(Debug)]
560struct OverviewGesture {
561 tracker: SwipeTracker,
562 /// Start point.
563 start: f64,
564 /// Current progress.
565 value: f64,
566}
567
568/// Layer of windows to render.
569#[derive(Clone, Copy)]
570pub enum RenderLayer {
571 Normal,
572 /// Windows currently moving between workspaces.
573 MovingBetweenWorkspaces,
574}
575
576impl SizingMode {
577 #[must_use]
578 pub fn is_normal(&self) -> bool {
579 matches!(self, Self::Normal)
580 }
581
582 #[must_use]
583 pub fn is_fullscreen(&self) -> bool {
584 matches!(self, Self::Fullscreen)
585 }
586
587 #[must_use]
588 pub fn is_maximized(&self) -> bool {
589 matches!(self, Self::Maximized)
590 }
591}
592
593impl<W: LayoutElement> InteractiveMoveState<W> {
594 fn moving(&self) -> Option<&InteractiveMoveData<W>> {
595 match self {
596 InteractiveMoveState::Moving(move_) => Some(move_),
597 _ => None,
598 }
599 }
600
601 fn moving_mut(&mut self) -> Option<&mut InteractiveMoveData<W>> {
602 match self {
603 InteractiveMoveState::Moving(move_) => Some(move_),
604 _ => None,
605 }
606 }
607}
608
609impl<W: LayoutElement> InteractiveMoveData<W> {
610 fn tile_render_location(&self, zoom: f64) -> Point<f64, Logical> {
611 let scale = Scale::from(self.output.current_scale().fractional_scale());
612 let window_size = self.tile.window_size();
613 let pointer_offset_within_window = Point::from((
614 window_size.w * self.pointer_ratio_within_window.0,
615 window_size.h * self.pointer_ratio_within_window.1,
616 ));
617 let pos = self.pointer_pos_within_output
618 - (pointer_offset_within_window + self.tile.window_loc() - self.tile.render_offset())
619 .upscale(zoom);
620 // Round to physical pixels.
621 pos.to_physical_precise_round(scale).to_logical(scale)
622 }
623}
624
625impl ActivateWindow {
626 pub fn map_smart(self, f: impl FnOnce() -> bool) -> bool {
627 match self {
628 ActivateWindow::Yes => true,
629 ActivateWindow::Smart => f(),
630 ActivateWindow::No => false,
631 }
632 }
633}
634
635impl HitType {
636 pub fn offset_win_pos(mut self, offset: Point<f64, Logical>) -> Self {
637 match &mut self {
638 HitType::Input { win_pos } => *win_pos += offset,
639 HitType::Activate { .. } => (),
640 }
641 self
642 }
643
644 pub fn hit_tile<W: LayoutElement>(
645 tile: &Tile<W>,
646 tile_pos: Point<f64, Logical>,
647 point: Point<f64, Logical>,
648 ) -> Option<(&W, Self)> {
649 let pos_within_tile = point - tile_pos;
650 tile.hit(pos_within_tile)
651 .map(|hit| (tile.window(), hit.offset_win_pos(tile_pos)))
652 }
653
654 pub fn to_activate(self) -> Self {
655 match self {
656 HitType::Input { .. } => HitType::Activate {
657 is_tab_indicator: false,
658 },
659 HitType::Activate { .. } => self,
660 }
661 }
662}
663
664impl Options {
665 fn from_config(config: &Config) -> Self {
666 Self {
667 layout: config.layout.clone(),
668 animations: config.animations.clone(),
669 gestures: config.gestures,
670 overview: config.overview,
671 blur: config.blur,
672 disable_resize_throttling: config.debug.disable_resize_throttling,
673 disable_transactions: config.debug.disable_transactions,
674 deactivate_unfocused_windows: config.debug.deactivate_unfocused_windows,
675 }
676 }
677
678 fn with_merged_layout(mut self, part: Option<&niri_config::LayoutPart>) -> Self {
679 if let Some(part) = part {
680 self.layout.merge_with(part);
681 }
682 self
683 }
684
685 fn adjusted_for_scale(mut self, scale: f64) -> Self {
686 self.layout.gaps = round_logical_in_physical_max1(scale, self.layout.gaps);
687 self
688 }
689}
690
691impl OverviewProgress {
692 fn value(&self) -> f64 {
693 match self {
694 OverviewProgress::Animation(anim) => anim.value(),
695 OverviewProgress::Gesture(gesture) => gesture.value,
696 OverviewProgress::Open => 1.,
697 }
698 }
699
700 fn is_animation(&self) -> bool {
701 matches!(self, OverviewProgress::Animation(_))
702 }
703}
704
705impl RenderLayer {
706 /// Returns `true` if the render layer is [`Normal`].
707 ///
708 /// [`Normal`]: RenderLayer::Normal
709 #[must_use]
710 pub fn is_normal(&self) -> bool {
711 matches!(self, Self::Normal)
712 }
713}
714
715impl<W: LayoutElement> Layout<W> {
716 pub fn new(clock: Clock, config: &Config) -> Self {
717 Self::with_options_and_workspaces(clock, config, Options::from_config(config))
718 }
719
720 pub fn with_options(clock: Clock, options: Options) -> Self {
721 Self {
722 monitor_set: MonitorSet::NoOutputs { workspaces: vec![] },
723 is_active: true,
724 last_active_workspace_id: HashMap::new(),
725 interactive_move: None,
726 dnd: None,
727 clock,
728 update_render_elements_time: Duration::ZERO,
729 overview_open: false,
730 overview_progress: None,
731 options: Rc::new(options),
732 }
733 }
734
735 fn with_options_and_workspaces(clock: Clock, config: &Config, options: Options) -> Self {
736 let opts = Rc::new(options);
737
738 let workspaces = config
739 .workspaces
740 .iter()
741 .filter(|ws| !ws.hidden)
742 .map(|ws| {
743 Workspace::new_with_config_no_outputs(Some(ws.clone()), clock.clone(), opts.clone())
744 })
745 .collect();
746
747 Self {
748 monitor_set: MonitorSet::NoOutputs { workspaces },
749 is_active: true,
750 last_active_workspace_id: HashMap::new(),
751 interactive_move: None,
752 dnd: None,
753 clock,
754 update_render_elements_time: Duration::ZERO,
755 overview_open: false,
756 overview_progress: None,
757 options: opts,
758 }
759 }
760
761 pub fn add_output(&mut self, output: Output, layout_config: Option<LayoutPart>) {
762 self.monitor_set = match mem::take(&mut self.monitor_set) {
763 MonitorSet::Normal {
764 mut monitors,
765 primary_idx,
766 active_monitor_idx,
767 } => {
768 let new_output_idx = monitors.len();
769 let mut workspaces = vec![];
770 for source_idx in 0..monitors.len() {
771 let mut stopped_ws_switch = false;
772
773 for i in (0..monitors[source_idx].workspaces.len()).rev() {
774 let preferred = monitors[source_idx].workspaces[i].find_preferred_output(
775 monitors
776 .iter()
777 .map(|monitor| &monitor.output)
778 .chain(std::iter::once(&output)),
779 ) == Some(new_output_idx);
780 if !preferred {
781 continue;
782 }
783
784 let source = &mut monitors[source_idx];
785 let ws = source.workspaces.remove(i);
786
787 // FIXME: this can be coded in a way that the workspace switch won't be
788 // affected if the removed workspace is invisible. But this is good enough
789 // for now.
790 if source.workspace_switch.is_some() {
791 source.workspace_switch = None;
792 stopped_ws_switch = true;
793 }
794
795 // The user could've closed a window while remaining on this workspace, on
796 // another monitor. However, we will add an empty workspace in the end
797 // instead.
798 if ws.has_windows_or_name() {
799 workspaces.push(ws);
800 }
801
802 if i <= source.active_workspace_idx
803 // Generally when moving the currently active workspace, we want to
804 // fall back to the workspace above, so as not to end up on the last
805 // empty workspace. However, with empty workspace above first, when
806 // moving the workspace at index 1 (first non-empty), we want to stay
807 // at index 1, so as once again not to end up on an empty workspace.
808 //
809 // This comes into play at compositor startup when having named
810 // workspaces set up across multiple monitors. Without this check, the
811 // first monitor to connect can end up with the first empty workspace
812 // focused instead of the first named workspace.
813 && !(source.options.layout.empty_workspace_above_first
814 && source.active_workspace_idx == 1)
815 {
816 source.active_workspace_idx =
817 source.active_workspace_idx.saturating_sub(1);
818 }
819 }
820
821 let source = &mut monitors[source_idx];
822
823 // If we stopped a workspace switch, then we might need to clean up workspaces.
824 // Also if empty_workspace_above_first is set and there are only 2 workspaces
825 // left, both will be empty and one of them needs to be removed.
826 // clean_up_workspaces takes care of this.
827 if stopped_ws_switch
828 || (source.options.layout.empty_workspace_above_first
829 && source.workspaces.len() == 2)
830 {
831 source.clean_up_workspaces();
832 }
833 }
834 workspaces.reverse();
835
836 let ws_id_to_activate = self.last_active_workspace_id.remove(&output.name());
837
838 let mut monitor = Monitor::new(
839 output,
840 workspaces,
841 ws_id_to_activate,
842 self.clock.clone(),
843 self.options.clone(),
844 layout_config,
845 );
846 monitor.overview_open = self.overview_open;
847 monitor.set_overview_progress(self.overview_progress.as_ref());
848 monitors.push(monitor);
849
850 MonitorSet::Normal {
851 monitors,
852 primary_idx,
853 active_monitor_idx,
854 }
855 }
856 MonitorSet::NoOutputs { workspaces } => {
857 let ws_id_to_activate = self.last_active_workspace_id.remove(&output.name());
858
859 let mut monitor = Monitor::new(
860 output,
861 workspaces,
862 ws_id_to_activate,
863 self.clock.clone(),
864 self.options.clone(),
865 layout_config,
866 );
867 monitor.overview_open = self.overview_open;
868 monitor.set_overview_progress(self.overview_progress.as_ref());
869
870 MonitorSet::Normal {
871 monitors: vec![monitor],
872 primary_idx: 0,
873 active_monitor_idx: 0,
874 }
875 }
876 }
877 }
878
879 pub fn remove_output(&mut self, output: &Output) {
880 self.monitor_set = match mem::take(&mut self.monitor_set) {
881 MonitorSet::Normal {
882 mut monitors,
883 mut primary_idx,
884 mut active_monitor_idx,
885 } => {
886 let idx = monitors
887 .iter()
888 .position(|mon| &mon.output == output)
889 .expect("trying to remove non-existing output");
890 let monitor = monitors.remove(idx);
891
892 self.last_active_workspace_id.insert(
893 monitor.output_name().clone(),
894 monitor.workspaces[monitor.active_workspace_idx].id(),
895 );
896
897 let mut workspaces = monitor.into_workspaces();
898
899 if monitors.is_empty() {
900 // Removed the last monitor.
901
902 for ws in &mut workspaces {
903 // Reset base options to layout ones.
904 ws.update_config(self.options.clone());
905 }
906
907 MonitorSet::NoOutputs { workspaces }
908 } else {
909 if primary_idx >= idx {
910 // Update primary_idx to either still point at the same monitor, or at some
911 // other monitor if the primary has been removed.
912 primary_idx = primary_idx.saturating_sub(1);
913 }
914 if active_monitor_idx >= idx {
915 // Update active_monitor_idx to either still point at the same monitor, or
916 // at some other monitor if the active monitor has
917 // been removed.
918 active_monitor_idx = active_monitor_idx.saturating_sub(1);
919 }
920
921 for target_idx in 0..monitors.len() {
922 let target_workspaces = workspaces
923 .extract_if(.., |ws| {
924 ws.find_preferred_output(
925 monitors.iter().map(|monitor| &monitor.output),
926 )
927 .unwrap_or(primary_idx)
928 == target_idx
929 })
930 .collect();
931 monitors[target_idx].append_workspaces(target_workspaces);
932 }
933
934 MonitorSet::Normal {
935 monitors,
936 primary_idx,
937 active_monitor_idx,
938 }
939 }
940 }
941 MonitorSet::NoOutputs { .. } => {
942 panic!("tried to remove output when there were already none")
943 }
944 }
945 }
946
947 pub fn add_column_by_idx(
948 &mut self,
949 monitor_idx: usize,
950 workspace_idx: usize,
951 column: Column<W>,
952 activate: bool,
953 ) {
954 let MonitorSet::Normal {
955 monitors,
956 active_monitor_idx,
957 ..
958 } = &mut self.monitor_set
959 else {
960 panic!()
961 };
962
963 monitors[monitor_idx].add_column(workspace_idx, column, activate, None);
964
965 if activate {
966 *active_monitor_idx = monitor_idx;
967 }
968 }
969
970 /// Adds a new window to the layout.
971 ///
972 /// Returns an output that the window was added to, if there were any outputs.
973 #[allow(clippy::too_many_arguments)]
974 pub fn add_window(
975 &mut self,
976 window: W,
977 target: AddWindowTarget<W>,
978 width: Option<PresetSize>,
979 height: Option<PresetSize>,
980 is_full_width: bool,
981 is_floating: bool,
982 activate: ActivateWindow,
983 ) -> Option<&Output> {
984 let scrolling_height = height.map(SizeChange::from);
985 let id = window.id().clone();
986
987 match &mut self.monitor_set {
988 MonitorSet::Normal {
989 monitors,
990 active_monitor_idx,
991 ..
992 } => {
993 let (mon_idx, target) = match target {
994 AddWindowTarget::Auto => (*active_monitor_idx, MonitorAddWindowTarget::Auto),
995 AddWindowTarget::Output(output) => {
996 let mon_idx = monitors
997 .iter()
998 .position(|mon| mon.output == *output)
999 .unwrap();
1000
1001 (mon_idx, MonitorAddWindowTarget::Auto)
1002 }
1003 AddWindowTarget::Workspace(ws_id) => {
1004 let mon_idx = monitors.iter().position(|mon| mon.has_ws(ws_id)).unwrap();
1005
1006 (
1007 mon_idx,
1008 MonitorAddWindowTarget::Workspace {
1009 id: ws_id,
1010 column_idx: None,
1011 },
1012 )
1013 }
1014 AddWindowTarget::NextTo(next_to) => {
1015 if let Some(output) = self
1016 .interactive_move
1017 .as_ref()
1018 .and_then(|move_| {
1019 if let InteractiveMoveState::Moving(move_) = move_ {
1020 Some(move_)
1021 } else {
1022 None
1023 }
1024 })
1025 .filter(|move_| next_to == move_.tile.window().id())
1026 .map(|move_| move_.output.clone())
1027 {
1028 // The next_to window is being interactively moved.
1029 let mon_idx = monitors
1030 .iter()
1031 .position(|mon| mon.output == output)
1032 .unwrap_or(*active_monitor_idx);
1033
1034 (mon_idx, MonitorAddWindowTarget::Auto)
1035 } else {
1036 let mon_idx = monitors
1037 .iter()
1038 .position(|mon| {
1039 mon.workspaces.iter().any(|ws| ws.has_window(next_to))
1040 })
1041 .unwrap();
1042 (mon_idx, MonitorAddWindowTarget::NextTo(next_to))
1043 }
1044 }
1045 };
1046 let mon = &mut monitors[mon_idx];
1047
1048 let (ws_idx, _) = mon.resolve_add_window_target(target);
1049 let ws = &mon.workspaces[ws_idx];
1050 let scrolling_width = ws.resolve_scrolling_width(&window, width);
1051
1052 mon.add_window(
1053 window,
1054 target,
1055 activate,
1056 scrolling_width,
1057 is_full_width,
1058 is_floating,
1059 );
1060
1061 if activate.map_smart(|| false) {
1062 *active_monitor_idx = mon_idx;
1063 }
1064
1065 // Set the default height for scrolling windows.
1066 if !is_floating {
1067 if let Some(change) = scrolling_height {
1068 let ws = mon
1069 .workspaces
1070 .iter_mut()
1071 .find(|ws| ws.has_window(&id))
1072 .unwrap();
1073 ws.set_window_height(Some(&id), change);
1074 }
1075 }
1076
1077 Some(&mon.output)
1078 }
1079 MonitorSet::NoOutputs { workspaces } => {
1080 let (ws_idx, target) = match target {
1081 AddWindowTarget::Auto => {
1082 if workspaces.is_empty() {
1083 workspaces.push(Workspace::new_no_outputs(
1084 self.clock.clone(),
1085 self.options.clone(),
1086 ));
1087 }
1088
1089 (0, WorkspaceAddWindowTarget::Auto)
1090 }
1091 AddWindowTarget::Output(_) => panic!(),
1092 AddWindowTarget::Workspace(ws_id) => {
1093 let ws_idx = workspaces.iter().position(|ws| ws.id() == ws_id).unwrap();
1094 (ws_idx, WorkspaceAddWindowTarget::Auto)
1095 }
1096 AddWindowTarget::NextTo(next_to) => {
1097 if self
1098 .interactive_move
1099 .as_ref()
1100 .and_then(|move_| {
1101 if let InteractiveMoveState::Moving(move_) = move_ {
1102 Some(move_)
1103 } else {
1104 None
1105 }
1106 })
1107 .filter(|move_| next_to == move_.tile.window().id())
1108 .is_some()
1109 {
1110 // The next_to window is being interactively moved. If there are no
1111 // other windows, we may have no workspaces at all.
1112 if workspaces.is_empty() {
1113 workspaces.push(Workspace::new_no_outputs(
1114 self.clock.clone(),
1115 self.options.clone(),
1116 ));
1117 }
1118
1119 (0, WorkspaceAddWindowTarget::Auto)
1120 } else {
1121 let ws_idx = workspaces
1122 .iter()
1123 .position(|ws| ws.has_window(next_to))
1124 .unwrap();
1125 (ws_idx, WorkspaceAddWindowTarget::NextTo(next_to))
1126 }
1127 }
1128 };
1129 let ws = &mut workspaces[ws_idx];
1130
1131 let scrolling_width = ws.resolve_scrolling_width(&window, width);
1132
1133 let tile = ws.make_tile(window);
1134 ws.add_tile(
1135 tile,
1136 target,
1137 activate,
1138 scrolling_width,
1139 is_full_width,
1140 is_floating,
1141 None,
1142 );
1143
1144 // Set the default height for scrolling windows.
1145 if !is_floating {
1146 if let Some(change) = scrolling_height {
1147 ws.set_window_height(Some(&id), change);
1148 }
1149 }
1150
1151 None
1152 }
1153 }
1154 }
1155
1156 pub fn remove_window(
1157 &mut self,
1158 window: &W::Id,
1159 transaction: Transaction,
1160 ) -> Option<RemovedTile<W>> {
1161 if let Some(state) = &self.interactive_move {
1162 match state {
1163 InteractiveMoveState::Starting { window_id, .. } => {
1164 if window_id == window {
1165 self.interactive_move_end(window);
1166 }
1167 }
1168 InteractiveMoveState::Moving(move_) => {
1169 if move_.tile.window().id() == window {
1170 let Some(InteractiveMoveState::Moving(move_)) =
1171 self.interactive_move.take()
1172 else {
1173 unreachable!()
1174 };
1175
1176 for mon in self.monitors_mut() {
1177 mon.dnd_scroll_gesture_end();
1178 }
1179
1180 // Unlock the view on the workspaces.
1181 for ws in self.workspaces_mut() {
1182 ws.dnd_scroll_gesture_end();
1183 }
1184
1185 return Some(RemovedTile {
1186 tile: move_.tile,
1187 width: move_.width,
1188 is_full_width: move_.is_full_width,
1189 is_floating: false,
1190 });
1191 }
1192 }
1193 }
1194 }
1195
1196 match &mut self.monitor_set {
1197 MonitorSet::Normal { monitors, .. } => {
1198 for mon in monitors {
1199 for (idx, ws) in mon.workspaces.iter_mut().enumerate() {
1200 if ws.has_window(window) {
1201 let removed = ws.remove_tile(window, transaction);
1202
1203 // Clean up empty workspaces that are not active and not last.
1204 if !ws.has_windows_or_name()
1205 && idx != mon.active_workspace_idx
1206 && idx != mon.workspaces.len() - 1
1207 && mon.workspace_switch.is_none()
1208 {
1209 mon.workspaces.remove(idx);
1210
1211 if idx < mon.active_workspace_idx {
1212 mon.active_workspace_idx -= 1;
1213 }
1214 }
1215
1216 // Special case handling when empty_workspace_above_first is set and all
1217 // workspaces are empty.
1218 if mon.options.layout.empty_workspace_above_first
1219 && mon.workspaces.len() == 2
1220 && mon.workspace_switch.is_none()
1221 {
1222 assert!(!mon.workspaces[0].has_windows_or_name());
1223 assert!(!mon.workspaces[1].has_windows_or_name());
1224 mon.workspaces.remove(1);
1225 mon.active_workspace_idx = 0;
1226 }
1227 return Some(removed);
1228 }
1229 }
1230 }
1231 }
1232 MonitorSet::NoOutputs { workspaces, .. } => {
1233 for (idx, ws) in workspaces.iter_mut().enumerate() {
1234 if ws.has_window(window) {
1235 let removed = ws.remove_tile(window, transaction);
1236
1237 // Clean up empty workspaces.
1238 if !ws.has_windows_or_name() {
1239 workspaces.remove(idx);
1240 }
1241
1242 return Some(removed);
1243 }
1244 }
1245 }
1246 }
1247
1248 None
1249 }
1250
1251 pub fn descendants_added(&mut self, id: &W::Id) -> bool {
1252 for ws in self.workspaces_mut() {
1253 if ws.descendants_added(id) {
1254 return true;
1255 }
1256 }
1257
1258 false
1259 }
1260
1261 pub fn update_window(&mut self, window: &W::Id, serial: Option<Serial>) {
1262 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
1263 if move_.tile.window().id() == window {
1264 // Do this before calling update_window() so it can get up-to-date info.
1265 if let Some(serial) = serial {
1266 move_.tile.window_mut().on_commit(serial);
1267 }
1268
1269 move_.tile.update_window();
1270 return;
1271 }
1272 }
1273
1274 match &mut self.monitor_set {
1275 MonitorSet::Normal { monitors, .. } => {
1276 for mon in monitors {
1277 for ws in &mut mon.workspaces {
1278 if ws.has_window(window) {
1279 ws.update_window(window, serial);
1280 return;
1281 }
1282 }
1283 }
1284 }
1285 MonitorSet::NoOutputs { workspaces, .. } => {
1286 for ws in workspaces {
1287 if ws.has_window(window) {
1288 ws.update_window(window, serial);
1289 return;
1290 }
1291 }
1292 }
1293 }
1294 }
1295
1296 pub fn find_workspace_by_id(&self, id: WorkspaceId) -> Option<(usize, &Workspace<W>)> {
1297 match &self.monitor_set {
1298 MonitorSet::Normal { ref monitors, .. } => {
1299 for mon in monitors {
1300 if let Some(index) = mon.idx_of_ws(id) {
1301 let workspace = &mon.workspaces[index];
1302 return Some((index, workspace));
1303 }
1304 }
1305 }
1306 MonitorSet::NoOutputs { workspaces } => {
1307 if let Some((index, workspace)) =
1308 workspaces.iter().enumerate().find(|(_, w)| w.id() == id)
1309 {
1310 return Some((index, workspace));
1311 }
1312 }
1313 }
1314
1315 None
1316 }
1317
1318 pub fn find_workspace_by_name(&self, workspace_name: &str) -> Option<(usize, &Workspace<W>)> {
1319 match &self.monitor_set {
1320 MonitorSet::Normal { ref monitors, .. } => {
1321 for mon in monitors {
1322 if let Some((index, workspace)) =
1323 mon.workspaces.iter().enumerate().find(|(_, w)| {
1324 w.name
1325 .as_ref()
1326 .is_some_and(|name| name.eq_ignore_ascii_case(workspace_name))
1327 })
1328 {
1329 return Some((index, workspace));
1330 }
1331 }
1332 }
1333 MonitorSet::NoOutputs { workspaces } => {
1334 if let Some((index, workspace)) = workspaces.iter().enumerate().find(|(_, w)| {
1335 w.name
1336 .as_ref()
1337 .is_some_and(|name| name.eq_ignore_ascii_case(workspace_name))
1338 }) {
1339 return Some((index, workspace));
1340 }
1341 }
1342 }
1343
1344 None
1345 }
1346
1347 pub fn find_workspace_by_ref(
1348 &mut self,
1349 reference: WorkspaceReference,
1350 ) -> Option<&mut Workspace<W>> {
1351 if let WorkspaceReference::Index(index) = reference {
1352 self.active_monitor().and_then(|m| {
1353 let index = index.saturating_sub(1) as usize;
1354 m.workspaces.get_mut(index)
1355 })
1356 } else {
1357 self.workspaces_mut().find(|ws| match &reference {
1358 WorkspaceReference::Name(ref_name) => ws
1359 .name
1360 .as_ref()
1361 .is_some_and(|name| name.eq_ignore_ascii_case(ref_name)),
1362 WorkspaceReference::Id(id) => ws.id().get() == *id,
1363 WorkspaceReference::Index(_) => unreachable!(),
1364 })
1365 }
1366 }
1367
1368 pub fn unname_workspace(&mut self, workspace_name: &str) {
1369 self.unname_workspace_by_ref(WorkspaceReference::Name(workspace_name.into()));
1370 }
1371
1372 pub fn unname_workspace_by_ref(&mut self, reference: WorkspaceReference) {
1373 let id = self.find_workspace_by_ref(reference).map(|ws| ws.id());
1374 if let Some(id) = id {
1375 self.unname_workspace_by_id(id);
1376 }
1377 }
1378
1379 pub fn unname_workspace_by_id(&mut self, id: WorkspaceId) {
1380 match &mut self.monitor_set {
1381 MonitorSet::Normal { monitors, .. } => {
1382 for mon in monitors {
1383 if mon.unname_workspace(id) {
1384 return;
1385 }
1386 }
1387 }
1388 MonitorSet::NoOutputs { workspaces } => {
1389 for (idx, ws) in workspaces.iter_mut().enumerate() {
1390 if ws.id() == id {
1391 ws.unname();
1392
1393 // Clean up empty workspaces.
1394 if !ws.has_windows() {
1395 workspaces.remove(idx);
1396 }
1397
1398 return;
1399 }
1400 }
1401 }
1402 }
1403 }
1404
1405 pub fn find_window_and_output(&self, wl_surface: &WlSurface) -> Option<(&W, Option<&Output>)> {
1406 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
1407 if move_.tile.window().is_wl_surface(wl_surface) {
1408 return Some((move_.tile.window(), Some(&move_.output)));
1409 }
1410 }
1411
1412 match &self.monitor_set {
1413 MonitorSet::Normal { monitors, .. } => {
1414 for mon in monitors {
1415 for ws in &mon.workspaces {
1416 if let Some(window) = ws.find_wl_surface(wl_surface) {
1417 return Some((window, Some(&mon.output)));
1418 }
1419 }
1420 }
1421 }
1422 MonitorSet::NoOutputs { workspaces } => {
1423 for ws in workspaces {
1424 if let Some(window) = ws.find_wl_surface(wl_surface) {
1425 return Some((window, None));
1426 }
1427 }
1428 }
1429 }
1430
1431 None
1432 }
1433
1434 pub fn find_window_and_output_mut(
1435 &mut self,
1436 wl_surface: &WlSurface,
1437 ) -> Option<(&mut W, Option<&Output>)> {
1438 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
1439 if move_.tile.window().is_wl_surface(wl_surface) {
1440 return Some((move_.tile.window_mut(), Some(&move_.output)));
1441 }
1442 }
1443
1444 match &mut self.monitor_set {
1445 MonitorSet::Normal { monitors, .. } => {
1446 for mon in monitors {
1447 for ws in &mut mon.workspaces {
1448 if let Some(window) = ws.find_wl_surface_mut(wl_surface) {
1449 return Some((window, Some(&mon.output)));
1450 }
1451 }
1452 }
1453 }
1454 MonitorSet::NoOutputs { workspaces } => {
1455 for ws in workspaces {
1456 if let Some(window) = ws.find_wl_surface_mut(wl_surface) {
1457 return Some((window, None));
1458 }
1459 }
1460 }
1461 }
1462
1463 None
1464 }
1465
1466 /// Computes the window-geometry-relative target rect for popup unconstraining.
1467 ///
1468 /// We will try to fit popups inside this rect.
1469 ///
1470 /// If `overflow` is true, prefer to return the working area region even for the scrolling
1471 /// layout where popups are normally kept constrained to the column width. This is used for
1472 /// IME popups where this is a more expected behavior.
1473 pub fn popup_target_rect(&self, window: &W::Id, overflow: bool) -> Rectangle<f64, Logical> {
1474 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
1475 if move_.tile.window().id() == window {
1476 // Follow the scrolling layout logic.
1477 let output_size = output_size(&move_.output);
1478 let tile_pos = move_.tile_render_location(1.);
1479
1480 let target = if overflow {
1481 let mut target = Rectangle::from_size(output_size);
1482 target.loc -= tile_pos;
1483 target.loc -= move_.tile.window_loc();
1484 target
1485 } else {
1486 let width = move_.tile.window_size().w;
1487 let height = output_size.h;
1488 let mut target = Rectangle::from_size(Size::from((width, height)));
1489 // FIXME: ideally this shouldn't include the tile render offset, but the code
1490 // duplication would be a bit annoying for this edge case.
1491 target.loc.y -= tile_pos.y;
1492 target.loc.y -= move_.tile.window_loc().y;
1493 target
1494 };
1495
1496 return target;
1497 }
1498 }
1499
1500 self.workspaces()
1501 .find_map(|(_, _, ws)| ws.popup_target_rect(window, overflow))
1502 .unwrap()
1503 }
1504
1505 pub fn update_output_size(&mut self, output: &Output) {
1506 let _span = tracy_client::span!("Layout::update_output_size");
1507
1508 let Some(mon) = self.monitor_for_output_mut(output) else {
1509 error!("monitor missing in update_output_size()");
1510 return;
1511 };
1512
1513 mon.update_output_size();
1514 }
1515
1516 pub fn scroll_amount_to_activate(&self, window: &W::Id) -> f64 {
1517 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
1518 if move_.tile.window().id() == window {
1519 return 0.;
1520 }
1521 }
1522
1523 for mon in self.monitors() {
1524 for ws in &mon.workspaces {
1525 if ws.has_window(window) {
1526 return ws.scroll_amount_to_activate(window);
1527 }
1528 }
1529 }
1530
1531 0.
1532 }
1533
1534 pub fn should_trigger_focus_follows_mouse_on(&self, window: &W::Id) -> bool {
1535 // During an animation, it's easy to trigger focus-follows-mouse on the previous workspace,
1536 // especially when clicking to switch workspace on a bar of some kind. This cancels the
1537 // workspace switch, which is annoying and not intended.
1538 //
1539 // This function allows focus-follows-mouse to trigger only on the animation target
1540 // workspace.
1541 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
1542 if move_.tile.window().id() == window {
1543 return true;
1544 }
1545 }
1546
1547 let MonitorSet::Normal { monitors, .. } = &self.monitor_set else {
1548 return true;
1549 };
1550
1551 let (mon, ws_idx) = monitors
1552 .iter()
1553 .find_map(|mon| {
1554 mon.workspaces
1555 .iter()
1556 .position(|ws| ws.has_window(window))
1557 .map(|ws_idx| (mon, ws_idx))
1558 })
1559 .unwrap();
1560
1561 // During a gesture, focus-follows-mouse does not cause any unintended workspace switches.
1562 if let Some(WorkspaceSwitch::Gesture(_)) = mon.workspace_switch {
1563 return true;
1564 }
1565
1566 ws_idx == mon.active_workspace_idx
1567 }
1568
1569 pub fn activate_window(&mut self, window: &W::Id) {
1570 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
1571 if move_.tile.window().id() == window {
1572 return;
1573 }
1574 }
1575
1576 let MonitorSet::Normal {
1577 monitors,
1578 active_monitor_idx,
1579 ..
1580 } = &mut self.monitor_set
1581 else {
1582 return;
1583 };
1584
1585 for (monitor_idx, mon) in monitors.iter_mut().enumerate() {
1586 for (workspace_idx, ws) in mon.workspaces.iter_mut().enumerate() {
1587 if ws.activate_window(window) {
1588 *active_monitor_idx = monitor_idx;
1589
1590 // If currently in the middle of a vertical swipe between the target workspace
1591 // and some other, don't switch the workspace.
1592 match &mon.workspace_switch {
1593 Some(WorkspaceSwitch::Gesture(gesture))
1594 if gesture.current_idx.floor() == workspace_idx as f64
1595 || gesture.current_idx.ceil() == workspace_idx as f64 => {}
1596 _ => mon.switch_workspace(workspace_idx),
1597 }
1598
1599 return;
1600 }
1601 }
1602 }
1603 }
1604
1605 pub fn activate_window_without_raising(&mut self, window: &W::Id) {
1606 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
1607 if move_.tile.window().id() == window {
1608 return;
1609 }
1610 }
1611
1612 let MonitorSet::Normal {
1613 monitors,
1614 active_monitor_idx,
1615 ..
1616 } = &mut self.monitor_set
1617 else {
1618 return;
1619 };
1620
1621 for (monitor_idx, mon) in monitors.iter_mut().enumerate() {
1622 for (workspace_idx, ws) in mon.workspaces.iter_mut().enumerate() {
1623 if ws.activate_window_without_raising(window) {
1624 *active_monitor_idx = monitor_idx;
1625
1626 // If currently in the middle of a vertical swipe between the target workspace
1627 // and some other, don't switch the workspace.
1628 match &mon.workspace_switch {
1629 Some(WorkspaceSwitch::Gesture(gesture))
1630 if gesture.current_idx.floor() == workspace_idx as f64
1631 || gesture.current_idx.ceil() == workspace_idx as f64 => {}
1632 _ => mon.switch_workspace(workspace_idx),
1633 }
1634
1635 return;
1636 }
1637 }
1638 }
1639 }
1640
1641 pub fn active_output(&self) -> Option<&Output> {
1642 let MonitorSet::Normal {
1643 monitors,
1644 active_monitor_idx,
1645 ..
1646 } = &self.monitor_set
1647 else {
1648 return None;
1649 };
1650
1651 Some(&monitors[*active_monitor_idx].output)
1652 }
1653
1654 pub fn active_workspace(&self) -> Option<&Workspace<W>> {
1655 let MonitorSet::Normal {
1656 monitors,
1657 active_monitor_idx,
1658 ..
1659 } = &self.monitor_set
1660 else {
1661 return None;
1662 };
1663
1664 let mon = &monitors[*active_monitor_idx];
1665 Some(&mon.workspaces[mon.active_workspace_idx])
1666 }
1667
1668 pub fn active_workspace_mut(&mut self) -> Option<&mut Workspace<W>> {
1669 let MonitorSet::Normal {
1670 monitors,
1671 active_monitor_idx,
1672 ..
1673 } = &mut self.monitor_set
1674 else {
1675 return None;
1676 };
1677
1678 let mon = &mut monitors[*active_monitor_idx];
1679 Some(&mut mon.workspaces[mon.active_workspace_idx])
1680 }
1681
1682 pub fn windows_for_output(&self, output: &Output) -> impl Iterator<Item = &W> + '_ {
1683 let MonitorSet::Normal { monitors, .. } = &self.monitor_set else {
1684 panic!()
1685 };
1686
1687 let moving_window = self
1688 .interactive_move
1689 .as_ref()
1690 .and_then(|x| x.moving())
1691 .filter(|move_| move_.output == *output)
1692 .map(|move_| move_.tile.window())
1693 .into_iter();
1694
1695 let mon = monitors.iter().find(|mon| &mon.output == output).unwrap();
1696 let mon_windows = mon.workspaces.iter().flat_map(|ws| ws.windows());
1697
1698 moving_window.chain(mon_windows)
1699 }
1700
1701 pub fn windows_for_output_mut(&mut self, output: &Output) -> impl Iterator<Item = &mut W> + '_ {
1702 let MonitorSet::Normal { monitors, .. } = &mut self.monitor_set else {
1703 panic!()
1704 };
1705
1706 let moving_window = self
1707 .interactive_move
1708 .as_mut()
1709 .and_then(|x| x.moving_mut())
1710 .filter(|move_| move_.output == *output)
1711 .map(|move_| move_.tile.window_mut())
1712 .into_iter();
1713
1714 let mon = monitors
1715 .iter_mut()
1716 .find(|mon| &mon.output == output)
1717 .unwrap();
1718 let mon_windows = mon.workspaces.iter_mut().flat_map(|ws| ws.windows_mut());
1719
1720 moving_window.chain(mon_windows)
1721 }
1722
1723 pub fn with_windows(
1724 &self,
1725 mut f: impl FnMut(&W, Option<&Output>, Option<WorkspaceId>, WindowLayout),
1726 ) {
1727 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
1728 // We don't fill any positions for interactively moved windows.
1729 let layout = move_.tile.ipc_layout_template();
1730 f(move_.tile.window(), Some(&move_.output), None, layout);
1731 }
1732
1733 match &self.monitor_set {
1734 MonitorSet::Normal { monitors, .. } => {
1735 for mon in monitors {
1736 for ws in &mon.workspaces {
1737 for (tile, layout) in ws.tiles_with_ipc_layouts() {
1738 f(tile.window(), Some(&mon.output), Some(ws.id()), layout);
1739 }
1740 }
1741 }
1742 }
1743 MonitorSet::NoOutputs { workspaces } => {
1744 for ws in workspaces {
1745 for (tile, layout) in ws.tiles_with_ipc_layouts() {
1746 f(tile.window(), None, Some(ws.id()), layout);
1747 }
1748 }
1749 }
1750 }
1751 }
1752
1753 pub fn with_windows_mut(&mut self, mut f: impl FnMut(&mut W, Option<&Output>)) {
1754 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
1755 f(move_.tile.window_mut(), Some(&move_.output));
1756 }
1757
1758 match &mut self.monitor_set {
1759 MonitorSet::Normal { monitors, .. } => {
1760 for mon in monitors {
1761 for ws in &mut mon.workspaces {
1762 for win in ws.windows_mut() {
1763 f(win, Some(&mon.output));
1764 }
1765 }
1766 }
1767 }
1768 MonitorSet::NoOutputs { workspaces } => {
1769 for ws in workspaces {
1770 for win in ws.windows_mut() {
1771 f(win, None);
1772 }
1773 }
1774 }
1775 }
1776 }
1777
1778 fn active_monitor(&mut self) -> Option<&mut Monitor<W>> {
1779 let MonitorSet::Normal {
1780 monitors,
1781 active_monitor_idx,
1782 ..
1783 } = &mut self.monitor_set
1784 else {
1785 return None;
1786 };
1787
1788 Some(&mut monitors[*active_monitor_idx])
1789 }
1790
1791 pub fn active_monitor_ref(&self) -> Option<&Monitor<W>> {
1792 let MonitorSet::Normal {
1793 monitors,
1794 active_monitor_idx,
1795 ..
1796 } = &self.monitor_set
1797 else {
1798 return None;
1799 };
1800
1801 Some(&monitors[*active_monitor_idx])
1802 }
1803
1804 pub fn monitors(&self) -> impl Iterator<Item = &Monitor<W>> + '_ {
1805 let monitors = if let MonitorSet::Normal { monitors, .. } = &self.monitor_set {
1806 &monitors[..]
1807 } else {
1808 &[][..]
1809 };
1810
1811 monitors.iter()
1812 }
1813
1814 pub fn monitors_mut(&mut self) -> impl Iterator<Item = &mut Monitor<W>> + '_ {
1815 let monitors = if let MonitorSet::Normal { monitors, .. } = &mut self.monitor_set {
1816 &mut monitors[..]
1817 } else {
1818 &mut [][..]
1819 };
1820
1821 monitors.iter_mut()
1822 }
1823
1824 pub fn monitor_for_output(&self, output: &Output) -> Option<&Monitor<W>> {
1825 self.monitors().find(|mon| &mon.output == output)
1826 }
1827
1828 pub fn monitor_for_output_mut(&mut self, output: &Output) -> Option<&mut Monitor<W>> {
1829 self.monitors_mut().find(|mon| &mon.output == output)
1830 }
1831
1832 pub fn monitor_for_workspace(&self, workspace_name: &str) -> Option<&Monitor<W>> {
1833 self.monitors().find(|monitor| {
1834 monitor.workspaces.iter().any(|ws| {
1835 ws.name
1836 .as_ref()
1837 .is_some_and(|name| name.eq_ignore_ascii_case(workspace_name))
1838 })
1839 })
1840 }
1841
1842 pub fn outputs(&self) -> impl Iterator<Item = &Output> + '_ {
1843 self.monitors().map(|mon| &mon.output)
1844 }
1845
1846 pub fn move_left(&mut self) {
1847 let Some(workspace) = self.active_workspace_mut() else {
1848 return;
1849 };
1850 workspace.move_left();
1851 }
1852
1853 pub fn move_right(&mut self) {
1854 let Some(workspace) = self.active_workspace_mut() else {
1855 return;
1856 };
1857 workspace.move_right();
1858 }
1859
1860 pub fn move_column_to_first(&mut self) {
1861 let Some(workspace) = self.active_workspace_mut() else {
1862 return;
1863 };
1864 workspace.move_column_to_first();
1865 }
1866
1867 pub fn move_column_to_last(&mut self) {
1868 let Some(workspace) = self.active_workspace_mut() else {
1869 return;
1870 };
1871 workspace.move_column_to_last();
1872 }
1873
1874 pub fn move_column_left_or_to_output(&mut self, output: &Output) -> bool {
1875 if let Some(workspace) = self.active_workspace_mut() {
1876 if workspace.move_left() {
1877 return false;
1878 }
1879 }
1880
1881 self.move_column_to_output(output, None, true);
1882 true
1883 }
1884
1885 pub fn move_column_right_or_to_output(&mut self, output: &Output) -> bool {
1886 if let Some(workspace) = self.active_workspace_mut() {
1887 if workspace.move_right() {
1888 return false;
1889 }
1890 }
1891
1892 self.move_column_to_output(output, None, true);
1893 true
1894 }
1895
1896 pub fn move_column_to_index(&mut self, index: usize) {
1897 let Some(workspace) = self.active_workspace_mut() else {
1898 return;
1899 };
1900 workspace.move_column_to_index(index);
1901 }
1902
1903 pub fn move_down(&mut self) {
1904 let Some(workspace) = self.active_workspace_mut() else {
1905 return;
1906 };
1907 workspace.move_down();
1908 }
1909
1910 pub fn move_up(&mut self) {
1911 let Some(workspace) = self.active_workspace_mut() else {
1912 return;
1913 };
1914 workspace.move_up();
1915 }
1916
1917 pub fn move_down_or_to_workspace_down(&mut self) {
1918 let Some(monitor) = self.active_monitor() else {
1919 return;
1920 };
1921 monitor.move_down_or_to_workspace_down();
1922 }
1923
1924 pub fn move_up_or_to_workspace_up(&mut self) {
1925 let Some(monitor) = self.active_monitor() else {
1926 return;
1927 };
1928 monitor.move_up_or_to_workspace_up();
1929 }
1930
1931 pub fn consume_or_expel_window_left(&mut self, window: Option<&W::Id>) {
1932 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
1933 if window.is_none() || window == Some(move_.tile.window().id()) {
1934 return;
1935 }
1936 }
1937
1938 let workspace = if let Some(window) = window {
1939 Some(
1940 self.workspaces_mut()
1941 .find(|ws| ws.has_window(window))
1942 .unwrap(),
1943 )
1944 } else {
1945 self.active_workspace_mut()
1946 };
1947
1948 let Some(workspace) = workspace else {
1949 return;
1950 };
1951 workspace.consume_or_expel_window_left(window);
1952 }
1953
1954 pub fn consume_or_expel_window_right(&mut self, window: Option<&W::Id>) {
1955 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
1956 if window.is_none() || window == Some(move_.tile.window().id()) {
1957 return;
1958 }
1959 }
1960
1961 let workspace = if let Some(window) = window {
1962 Some(
1963 self.workspaces_mut()
1964 .find(|ws| ws.has_window(window))
1965 .unwrap(),
1966 )
1967 } else {
1968 self.active_workspace_mut()
1969 };
1970
1971 let Some(workspace) = workspace else {
1972 return;
1973 };
1974 workspace.consume_or_expel_window_right(window);
1975 }
1976
1977 pub fn focus_left(&mut self) {
1978 let Some(workspace) = self.active_workspace_mut() else {
1979 return;
1980 };
1981 workspace.focus_left();
1982 }
1983
1984 pub fn focus_right(&mut self) {
1985 let Some(workspace) = self.active_workspace_mut() else {
1986 return;
1987 };
1988 workspace.focus_right();
1989 }
1990
1991 pub fn focus_column_first(&mut self) {
1992 let Some(workspace) = self.active_workspace_mut() else {
1993 return;
1994 };
1995 workspace.focus_column_first();
1996 }
1997
1998 pub fn focus_column_last(&mut self) {
1999 let Some(workspace) = self.active_workspace_mut() else {
2000 return;
2001 };
2002 workspace.focus_column_last();
2003 }
2004
2005 pub fn focus_column_right_or_first(&mut self) {
2006 let Some(workspace) = self.active_workspace_mut() else {
2007 return;
2008 };
2009 workspace.focus_column_right_or_first();
2010 }
2011
2012 pub fn focus_column_left_or_last(&mut self) {
2013 let Some(workspace) = self.active_workspace_mut() else {
2014 return;
2015 };
2016 workspace.focus_column_left_or_last();
2017 }
2018
2019 pub fn focus_column(&mut self, index: usize) {
2020 let Some(workspace) = self.active_workspace_mut() else {
2021 return;
2022 };
2023 workspace.focus_column(index);
2024 }
2025
2026 pub fn focus_window_up_or_output(&mut self, output: &Output) -> bool {
2027 if let Some(workspace) = self.active_workspace_mut() {
2028 if workspace.focus_up() {
2029 return false;
2030 }
2031 }
2032
2033 self.focus_output(output);
2034 true
2035 }
2036
2037 pub fn focus_window_down_or_output(&mut self, output: &Output) -> bool {
2038 if let Some(workspace) = self.active_workspace_mut() {
2039 if workspace.focus_down() {
2040 return false;
2041 }
2042 }
2043
2044 self.focus_output(output);
2045 true
2046 }
2047
2048 pub fn focus_column_left_or_output(&mut self, output: &Output) -> bool {
2049 if let Some(workspace) = self.active_workspace_mut() {
2050 if workspace.focus_left() {
2051 return false;
2052 }
2053 }
2054
2055 self.focus_output(output);
2056 true
2057 }
2058
2059 pub fn focus_column_right_or_output(&mut self, output: &Output) -> bool {
2060 if let Some(workspace) = self.active_workspace_mut() {
2061 if workspace.focus_right() {
2062 return false;
2063 }
2064 }
2065
2066 self.focus_output(output);
2067 true
2068 }
2069
2070 pub fn focus_window_in_column(&mut self, index: u8) {
2071 let Some(workspace) = self.active_workspace_mut() else {
2072 return;
2073 };
2074 workspace.focus_window_in_column(index);
2075 }
2076
2077 pub fn focus_down(&mut self) {
2078 let Some(workspace) = self.active_workspace_mut() else {
2079 return;
2080 };
2081 workspace.focus_down();
2082 }
2083
2084 pub fn focus_up(&mut self) {
2085 let Some(workspace) = self.active_workspace_mut() else {
2086 return;
2087 };
2088 workspace.focus_up();
2089 }
2090
2091 pub fn focus_down_or_left(&mut self) {
2092 let Some(workspace) = self.active_workspace_mut() else {
2093 return;
2094 };
2095 workspace.focus_down_or_left();
2096 }
2097
2098 pub fn focus_down_or_right(&mut self) {
2099 let Some(workspace) = self.active_workspace_mut() else {
2100 return;
2101 };
2102 workspace.focus_down_or_right();
2103 }
2104
2105 pub fn focus_up_or_left(&mut self) {
2106 let Some(workspace) = self.active_workspace_mut() else {
2107 return;
2108 };
2109 workspace.focus_up_or_left();
2110 }
2111
2112 pub fn focus_up_or_right(&mut self) {
2113 let Some(workspace) = self.active_workspace_mut() else {
2114 return;
2115 };
2116 workspace.focus_up_or_right();
2117 }
2118
2119 pub fn focus_window_or_workspace_down(&mut self) {
2120 let Some(monitor) = self.active_monitor() else {
2121 return;
2122 };
2123 monitor.focus_window_or_workspace_down();
2124 }
2125
2126 pub fn focus_window_or_workspace_up(&mut self) {
2127 let Some(monitor) = self.active_monitor() else {
2128 return;
2129 };
2130 monitor.focus_window_or_workspace_up();
2131 }
2132
2133 pub fn focus_window_top(&mut self) {
2134 let Some(workspace) = self.active_workspace_mut() else {
2135 return;
2136 };
2137 workspace.focus_window_top();
2138 }
2139
2140 pub fn focus_window_bottom(&mut self) {
2141 let Some(workspace) = self.active_workspace_mut() else {
2142 return;
2143 };
2144 workspace.focus_window_bottom();
2145 }
2146
2147 pub fn focus_window_down_or_top(&mut self) {
2148 let Some(workspace) = self.active_workspace_mut() else {
2149 return;
2150 };
2151 workspace.focus_window_down_or_top();
2152 }
2153
2154 pub fn focus_window_up_or_bottom(&mut self) {
2155 let Some(workspace) = self.active_workspace_mut() else {
2156 return;
2157 };
2158 workspace.focus_window_up_or_bottom();
2159 }
2160
2161 pub fn move_to_workspace_up(&mut self, focus: bool) {
2162 let Some(monitor) = self.active_monitor() else {
2163 return;
2164 };
2165 let activate = if focus {
2166 ActivateWindow::Smart
2167 } else {
2168 ActivateWindow::No
2169 };
2170 monitor.move_to_workspace_up(activate);
2171 }
2172
2173 pub fn move_to_workspace_down(&mut self, focus: bool) {
2174 let Some(monitor) = self.active_monitor() else {
2175 return;
2176 };
2177 let activate = if focus {
2178 ActivateWindow::Smart
2179 } else {
2180 ActivateWindow::No
2181 };
2182 monitor.move_to_workspace_down(activate);
2183 }
2184
2185 pub fn move_to_workspace(
2186 &mut self,
2187 window: Option<&W::Id>,
2188 idx: usize,
2189 activate: ActivateWindow,
2190 ) {
2191 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
2192 if window.is_none() || window == Some(move_.tile.window().id()) {
2193 return;
2194 }
2195 }
2196
2197 let monitor = if let Some(window) = window {
2198 match &mut self.monitor_set {
2199 MonitorSet::Normal { monitors, .. } => monitors
2200 .iter_mut()
2201 .find(|mon| mon.has_window(window))
2202 .unwrap(),
2203 MonitorSet::NoOutputs { .. } => {
2204 return;
2205 }
2206 }
2207 } else {
2208 let Some(monitor) = self.active_monitor() else {
2209 return;
2210 };
2211 monitor
2212 };
2213 monitor.move_to_workspace(window, idx, activate);
2214 }
2215
2216 pub fn move_column_to_workspace_up(&mut self, activate: bool) {
2217 let Some(monitor) = self.active_monitor() else {
2218 return;
2219 };
2220 monitor.move_column_to_workspace_up(activate);
2221 }
2222
2223 pub fn move_column_to_workspace_down(&mut self, activate: bool) {
2224 let Some(monitor) = self.active_monitor() else {
2225 return;
2226 };
2227 monitor.move_column_to_workspace_down(activate);
2228 }
2229
2230 pub fn move_column_to_workspace(&mut self, idx: usize, activate: bool) {
2231 let Some(monitor) = self.active_monitor() else {
2232 return;
2233 };
2234 monitor.move_column_to_workspace(idx, activate);
2235 }
2236
2237 pub fn switch_workspace_up(&mut self) {
2238 let Some(monitor) = self.active_monitor() else {
2239 return;
2240 };
2241 monitor.switch_workspace_up();
2242 }
2243
2244 pub fn switch_workspace_down(&mut self) {
2245 let Some(monitor) = self.active_monitor() else {
2246 return;
2247 };
2248 monitor.switch_workspace_down();
2249 }
2250
2251 pub fn switch_workspace(&mut self, idx: usize) {
2252 let Some(monitor) = self.active_monitor() else {
2253 return;
2254 };
2255 monitor.switch_workspace(idx);
2256 }
2257
2258 pub fn switch_workspace_auto_back_and_forth(&mut self, idx: usize) {
2259 let Some(monitor) = self.active_monitor() else {
2260 return;
2261 };
2262 monitor.switch_workspace_auto_back_and_forth(idx);
2263 }
2264
2265 pub fn switch_workspace_previous(&mut self) {
2266 let Some(monitor) = self.active_monitor() else {
2267 return;
2268 };
2269 monitor.switch_workspace_previous();
2270 }
2271
2272 pub fn consume_into_column(&mut self) {
2273 let Some(workspace) = self.active_workspace_mut() else {
2274 return;
2275 };
2276 workspace.consume_into_column();
2277 }
2278
2279 pub fn expel_from_column(&mut self) {
2280 let Some(workspace) = self.active_workspace_mut() else {
2281 return;
2282 };
2283 workspace.expel_from_column();
2284 }
2285
2286 pub fn swap_window_in_direction(&mut self, direction: ScrollDirection) {
2287 let Some(workspace) = self.active_workspace_mut() else {
2288 return;
2289 };
2290 workspace.swap_window_in_direction(direction);
2291 }
2292
2293 pub fn toggle_column_tabbed_display(&mut self) {
2294 let Some(workspace) = self.active_workspace_mut() else {
2295 return;
2296 };
2297 workspace.toggle_column_tabbed_display();
2298 }
2299
2300 pub fn set_column_display(&mut self, display: ColumnDisplay) {
2301 let Some(workspace) = self.active_workspace_mut() else {
2302 return;
2303 };
2304 workspace.set_column_display(display);
2305 }
2306
2307 pub fn center_column(&mut self) {
2308 let Some(workspace) = self.active_workspace_mut() else {
2309 return;
2310 };
2311 workspace.center_column();
2312 }
2313
2314 pub fn center_window(&mut self, id: Option<&W::Id>) {
2315 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
2316 if id.is_none() || id == Some(move_.tile.window().id()) {
2317 return;
2318 }
2319 }
2320
2321 let workspace = if let Some(id) = id {
2322 Some(self.workspaces_mut().find(|ws| ws.has_window(id)).unwrap())
2323 } else {
2324 self.active_workspace_mut()
2325 };
2326
2327 let Some(workspace) = workspace else {
2328 return;
2329 };
2330 workspace.center_window(id);
2331 }
2332
2333 pub fn center_visible_columns(&mut self) {
2334 let Some(workspace) = self.active_workspace_mut() else {
2335 return;
2336 };
2337 workspace.center_visible_columns();
2338 }
2339
2340 pub fn focus(&self) -> Option<&W> {
2341 self.focus_with_output().map(|(win, _out)| win)
2342 }
2343
2344 pub fn focus_with_output(&self) -> Option<(&W, &Output)> {
2345 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
2346 return Some((move_.tile.window(), &move_.output));
2347 }
2348
2349 let MonitorSet::Normal {
2350 monitors,
2351 active_monitor_idx,
2352 ..
2353 } = &self.monitor_set
2354 else {
2355 return None;
2356 };
2357
2358 let mon = &monitors[*active_monitor_idx];
2359 mon.active_window().map(|win| (win, &mon.output))
2360 }
2361
2362 pub fn interactive_moved_window_under(
2363 &self,
2364 output: &Output,
2365 pos_within_output: Point<f64, Logical>,
2366 ) -> Option<(&W, HitType)> {
2367 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
2368 if move_.output == *output {
2369 if self.overview_progress.is_some() {
2370 let zoom = self.overview_zoom();
2371 let tile_pos = move_.tile_render_location(zoom);
2372 let pos_within_tile = (pos_within_output - tile_pos).downscale(zoom);
2373 // During the overview animation, we cannot do input hits because we cannot
2374 // really represent scaled windows properly.
2375 let (win, hit) =
2376 HitType::hit_tile(&move_.tile, Point::from((0., 0.)), pos_within_tile)?;
2377 Some((win, hit.to_activate()))
2378 } else {
2379 let tile_pos = move_.tile_render_location(1.);
2380 HitType::hit_tile(&move_.tile, tile_pos, pos_within_output)
2381 }
2382 } else {
2383 None
2384 }
2385 } else {
2386 None
2387 }
2388 }
2389
2390 /// Returns the window under the cursor and the hit type.
2391 pub fn window_under(
2392 &self,
2393 output: &Output,
2394 pos_within_output: Point<f64, Logical>,
2395 ) -> Option<(&W, HitType)> {
2396 let mon = self.monitor_for_output(output)?;
2397 mon.window_under(pos_within_output)
2398 }
2399
2400 pub fn resize_edges_under(
2401 &self,
2402 output: &Output,
2403 pos_within_output: Point<f64, Logical>,
2404 ) -> Option<ResizeEdge> {
2405 let mon = self.monitor_for_output(output)?;
2406 mon.resize_edges_under(pos_within_output)
2407 }
2408
2409 pub fn workspace_under(
2410 &self,
2411 extended_bounds: bool,
2412 output: &Output,
2413 pos_within_output: Point<f64, Logical>,
2414 ) -> Option<&Workspace<W>> {
2415 if self
2416 .interactive_moved_window_under(output, pos_within_output)
2417 .is_some()
2418 {
2419 return None;
2420 }
2421
2422 let mon = self.monitor_for_output(output)?;
2423 if extended_bounds {
2424 mon.workspace_under(pos_within_output).map(|(ws, _)| ws)
2425 } else {
2426 mon.workspace_under_narrow(pos_within_output)
2427 }
2428 }
2429
2430 pub fn overview_zoom(&self) -> f64 {
2431 let progress = self.overview_progress.as_ref().map(|p| p.value());
2432 compute_overview_zoom(&self.options, progress)
2433 }
2434
2435 #[cfg(test)]
2436 fn verify_invariants(&self) {
2437 use std::collections::HashSet;
2438
2439 use approx::assert_abs_diff_eq;
2440
2441 let zoom = self.overview_zoom();
2442
2443 let mut move_win_id = None;
2444 if let Some(state) = &self.interactive_move {
2445 match state {
2446 InteractiveMoveState::Starting {
2447 window_id,
2448 pointer_delta: _,
2449 pointer_ratio_within_window: _,
2450 } => {
2451 assert!(
2452 self.has_window(window_id),
2453 "interactive move must be on an existing window"
2454 );
2455 move_win_id = Some(window_id.clone());
2456 }
2457 InteractiveMoveState::Moving(move_) => {
2458 assert_eq!(self.clock, move_.tile.clock);
2459 assert!(move_.tile.window().pending_sizing_mode().is_normal());
2460
2461 move_.tile.verify_invariants();
2462
2463 let scale = move_.output.current_scale().fractional_scale();
2464 let options = Options::clone(&self.options)
2465 .with_merged_layout(move_.output_config.as_ref())
2466 .with_merged_layout(move_.workspace_config.as_ref().map(|(_, c)| c))
2467 .adjusted_for_scale(scale);
2468 assert_eq!(
2469 &*move_.tile.options, &options,
2470 "interactive moved tile options must be \
2471 base options adjusted for output scale"
2472 );
2473
2474 let tile_pos = move_.tile_render_location(zoom);
2475 let rounded_pos = tile_pos.to_physical_precise_round(scale).to_logical(scale);
2476
2477 // Tile position must be rounded to physical pixels.
2478 assert_abs_diff_eq!(tile_pos.x, rounded_pos.x, epsilon = 1e-5);
2479 assert_abs_diff_eq!(tile_pos.y, rounded_pos.y, epsilon = 1e-5);
2480
2481 if let Some(alpha) = &move_.tile.alpha_animation {
2482 if move_.is_floating {
2483 assert_eq!(
2484 alpha.anim.to(),
2485 1.,
2486 "interactively moved floating tile can animate alpha only to 1"
2487 );
2488
2489 assert!(
2490 !alpha.hold_after_done,
2491 "interactively moved floating tile \
2492 cannot have held alpha animation"
2493 );
2494 } else {
2495 assert_ne!(
2496 alpha.anim.to(),
2497 1.,
2498 "interactively moved scrolling tile must animate alpha to not 1"
2499 );
2500
2501 assert!(
2502 alpha.hold_after_done,
2503 "interactively moved scrolling tile \
2504 must have held alpha animation"
2505 );
2506 }
2507 }
2508 }
2509 }
2510 }
2511
2512 let mut seen_workspace_id = HashSet::new();
2513 let mut seen_workspace_name = Vec::<String>::new();
2514
2515 let (monitors, &primary_idx, &active_monitor_idx) = match &self.monitor_set {
2516 MonitorSet::Normal {
2517 monitors,
2518 primary_idx,
2519 active_monitor_idx,
2520 } => (monitors, primary_idx, active_monitor_idx),
2521 MonitorSet::NoOutputs { workspaces } => {
2522 for workspace in workspaces {
2523 assert!(
2524 workspace.has_windows_or_name(),
2525 "with no outputs there cannot be empty unnamed workspaces"
2526 );
2527
2528 assert_eq!(self.clock, workspace.clock);
2529
2530 assert_eq!(
2531 workspace.base_options, self.options,
2532 "workspace base options must be synchronized with layout"
2533 );
2534
2535 assert!(
2536 seen_workspace_id.insert(workspace.id()),
2537 "workspace id must be unique"
2538 );
2539
2540 if let Some(name) = &workspace.name {
2541 assert!(
2542 !seen_workspace_name
2543 .iter()
2544 .any(|n| n.eq_ignore_ascii_case(name)),
2545 "workspace name must be unique"
2546 );
2547 seen_workspace_name.push(name.clone());
2548 }
2549
2550 workspace.verify_invariants(move_win_id.as_ref());
2551 }
2552
2553 return;
2554 }
2555 };
2556
2557 assert!(primary_idx < monitors.len());
2558 assert!(active_monitor_idx < monitors.len());
2559
2560 let mut saw_view_offset_gesture = false;
2561
2562 for (idx, monitor) in monitors.iter().enumerate() {
2563 assert_eq!(self.clock, monitor.clock);
2564 assert_eq!(
2565 monitor.base_options, self.options,
2566 "monitor base options must be synchronized with layout"
2567 );
2568
2569 assert_eq!(self.overview_open, monitor.overview_open);
2570 assert_eq!(
2571 self.overview_progress.as_ref().map(|p| p.value()),
2572 monitor.overview_progress_value()
2573 );
2574
2575 monitor.verify_invariants();
2576
2577 for workspace in &monitor.workspaces {
2578 let preferred =
2579 workspace.find_preferred_output(monitors.iter().map(|monitor| &monitor.output));
2580 let Some(preferred_idx) = preferred else {
2581 assert_eq!(
2582 idx, primary_idx,
2583 "workspace without a connected output candidate must be on the primary monitor"
2584 );
2585 continue;
2586 };
2587 assert_eq!(
2588 idx, preferred_idx,
2589 "workspace must be on its preferred connected output"
2590 );
2591 }
2592
2593 for workspace in &monitor.workspaces {
2594 assert!(
2595 seen_workspace_id.insert(workspace.id()),
2596 "workspace id must be unique"
2597 );
2598
2599 if let Some(name) = &workspace.name {
2600 assert!(
2601 !seen_workspace_name
2602 .iter()
2603 .any(|n| n.eq_ignore_ascii_case(name)),
2604 "workspace name must be unique"
2605 );
2606 seen_workspace_name.push(name.clone());
2607 }
2608
2609 workspace.verify_invariants(move_win_id.as_ref());
2610
2611 let has_view_offset_gesture = workspace.scrolling().view_offset().is_gesture();
2612 if self.dnd.is_some() || self.interactive_move.is_some() {
2613 // We'd like to check that all workspaces have the gesture here, furthermore we
2614 // want to check that they have the gesture only if the interactive move
2615 // targets the scrolling layout. However, we cannot do that because we start
2616 // and stop the gesture lazily. Otherwise the gesture code would pollute a lot
2617 // of places like adding new workspaces, implicitly moving windows between
2618 // floating and tiling on fullscreen, etc.
2619 //
2620 // assert!(
2621 // has_view_offset_gesture,
2622 // "during an interactive move in the scrolling layout, \
2623 // all workspaces should be in a view offset gesture"
2624 // );
2625 } else if saw_view_offset_gesture {
2626 assert!(
2627 !has_view_offset_gesture,
2628 "only one workspace can have an ongoing view offset gesture"
2629 );
2630 }
2631 saw_view_offset_gesture = has_view_offset_gesture;
2632 }
2633 }
2634 }
2635
2636 pub fn advance_animations(&mut self) {
2637 let _span = tracy_client::span!("Layout::advance_animations");
2638
2639 let mut dnd_scroll = None;
2640 let mut is_dnd = false;
2641 if let Some(dnd) = &self.dnd {
2642 dnd_scroll = Some((dnd.output.clone(), dnd.pointer_pos_within_output, true));
2643 is_dnd = true;
2644 }
2645
2646 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
2647 move_.tile.advance_animations();
2648
2649 if dnd_scroll.is_none() {
2650 dnd_scroll = Some((
2651 move_.output.clone(),
2652 move_.pointer_pos_within_output,
2653 !move_.is_floating,
2654 ));
2655 }
2656 }
2657
2658 let is_overview_open = self.overview_open;
2659
2660 // Scroll the view if needed.
2661 if let Some((output, pos_within_output, is_scrolling)) = dnd_scroll {
2662 if let Some(mon) = self.monitor_for_output_mut(&output) {
2663 let mut scrolled = false;
2664
2665 let zoom = mon.overview_zoom();
2666 scrolled |= mon.dnd_scroll_gesture_scroll(pos_within_output, 1. / zoom);
2667
2668 if is_scrolling {
2669 if let Some((ws, geo)) = mon.workspace_under(pos_within_output) {
2670 let idx = mon.idx_of_ws(ws.id()).unwrap();
2671 let ws = &mut mon.workspaces[idx];
2672 // As far as the DnD scroll gesture is concerned, the workspace spans across
2673 // the whole monitor horizontally.
2674 let ws_pos = Point::from((0., geo.loc.y));
2675 scrolled |=
2676 ws.dnd_scroll_gesture_scroll(pos_within_output - ws_pos, 1. / zoom);
2677 }
2678 }
2679
2680 if scrolled {
2681 // Don't trigger DnD hold while scrolling.
2682 if let Some(dnd) = &mut self.dnd {
2683 dnd.hold = None;
2684 }
2685 } else if is_dnd {
2686 let target = mon
2687 .window_under(pos_within_output)
2688 .map(|(win, _)| DndHoldTarget::Window(win.id().clone()))
2689 .or_else(|| {
2690 mon.workspace_under_narrow(pos_within_output)
2691 .map(|ws| DndHoldTarget::Workspace(ws.id()))
2692 });
2693
2694 let dnd = self.dnd.as_mut().unwrap();
2695 if let Some(target) = target {
2696 let now = self.clock.now_unadjusted();
2697 let start_time = if let Some(hold) = &mut dnd.hold {
2698 if hold.target != target {
2699 hold.start_time = now;
2700 }
2701 hold.target = target;
2702 hold.start_time
2703 } else {
2704 let hold = dnd.hold.insert(DndHold {
2705 start_time: now,
2706 target,
2707 });
2708 hold.start_time
2709 };
2710
2711 // Delay copied from gnome-shell.
2712 let delay = Duration::from_millis(750);
2713 if delay <= now.saturating_sub(start_time) {
2714 let hold = dnd.hold.take().unwrap();
2715
2716 // Synchronize workspace switch to overview close to get a monotonic
2717 // animation.
2718 let config = is_overview_open
2719 .then_some(self.options.animations.overview_open_close.0);
2720
2721 let mon = self.monitor_for_output_mut(&output).unwrap();
2722
2723 let ws_idx = match hold.target {
2724 DndHoldTarget::Window(id) => mon
2725 .workspaces
2726 .iter_mut()
2727 .position(|ws| ws.activate_window(&id))
2728 .unwrap(),
2729 DndHoldTarget::Workspace(id) => mon.idx_of_ws(id).unwrap(),
2730 };
2731
2732 mon.dnd_scroll_gesture_end();
2733 mon.activate_workspace_with_anim_config(ws_idx, config);
2734
2735 self.focus_output(&output);
2736
2737 if is_overview_open {
2738 self.close_overview();
2739 }
2740 }
2741 } else {
2742 // No target, reset the hold timer.
2743 dnd.hold = None;
2744 }
2745 }
2746 }
2747 }
2748
2749 if let Some(OverviewProgress::Animation(anim)) = &mut self.overview_progress {
2750 if anim.is_done() {
2751 if self.overview_open {
2752 self.overview_progress = Some(OverviewProgress::Open);
2753 } else {
2754 self.overview_progress = None;
2755 }
2756 }
2757 }
2758
2759 match &mut self.monitor_set {
2760 MonitorSet::Normal { monitors, .. } => {
2761 for mon in monitors {
2762 mon.set_overview_progress(self.overview_progress.as_ref());
2763 mon.advance_animations();
2764 }
2765 }
2766 MonitorSet::NoOutputs { workspaces, .. } => {
2767 for ws in workspaces {
2768 ws.advance_animations();
2769 }
2770 }
2771 }
2772 }
2773
2774 pub fn are_animations_ongoing(&self, output: Option<&Output>) -> bool {
2775 // Keep advancing animations if we might need to scroll the view.
2776 if let Some(dnd) = &self.dnd {
2777 if output.is_none_or(|output| *output == dnd.output) {
2778 return true;
2779 }
2780 }
2781
2782 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
2783 if output.is_none_or(|output| *output == move_.output) {
2784 if move_.tile.are_animations_ongoing() {
2785 return true;
2786 }
2787
2788 // Keep advancing animations if we might need to scroll the view.
2789 if !move_.is_floating || self.overview_open {
2790 return true;
2791 }
2792 }
2793 }
2794
2795 if self
2796 .overview_progress
2797 .as_ref()
2798 .is_some_and(|p| p.is_animation())
2799 {
2800 return true;
2801 }
2802
2803 for mon in self.monitors() {
2804 if output.is_some_and(|output| mon.output != *output) {
2805 continue;
2806 }
2807
2808 if mon.are_animations_ongoing() {
2809 return true;
2810 }
2811 }
2812
2813 false
2814 }
2815
2816 pub fn update_render_elements(&mut self, output: Option<&Output>) {
2817 let _span = tracy_client::span!("Layout::update_render_elements");
2818
2819 self.update_render_elements_time = self.clock.now();
2820
2821 let zoom = self.overview_zoom();
2822 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
2823 if output.is_none_or(|output| move_.output == *output) {
2824 let pos_within_output = move_.tile_render_location(zoom);
2825
2826 // We're not on any specific workspace so we can't compute a "workspace view" rect.
2827 // Let's instead compute a rect relative to the output.
2828 //
2829 // FIXME: we could make the colors match up better in the overview by figuring out
2830 // where a centered workspace would currently be, and computing the view rect
2831 // against that. Since most of the time the dragged window will be on a centered
2832 // workspace.
2833 let view_rect =
2834 Rectangle::new(pos_within_output.upscale(-1.), output_size(&move_.output))
2835 .downscale(zoom);
2836
2837 move_.tile.update_render_elements(true, view_rect);
2838 }
2839 }
2840
2841 self.update_insert_hint(output);
2842
2843 let MonitorSet::Normal {
2844 monitors,
2845 active_monitor_idx,
2846 ..
2847 } = &mut self.monitor_set
2848 else {
2849 if output.is_some() {
2850 error!("update_render_elements called with no monitors but Some output");
2851 }
2852 return;
2853 };
2854
2855 for (idx, mon) in monitors.iter_mut().enumerate() {
2856 if output.is_none_or(|output| mon.output == *output) {
2857 let is_active = self.is_active
2858 && idx == *active_monitor_idx
2859 && !matches!(self.interactive_move, Some(InteractiveMoveState::Moving(_)));
2860 mon.set_overview_progress(self.overview_progress.as_ref());
2861 mon.update_render_elements(is_active);
2862 }
2863 }
2864 }
2865
2866 pub fn update_shaders(&mut self) {
2867 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
2868 move_.tile.update_shaders();
2869 }
2870
2871 match &mut self.monitor_set {
2872 MonitorSet::Normal { monitors, .. } => {
2873 for mon in monitors {
2874 mon.update_shaders();
2875 }
2876 }
2877 MonitorSet::NoOutputs { workspaces, .. } => {
2878 for ws in workspaces {
2879 ws.update_shaders();
2880 }
2881 }
2882 }
2883 }
2884
2885 fn update_insert_hint(&mut self, output: Option<&Output>) {
2886 let _span = tracy_client::span!("Layout::update_insert_hint");
2887
2888 for mon in self.monitors_mut() {
2889 mon.insert_hint = None;
2890 }
2891
2892 if !matches!(self.interactive_move, Some(InteractiveMoveState::Moving(_))) {
2893 return;
2894 }
2895 let Some(InteractiveMoveState::Moving(move_)) = self.interactive_move.take() else {
2896 unreachable!()
2897 };
2898 if output.is_some_and(|out| &move_.output != out) {
2899 self.interactive_move = Some(InteractiveMoveState::Moving(move_));
2900 return;
2901 }
2902
2903 let _span = tracy_client::span!("Layout::update_insert_hint::update");
2904
2905 if let Some(mon) = self.monitor_for_output_mut(&move_.output) {
2906 let zoom = mon.overview_zoom();
2907 let (insert_ws, geo) = mon.insert_position(move_.pointer_pos_within_output);
2908 match insert_ws {
2909 InsertWorkspace::Existing(ws_id) => {
2910 let idx = mon.idx_of_ws(ws_id).unwrap();
2911 let ws = &mut mon.workspaces[idx];
2912 let pos_within_workspace =
2913 (move_.pointer_pos_within_output - geo.loc).downscale(zoom);
2914 let position = if move_.is_floating {
2915 InsertPosition::Floating
2916 } else {
2917 ws.scrolling_insert_position(pos_within_workspace)
2918 };
2919
2920 let border_width = move_.tile.effective_border_width().unwrap_or(0.);
2921 let corner_radius = move_
2922 .tile
2923 .window()
2924 .geometry_corner_radius()
2925 .expanded_by(border_width as f32);
2926 mon.insert_hint = Some(InsertHint {
2927 workspace: insert_ws,
2928 position,
2929 corner_radius,
2930 });
2931 }
2932 InsertWorkspace::NewAt(_) => {
2933 let position = if move_.is_floating {
2934 InsertPosition::Floating
2935 } else {
2936 InsertPosition::NewColumn(0)
2937 };
2938 mon.insert_hint = Some(InsertHint {
2939 workspace: insert_ws,
2940 position,
2941 corner_radius: CornerRadius::default(),
2942 });
2943 }
2944 }
2945 }
2946
2947 self.interactive_move = Some(InteractiveMoveState::Moving(move_));
2948 }
2949
2950 pub fn ensure_named_workspace(&mut self, ws_config: &WorkspaceConfig) {
2951 self.ensure_named_workspace_at(ws_config, false);
2952 }
2953
2954 /// Creates a hidden named workspace on demand, at the bottom of its monitor.
2955 pub fn ensure_hidden_workspace(&mut self, ws_config: &WorkspaceConfig) {
2956 self.ensure_named_workspace_at(ws_config, true);
2957 }
2958
2959 fn ensure_named_workspace_at(&mut self, ws_config: &WorkspaceConfig, at_bottom: bool) {
2960 if self.find_workspace_by_name(&ws_config.name.0).is_some() {
2961 return;
2962 }
2963
2964 let clock = self.clock.clone();
2965 let options = self.options.clone();
2966
2967 match &mut self.monitor_set {
2968 MonitorSet::Normal {
2969 monitors,
2970 primary_idx,
2971 active_monitor_idx,
2972 } => {
2973 let mon_idx = if ws_config.open_on_output.is_empty() {
2974 *active_monitor_idx
2975 } else {
2976 ws_config
2977 .open_on_output
2978 .iter()
2979 .find_map(|name| {
2980 monitors
2981 .iter()
2982 .position(|monitor| output_matches_name(&monitor.output, name))
2983 })
2984 .unwrap_or(*primary_idx)
2985 };
2986 let mon = &mut monitors[mon_idx];
2987
2988 let ws = Workspace::new_with_config(
2989 mon.output.clone(),
2990 Some(ws_config.clone()),
2991 clock,
2992 options,
2993 );
2994
2995 if at_bottom {
2996 // Insert directly rather than via insert_workspace, which would clean up
2997 // the new (empty, hidden) workspace right away.
2998 mon.workspace_switch = None;
2999 let mut ws = ws;
3000 ws.update_config(mon.options.clone());
3001 let mut idx = mon.workspaces.len() - 1;
3002 if idx == 0 && mon.options.layout.empty_workspace_above_first {
3003 // Keep the empty workspace above the first one.
3004 mon.add_workspace_top();
3005 idx += 1;
3006 }
3007 mon.workspaces.insert(idx, ws);
3008 if idx <= mon.active_workspace_idx {
3009 mon.active_workspace_idx += 1;
3010 }
3011 } else {
3012 mon.insert_workspace(ws, 0, false);
3013 }
3014 }
3015 MonitorSet::NoOutputs { workspaces } => {
3016 let ws =
3017 Workspace::new_with_config_no_outputs(Some(ws_config.clone()), clock, options);
3018 if at_bottom {
3019 workspaces.push(ws);
3020 } else {
3021 workspaces.insert(0, ws);
3022 }
3023 }
3024 }
3025 }
3026
3027 pub fn update_config(&mut self, config: &Config) {
3028 // Update workspace-specific config for all named workspaces.
3029 for ws in self.workspaces_mut() {
3030 let Some(name) = ws.name() else { continue };
3031 if let Some(config) = config.workspaces.iter().find(|w| &w.name.0 == name) {
3032 ws.update_layout_config(config.layout.clone().map(|x| x.0));
3033 ws.set_hidden(config.hidden);
3034 }
3035 }
3036
3037 // Workspaces that just became hidden and are empty should go away.
3038 if let MonitorSet::Normal { monitors, .. } = &mut self.monitor_set {
3039 for mon in monitors {
3040 if mon.workspace_switch.is_none() {
3041 mon.clean_up_workspaces();
3042 }
3043 }
3044 }
3045
3046 self.update_options(Options::from_config(config));
3047 }
3048
3049 fn update_options(&mut self, options: Options) {
3050 let options = Rc::new(options);
3051
3052 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
3053 let view_size = output_size(&move_.output);
3054 let scale = move_.output.current_scale().fractional_scale();
3055 let options = Options::clone(&options)
3056 .with_merged_layout(move_.output_config.as_ref())
3057 .with_merged_layout(move_.workspace_config.as_ref().map(|(_, c)| c))
3058 .adjusted_for_scale(scale);
3059 move_.tile.update_config(view_size, scale, Rc::new(options));
3060 }
3061
3062 match &mut self.monitor_set {
3063 MonitorSet::Normal { monitors, .. } => {
3064 for mon in monitors {
3065 mon.update_config(options.clone());
3066 }
3067 }
3068 MonitorSet::NoOutputs { workspaces } => {
3069 for ws in workspaces {
3070 ws.update_config(options.clone());
3071 }
3072 }
3073 }
3074
3075 self.options = options;
3076 }
3077
3078 pub fn toggle_width(&mut self, forwards: bool) {
3079 let Some(workspace) = self.active_workspace_mut() else {
3080 return;
3081 };
3082 workspace.toggle_width(forwards);
3083 }
3084
3085 pub fn toggle_window_width(&mut self, window: Option<&W::Id>, forwards: bool) {
3086 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
3087 if window.is_none() || window == Some(move_.tile.window().id()) {
3088 return;
3089 }
3090 }
3091
3092 let workspace = if let Some(window) = window {
3093 Some(
3094 self.workspaces_mut()
3095 .find(|ws| ws.has_window(window))
3096 .unwrap(),
3097 )
3098 } else {
3099 self.active_workspace_mut()
3100 };
3101
3102 let Some(workspace) = workspace else {
3103 return;
3104 };
3105 workspace.toggle_window_width(window, forwards);
3106 }
3107
3108 pub fn toggle_window_height(&mut self, window: Option<&W::Id>, forwards: bool) {
3109 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
3110 if window.is_none() || window == Some(move_.tile.window().id()) {
3111 return;
3112 }
3113 }
3114
3115 let workspace = if let Some(window) = window {
3116 Some(
3117 self.workspaces_mut()
3118 .find(|ws| ws.has_window(window))
3119 .unwrap(),
3120 )
3121 } else {
3122 self.active_workspace_mut()
3123 };
3124
3125 let Some(workspace) = workspace else {
3126 return;
3127 };
3128 workspace.toggle_window_height(window, forwards);
3129 }
3130
3131 pub fn toggle_full_width(&mut self) {
3132 let Some(workspace) = self.active_workspace_mut() else {
3133 return;
3134 };
3135 workspace.toggle_full_width();
3136 }
3137
3138 pub fn set_column_width(&mut self, change: SizeChange) {
3139 let Some(workspace) = self.active_workspace_mut() else {
3140 return;
3141 };
3142 workspace.set_column_width(change);
3143 }
3144
3145 pub fn set_window_width(&mut self, window: Option<&W::Id>, change: SizeChange) {
3146 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
3147 if window.is_none() || window == Some(move_.tile.window().id()) {
3148 return;
3149 }
3150 }
3151
3152 let workspace = if let Some(window) = window {
3153 Some(
3154 self.workspaces_mut()
3155 .find(|ws| ws.has_window(window))
3156 .unwrap(),
3157 )
3158 } else {
3159 self.active_workspace_mut()
3160 };
3161
3162 let Some(workspace) = workspace else {
3163 return;
3164 };
3165 workspace.set_window_width(window, change);
3166 }
3167
3168 pub fn set_window_height(&mut self, window: Option<&W::Id>, change: SizeChange) {
3169 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
3170 if window.is_none() || window == Some(move_.tile.window().id()) {
3171 return;
3172 }
3173 }
3174
3175 let workspace = if let Some(window) = window {
3176 Some(
3177 self.workspaces_mut()
3178 .find(|ws| ws.has_window(window))
3179 .unwrap(),
3180 )
3181 } else {
3182 self.active_workspace_mut()
3183 };
3184
3185 let Some(workspace) = workspace else {
3186 return;
3187 };
3188 workspace.set_window_height(window, change);
3189 }
3190
3191 pub fn reset_window_height(&mut self, window: Option<&W::Id>) {
3192 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
3193 if window.is_none() || window == Some(move_.tile.window().id()) {
3194 return;
3195 }
3196 }
3197
3198 let workspace = if let Some(window) = window {
3199 Some(
3200 self.workspaces_mut()
3201 .find(|ws| ws.has_window(window))
3202 .unwrap(),
3203 )
3204 } else {
3205 self.active_workspace_mut()
3206 };
3207
3208 let Some(workspace) = workspace else {
3209 return;
3210 };
3211 workspace.reset_window_height(window);
3212 }
3213
3214 pub fn expand_column_to_available_width(&mut self) {
3215 let Some(workspace) = self.active_workspace_mut() else {
3216 return;
3217 };
3218 workspace.expand_column_to_available_width();
3219 }
3220
3221 pub fn toggle_window_floating(&mut self, window: Option<&W::Id>) {
3222 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
3223 if window.is_none() || window == Some(move_.tile.window().id()) {
3224 move_.is_floating = !move_.is_floating;
3225
3226 // When going to floating, restore the floating window size.
3227 if move_.is_floating {
3228 let floating_size = move_.tile.floating_window_size;
3229 let win = move_.tile.window_mut();
3230 let mut size =
3231 floating_size.unwrap_or_else(|| win.expected_size().unwrap_or_default());
3232
3233 // Apply min/max size window rules. If requesting a concrete size, apply
3234 // completely; if requesting (0, 0), apply only when min/max results in a fixed
3235 // size.
3236 let min_size = win.min_size();
3237 let max_size = win.max_size();
3238 size.w = ensure_min_max_size_maybe_zero(size.w, min_size.w, max_size.w);
3239 size.h = ensure_min_max_size_maybe_zero(size.h, min_size.h, max_size.h);
3240
3241 win.request_size_once(size, true);
3242
3243 // Animate the tile back to opaque.
3244 move_.tile.animate_alpha(
3245 INTERACTIVE_MOVE_ALPHA,
3246 1.,
3247 self.options.animations.window_movement.0,
3248 );
3249
3250 // Unlock the view on the workspaces.
3251 for ws in self.workspaces_mut() {
3252 ws.dnd_scroll_gesture_end();
3253 }
3254 } else {
3255 // Animate the tile back to semitransparent.
3256 move_.tile.animate_alpha(
3257 1.,
3258 INTERACTIVE_MOVE_ALPHA,
3259 self.options.animations.window_movement.0,
3260 );
3261 move_.tile.hold_alpha_animation_after_done();
3262 }
3263
3264 return;
3265 }
3266 }
3267
3268 let workspace = if let Some(window) = window {
3269 Some(
3270 self.workspaces_mut()
3271 .find(|ws| ws.has_window(window))
3272 .unwrap(),
3273 )
3274 } else {
3275 self.active_workspace_mut()
3276 };
3277
3278 let Some(workspace) = workspace else {
3279 return;
3280 };
3281 workspace.toggle_window_floating(window);
3282 }
3283
3284 pub fn set_window_floating(&mut self, window: Option<&W::Id>, floating: bool) {
3285 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
3286 if window.is_none() || window == Some(move_.tile.window().id()) {
3287 if move_.is_floating != floating {
3288 self.toggle_window_floating(window);
3289 }
3290 return;
3291 }
3292 }
3293
3294 let workspace = if let Some(window) = window {
3295 Some(
3296 self.workspaces_mut()
3297 .find(|ws| ws.has_window(window))
3298 .unwrap(),
3299 )
3300 } else {
3301 self.active_workspace_mut()
3302 };
3303
3304 let Some(workspace) = workspace else {
3305 return;
3306 };
3307 workspace.set_window_floating(window, floating);
3308 }
3309
3310 pub fn focus_floating(&mut self) {
3311 let Some(workspace) = self.active_workspace_mut() else {
3312 return;
3313 };
3314 workspace.focus_floating();
3315 }
3316
3317 pub fn focus_tiling(&mut self) {
3318 let Some(workspace) = self.active_workspace_mut() else {
3319 return;
3320 };
3321 workspace.focus_tiling();
3322 }
3323
3324 pub fn switch_focus_floating_tiling(&mut self) {
3325 let Some(workspace) = self.active_workspace_mut() else {
3326 return;
3327 };
3328 workspace.switch_focus_floating_tiling();
3329 }
3330
3331 pub fn move_floating_window(
3332 &mut self,
3333 id: Option<&W::Id>,
3334 x: PositionChange,
3335 y: PositionChange,
3336 animate: bool,
3337 ) {
3338 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
3339 if id.is_none() || id == Some(move_.tile.window().id()) {
3340 return;
3341 }
3342 }
3343
3344 let workspace = if let Some(id) = id {
3345 Some(self.workspaces_mut().find(|ws| ws.has_window(id)).unwrap())
3346 } else {
3347 self.active_workspace_mut()
3348 };
3349
3350 let Some(workspace) = workspace else {
3351 return;
3352 };
3353 workspace.move_floating_window(id, x, y, animate);
3354 }
3355
3356 pub fn focus_output(&mut self, output: &Output) {
3357 if let MonitorSet::Normal {
3358 monitors,
3359 active_monitor_idx,
3360 ..
3361 } = &mut self.monitor_set
3362 {
3363 for (idx, mon) in monitors.iter().enumerate() {
3364 if &mon.output == output {
3365 *active_monitor_idx = idx;
3366 return;
3367 }
3368 }
3369 }
3370 }
3371
3372 pub fn move_to_output(
3373 &mut self,
3374 window: Option<&W::Id>,
3375 output: &Output,
3376 target_ws_idx: Option<usize>,
3377 activate: ActivateWindow,
3378 ) {
3379 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
3380 if window.is_none() || window == Some(move_.tile.window().id()) {
3381 return;
3382 }
3383 }
3384
3385 if let MonitorSet::Normal {
3386 monitors,
3387 active_monitor_idx,
3388 ..
3389 } = &mut self.monitor_set
3390 {
3391 let new_idx = monitors
3392 .iter()
3393 .position(|mon| &mon.output == output)
3394 .unwrap();
3395
3396 let (mon_idx, ws_idx) = if let Some(window) = window {
3397 monitors
3398 .iter()
3399 .enumerate()
3400 .find_map(|(mon_idx, mon)| {
3401 mon.workspaces
3402 .iter()
3403 .position(|ws| ws.has_window(window))
3404 .map(|ws_idx| (mon_idx, ws_idx))
3405 })
3406 .unwrap()
3407 } else {
3408 let mon_idx = *active_monitor_idx;
3409 let mon = &monitors[mon_idx];
3410 (mon_idx, mon.active_workspace_idx)
3411 };
3412
3413 let workspace_idx = target_ws_idx.unwrap_or(monitors[new_idx].active_workspace_idx);
3414 if mon_idx == new_idx && ws_idx == workspace_idx {
3415 return;
3416 }
3417
3418 let mon = &monitors[new_idx];
3419 if mon.workspaces.len() <= workspace_idx {
3420 return;
3421 }
3422
3423 let ws_id = mon.workspaces[workspace_idx].id();
3424
3425 let mon = &mut monitors[mon_idx];
3426 let activate = activate.map_smart(|| {
3427 window.is_none_or(|win| {
3428 mon_idx == *active_monitor_idx
3429 && mon.active_window().map(|win| win.id()) == Some(win)
3430 })
3431 });
3432 let activate = if activate {
3433 ActivateWindow::Yes
3434 } else {
3435 ActivateWindow::No
3436 };
3437
3438 let ws = &mut mon.workspaces[ws_idx];
3439 let Some(window) = window.or_else(|| ws.active_window().map(|win| win.id())) else {
3440 return;
3441 };
3442 let window = window.clone();
3443
3444 let transaction = Transaction::new();
3445 let mut removed = ws.remove_tile(&window, transaction);
3446
3447 removed.tile.stop_move_animations();
3448
3449 let mon = &mut monitors[new_idx];
3450 mon.add_tile(
3451 removed.tile,
3452 MonitorAddWindowTarget::Workspace {
3453 id: ws_id,
3454 column_idx: None,
3455 },
3456 activate,
3457 true,
3458 removed.width,
3459 removed.is_full_width,
3460 removed.is_floating,
3461 None,
3462 );
3463 if activate.map_smart(|| false) {
3464 *active_monitor_idx = new_idx;
3465 }
3466
3467 let mon = &mut monitors[mon_idx];
3468 if mon.workspace_switch.is_none() {
3469 monitors[mon_idx].clean_up_workspaces();
3470 }
3471 }
3472 }
3473
3474 pub fn move_column_to_output(
3475 &mut self,
3476 output: &Output,
3477 target_ws_idx: Option<usize>,
3478 activate: bool,
3479 ) {
3480 if let MonitorSet::Normal {
3481 monitors,
3482 active_monitor_idx,
3483 ..
3484 } = &mut self.monitor_set
3485 {
3486 let new_idx = monitors
3487 .iter()
3488 .position(|mon| &mon.output == output)
3489 .unwrap();
3490
3491 let current = &mut monitors[*active_monitor_idx];
3492 let ws = current.active_workspace();
3493
3494 if ws.floating_is_active() {
3495 self.move_to_output(None, output, None, ActivateWindow::Smart);
3496 return;
3497 }
3498
3499 let Some(column) = ws.remove_active_column() else {
3500 return;
3501 };
3502
3503 let workspace_idx = target_ws_idx
3504 .unwrap_or(monitors[new_idx].active_workspace_idx)
3505 .min(monitors[new_idx].workspaces.len() - 1);
3506 self.add_column_by_idx(new_idx, workspace_idx, column, activate);
3507 }
3508 }
3509
3510 pub fn move_workspace_to_output(&mut self, output: &Output) -> bool {
3511 let MonitorSet::Normal {
3512 monitors,
3513 active_monitor_idx,
3514 ..
3515 } = &self.monitor_set
3516 else {
3517 return false;
3518 };
3519
3520 let idx = monitors[*active_monitor_idx].active_workspace_idx;
3521 self.move_workspace_to_output_by_id(idx, None, output)
3522 }
3523
3524 // FIXME: accept workspace by id
3525 pub fn move_workspace_to_output_by_id(
3526 &mut self,
3527 old_idx: usize,
3528 old_output: Option<Output>,
3529 new_output: &Output,
3530 ) -> bool {
3531 let MonitorSet::Normal {
3532 monitors,
3533 active_monitor_idx,
3534 ..
3535 } = &mut self.monitor_set
3536 else {
3537 return false;
3538 };
3539
3540 let current_idx = if let Some(old_output) = old_output {
3541 monitors
3542 .iter()
3543 .position(|mon| mon.output == old_output)
3544 .unwrap()
3545 } else {
3546 *active_monitor_idx
3547 };
3548 let target_idx = monitors
3549 .iter()
3550 .position(|mon| mon.output == *new_output)
3551 .unwrap();
3552
3553 let current = &mut monitors[current_idx];
3554
3555 if current.workspaces.len() <= old_idx {
3556 return false;
3557 }
3558
3559 // Do not do anything if the output is already correct
3560 if current_idx == target_idx {
3561 // Just update the original output since this is an explicit movement action.
3562 current.workspaces[old_idx].original_outputs = vec![OutputId::new(&current.output)];
3563
3564 return false;
3565 }
3566
3567 // Only switch active monitor if the workspace to be moved is the currently focused one on
3568 // the current monitor.
3569 let activate =
3570 current_idx == *active_monitor_idx && old_idx == current.active_workspace_idx;
3571
3572 let mut ws = current.remove_workspace_by_idx(old_idx);
3573 ws.original_outputs = vec![OutputId::new(new_output)];
3574
3575 let target = &mut monitors[target_idx];
3576 target.insert_workspace(ws, target.active_workspace_idx + 1, activate);
3577
3578 if activate {
3579 *active_monitor_idx = target_idx;
3580 }
3581
3582 activate
3583 }
3584
3585 pub fn set_fullscreen(&mut self, id: &W::Id, is_fullscreen: bool) {
3586 // Check if this is a request to unset the windowed fullscreen state.
3587 if !is_fullscreen {
3588 let mut handled = false;
3589 self.with_windows_mut(|window, _| {
3590 if window.id() == id && window.is_pending_windowed_fullscreen() {
3591 window.request_windowed_fullscreen(false);
3592 handled = true;
3593 }
3594 });
3595 if handled {
3596 return;
3597 }
3598 }
3599
3600 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
3601 if move_.tile.window().id() == id {
3602 return;
3603 }
3604 }
3605
3606 for ws in self.workspaces_mut() {
3607 if ws.has_window(id) {
3608 ws.set_fullscreen(id, is_fullscreen);
3609 return;
3610 }
3611 }
3612 }
3613
3614 pub fn toggle_fullscreen(&mut self, id: &W::Id) {
3615 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
3616 if move_.tile.window().id() == id {
3617 return;
3618 }
3619 }
3620
3621 for ws in self.workspaces_mut() {
3622 if ws.has_window(id) {
3623 ws.toggle_fullscreen(id);
3624 return;
3625 }
3626 }
3627 }
3628
3629 pub fn toggle_windowed_fullscreen(&mut self, id: &W::Id) {
3630 let (_, window) = self.windows().find(|(_, win)| win.id() == id).unwrap();
3631 if window.pending_sizing_mode().is_fullscreen() {
3632 // Remove the real fullscreen.
3633 for ws in self.workspaces_mut() {
3634 if ws.has_window(id) {
3635 ws.set_fullscreen(id, false);
3636 break;
3637 }
3638 }
3639 }
3640
3641 // This will switch is_pending_fullscreen() to false right away.
3642 self.with_windows_mut(|window, _| {
3643 if window.id() == id {
3644 window.request_windowed_fullscreen(!window.is_pending_windowed_fullscreen());
3645 }
3646 });
3647 }
3648
3649 pub fn set_maximized(&mut self, id: &W::Id, maximize: bool) {
3650 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
3651 if move_.tile.window().id() == id {
3652 return;
3653 }
3654 }
3655
3656 for ws in self.workspaces_mut() {
3657 if ws.has_window(id) {
3658 ws.set_maximized(id, maximize);
3659 return;
3660 }
3661 }
3662 }
3663
3664 pub fn toggle_maximized(&mut self, id: &W::Id) {
3665 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
3666 if move_.tile.window().id() == id {
3667 return;
3668 }
3669 }
3670
3671 for ws in self.workspaces_mut() {
3672 if ws.has_window(id) {
3673 ws.toggle_maximized(id);
3674 return;
3675 }
3676 }
3677 }
3678
3679 pub fn workspace_switch_gesture_begin(&mut self, output: &Output, is_touchpad: bool) {
3680 let monitors = match &mut self.monitor_set {
3681 MonitorSet::Normal { monitors, .. } => monitors,
3682 MonitorSet::NoOutputs { .. } => unreachable!(),
3683 };
3684
3685 for monitor in monitors {
3686 // Cancel the gesture on other outputs.
3687 if &monitor.output != output {
3688 monitor.workspace_switch_gesture_end(None);
3689 continue;
3690 }
3691
3692 monitor.workspace_switch_gesture_begin(is_touchpad);
3693 }
3694 }
3695
3696 pub fn workspace_switch_gesture_update(
3697 &mut self,
3698 delta_y: f64,
3699 timestamp: Duration,
3700 is_touchpad: bool,
3701 ) -> Option<Option<Output>> {
3702 let monitors = match &mut self.monitor_set {
3703 MonitorSet::Normal { monitors, .. } => monitors,
3704 MonitorSet::NoOutputs { .. } => return None,
3705 };
3706
3707 for monitor in monitors {
3708 if let Some(refresh) =
3709 monitor.workspace_switch_gesture_update(delta_y, timestamp, is_touchpad)
3710 {
3711 if refresh {
3712 return Some(Some(monitor.output.clone()));
3713 } else {
3714 return Some(None);
3715 }
3716 }
3717 }
3718
3719 None
3720 }
3721
3722 pub fn workspace_switch_gesture_end(&mut self, is_touchpad: Option<bool>) -> Option<Output> {
3723 let monitors = match &mut self.monitor_set {
3724 MonitorSet::Normal { monitors, .. } => monitors,
3725 MonitorSet::NoOutputs { .. } => return None,
3726 };
3727
3728 for monitor in monitors {
3729 if monitor.workspace_switch_gesture_end(is_touchpad) {
3730 return Some(monitor.output.clone());
3731 }
3732 }
3733
3734 None
3735 }
3736
3737 pub fn view_offset_gesture_begin(
3738 &mut self,
3739 output: &Output,
3740 workspace_idx: Option<usize>,
3741 is_touchpad: bool,
3742 ) {
3743 let monitors = match &mut self.monitor_set {
3744 MonitorSet::Normal { monitors, .. } => monitors,
3745 MonitorSet::NoOutputs { .. } => unreachable!(),
3746 };
3747
3748 for monitor in monitors {
3749 for (idx, ws) in monitor.workspaces.iter_mut().enumerate() {
3750 // Cancel the gesture on other workspaces.
3751 if &monitor.output != output
3752 || idx != workspace_idx.unwrap_or(monitor.active_workspace_idx)
3753 {
3754 ws.view_offset_gesture_end(None);
3755 continue;
3756 }
3757
3758 ws.view_offset_gesture_begin(is_touchpad);
3759 }
3760 }
3761 }
3762
3763 pub fn view_offset_gesture_update(
3764 &mut self,
3765 delta_x: f64,
3766 timestamp: Duration,
3767 is_touchpad: bool,
3768 ) -> Option<Option<Output>> {
3769 let zoom = self.overview_zoom();
3770 let delta_x = delta_x / zoom;
3771
3772 let monitors = match &mut self.monitor_set {
3773 MonitorSet::Normal { monitors, .. } => monitors,
3774 MonitorSet::NoOutputs { .. } => return None,
3775 };
3776
3777 for monitor in monitors {
3778 for ws in &mut monitor.workspaces {
3779 if let Some(refresh) =
3780 ws.view_offset_gesture_update(delta_x, timestamp, is_touchpad)
3781 {
3782 if refresh {
3783 return Some(Some(monitor.output.clone()));
3784 } else {
3785 return Some(None);
3786 }
3787 }
3788 }
3789 }
3790
3791 None
3792 }
3793
3794 pub fn view_offset_gesture_end(&mut self, is_touchpad: Option<bool>) -> Option<Output> {
3795 let monitors = match &mut self.monitor_set {
3796 MonitorSet::Normal { monitors, .. } => monitors,
3797 MonitorSet::NoOutputs { .. } => return None,
3798 };
3799
3800 for monitor in monitors {
3801 for ws in &mut monitor.workspaces {
3802 if ws.view_offset_gesture_end(is_touchpad) {
3803 return Some(monitor.output.clone());
3804 }
3805 }
3806 }
3807
3808 None
3809 }
3810
3811 pub fn overview_gesture_begin(&mut self) {
3812 self.overview_open = true;
3813
3814 let value = self.overview_progress.take().map_or(0., |p| p.value());
3815 let gesture = OverviewGesture {
3816 tracker: SwipeTracker::new(),
3817 start: value,
3818 value,
3819 };
3820 self.overview_progress = Some(OverviewProgress::Gesture(gesture));
3821
3822 self.set_monitors_overview_state();
3823 }
3824
3825 pub fn overview_gesture_update(&mut self, delta_y: f64, timestamp: Duration) -> Option<bool> {
3826 let Some(OverviewProgress::Gesture(gesture)) = &mut self.overview_progress else {
3827 return None;
3828 };
3829
3830 gesture.tracker.push(delta_y, timestamp);
3831
3832 let total_height = OVERVIEW_GESTURE_MOVEMENT;
3833 let pos = gesture.tracker.pos() / total_height;
3834 let new_value = gesture.start + pos;
3835 let new_value = OVERVIEW_GESTURE_RUBBER_BAND.clamp(0., 1., new_value);
3836
3837 if gesture.value == new_value {
3838 return Some(false);
3839 }
3840
3841 gesture.value = new_value;
3842 self.set_monitors_overview_state();
3843
3844 Some(true)
3845 }
3846
3847 pub fn overview_gesture_end(&mut self) -> bool {
3848 let Some(OverviewProgress::Gesture(gesture)) = &mut self.overview_progress else {
3849 return false;
3850 };
3851
3852 // Take into account any idle time between the last event and now.
3853 let now = self.clock.now_unadjusted();
3854 gesture.tracker.push(0., now);
3855
3856 let total_height = OVERVIEW_GESTURE_MOVEMENT;
3857
3858 let mut velocity = gesture.tracker.velocity() / total_height;
3859 let current_pos = gesture.tracker.pos() / total_height;
3860 let pos = gesture.tracker.projected_end_pos() / total_height;
3861
3862 let new_value = gesture.start + pos;
3863 let new_value = new_value.clamp(0., 1.).round();
3864
3865 velocity *=
3866 OVERVIEW_GESTURE_RUBBER_BAND.clamp_derivative(0., 1., gesture.start + current_pos);
3867
3868 self.overview_open = new_value == 1.;
3869 self.overview_progress = Some(OverviewProgress::Animation(Animation::new(
3870 self.clock.clone(),
3871 gesture.value,
3872 new_value,
3873 velocity,
3874 self.options.animations.overview_open_close.0,
3875 )));
3876
3877 self.set_monitors_overview_state();
3878
3879 true
3880 }
3881
3882 pub fn interactive_move_begin(
3883 &mut self,
3884 window_id: W::Id,
3885 output: &Output,
3886 start_pos_within_output: Point<f64, Logical>,
3887 ) -> bool {
3888 if self.interactive_move.is_some() {
3889 return false;
3890 }
3891
3892 let Some((mon, (ws, ws_geo))) = self.monitors().find_map(|mon| {
3893 mon.workspaces_with_render_geo()
3894 .find(|(ws, _)| ws.has_window(&window_id))
3895 .map(|rv| (mon, rv))
3896 }) else {
3897 return false;
3898 };
3899
3900 if mon.output() != output {
3901 return false;
3902 }
3903
3904 let zoom = mon.overview_zoom();
3905
3906 let is_floating = ws.is_floating(&window_id);
3907 let (tile, tile_offset, _visible) = ws
3908 .tiles_with_render_positions()
3909 .find(|(tile, _, _)| tile.window().id() == &window_id)
3910 .unwrap();
3911 let window_offset = tile.window_loc();
3912
3913 let tile_pos = ws_geo.loc + tile_offset.upscale(zoom);
3914
3915 let pointer_offset_within_window =
3916 start_pos_within_output - tile_pos - window_offset.upscale(zoom);
3917 let window_size = tile.window_size().upscale(zoom);
3918 let pointer_ratio_within_window = (
3919 f64::clamp(pointer_offset_within_window.x / window_size.w, 0., 1.),
3920 f64::clamp(pointer_offset_within_window.y / window_size.h, 0., 1.),
3921 );
3922
3923 self.interactive_move = Some(InteractiveMoveState::Starting {
3924 window_id,
3925 pointer_delta: Point::from((0., 0.)),
3926 pointer_ratio_within_window,
3927 });
3928
3929 for mon in self.monitors_mut() {
3930 mon.dnd_scroll_gesture_begin();
3931 }
3932
3933 // Lock the view for scrolling interactive move.
3934 if !is_floating {
3935 for ws in self.workspaces_mut() {
3936 ws.dnd_scroll_gesture_begin();
3937 }
3938 }
3939
3940 true
3941 }
3942
3943 pub fn interactive_move_update(
3944 &mut self,
3945 window: &W::Id,
3946 delta: Point<f64, Logical>,
3947 output: Output,
3948 pointer_pos_within_output: Point<f64, Logical>,
3949 ) -> bool {
3950 let Some(state) = self.interactive_move.take() else {
3951 return false;
3952 };
3953
3954 match state {
3955 InteractiveMoveState::Starting {
3956 window_id,
3957 mut pointer_delta,
3958 pointer_ratio_within_window,
3959 } => {
3960 if window_id != *window {
3961 self.interactive_move = Some(InteractiveMoveState::Starting {
3962 window_id,
3963 pointer_delta,
3964 pointer_ratio_within_window,
3965 });
3966 return false;
3967 }
3968
3969 let zoom = self.overview_zoom();
3970 let delta = delta.downscale(zoom);
3971
3972 pointer_delta += delta;
3973
3974 let (cx, cy) = (pointer_delta.x, pointer_delta.y);
3975 let sq_dist = cx * cx + cy * cy;
3976
3977 let factor = RubberBand {
3978 stiffness: 1.0,
3979 limit: 0.5,
3980 }
3981 .band(sq_dist / INTERACTIVE_MOVE_START_THRESHOLD);
3982
3983 let (is_floating, tile, workspace_config) = self
3984 .workspaces_mut()
3985 .find(|ws| ws.has_window(&window_id))
3986 .map(|ws| {
3987 let workspace_config = ws.layout_config().cloned().map(|c| (ws.id(), c));
3988 (
3989 ws.is_floating(&window_id),
3990 ws.tiles_mut()
3991 .find(|tile| *tile.window().id() == window_id)
3992 .unwrap(),
3993 workspace_config,
3994 )
3995 })
3996 .unwrap();
3997 tile.interactive_move_offset = pointer_delta.upscale(factor);
3998
3999 // Put it back to be able to easily return.
4000 self.interactive_move = Some(InteractiveMoveState::Starting {
4001 window_id: window_id.clone(),
4002 pointer_delta,
4003 pointer_ratio_within_window,
4004 });
4005
4006 if !is_floating && sq_dist < INTERACTIVE_MOVE_START_THRESHOLD {
4007 return true;
4008 }
4009
4010 let output_config = self
4011 .monitors()
4012 .find(|mon| mon.output() == &output)
4013 .and_then(|mon| mon.layout_config().cloned());
4014
4015 // If the pointer is currently on the window's own output, then we can animate the
4016 // window movement from its current (rubberbanded and possibly moved away) position
4017 // to the pointer. Otherwise, we just teleport it as the layout code is not aware
4018 // of monitor positions.
4019 //
4020 // FIXME: when and if the layout code knows about monitor positions, this will be
4021 // potentially animatable.
4022 let mut tile_pos = None;
4023 if let Some((mon, (ws, ws_geo))) = self.monitors().find_map(|mon| {
4024 mon.workspaces_with_render_geo()
4025 .find(|(ws, _)| ws.has_window(window))
4026 .map(|rv| (mon, rv))
4027 }) {
4028 if mon.output() == &output {
4029 let (_, tile_offset, _) = ws
4030 .tiles_with_render_positions()
4031 .find(|(tile, _, _)| tile.window().id() == window)
4032 .unwrap();
4033
4034 let zoom = mon.overview_zoom();
4035 tile_pos = Some((ws_geo.loc + tile_offset.upscale(zoom), zoom));
4036 }
4037 }
4038
4039 // Clear it before calling remove_window() to avoid running interactive_move_end()
4040 // in the middle of interactive_move_update() and the confusion that causes.
4041 self.interactive_move = None;
4042
4043 // Unset fullscreen before removing the tile. This will restore its size properly,
4044 // and move it to floating if needed, so we don't have to deal with that here.
4045 let ws = self
4046 .workspaces_mut()
4047 .find(|ws| ws.has_window(&window_id))
4048 .unwrap();
4049 ws.set_fullscreen(window, false);
4050 ws.set_maximized(window, false);
4051
4052 let RemovedTile {
4053 mut tile,
4054 width,
4055 is_full_width,
4056 is_floating,
4057 } = self.remove_window(window, Transaction::new()).unwrap();
4058
4059 tile.stop_move_animations();
4060 tile.interactive_move_offset = Point::from((0., 0.));
4061 tile.window().output_enter(&output);
4062 tile.window().set_preferred_scale_transform(
4063 output.current_scale(),
4064 output.current_transform(),
4065 );
4066
4067 let view_size = output_size(&output);
4068 let scale = output.current_scale().fractional_scale();
4069 let options = Options::clone(&self.options)
4070 .with_merged_layout(output_config.as_ref())
4071 .with_merged_layout(workspace_config.as_ref().map(|(_, c)| c))
4072 .adjusted_for_scale(scale);
4073 tile.update_config(view_size, scale, Rc::new(options));
4074
4075 if is_floating {
4076 // Unlock the view in case we locked it moving a fullscreen window that is
4077 // going to unfullscreen to floating.
4078 for ws in self.workspaces_mut() {
4079 ws.dnd_scroll_gesture_end();
4080 }
4081 } else {
4082 // Animate to semitransparent.
4083 tile.animate_alpha(
4084 1.,
4085 INTERACTIVE_MOVE_ALPHA,
4086 self.options.animations.window_movement.0,
4087 );
4088 tile.hold_alpha_animation_after_done();
4089 }
4090
4091 let mut data = InteractiveMoveData {
4092 tile,
4093 output,
4094 pointer_pos_within_output,
4095 width,
4096 is_full_width,
4097 is_floating,
4098 pointer_ratio_within_window,
4099 output_config,
4100 workspace_config,
4101 };
4102
4103 if let Some((tile_pos, zoom)) = tile_pos {
4104 let new_tile_pos = data.tile_render_location(zoom);
4105 data.tile
4106 .animate_move_from((tile_pos - new_tile_pos).downscale(zoom));
4107 }
4108
4109 self.interactive_move = Some(InteractiveMoveState::Moving(data));
4110 }
4111 InteractiveMoveState::Moving(mut move_) => {
4112 if window != move_.tile.window().id() {
4113 self.interactive_move = Some(InteractiveMoveState::Moving(move_));
4114 return false;
4115 }
4116
4117 let mut ws_id = None;
4118 if let Some(mon) = self.monitor_for_output(&output) {
4119 let (insert_ws, _) = mon.insert_position(move_.pointer_pos_within_output);
4120 if let InsertWorkspace::Existing(id) = insert_ws {
4121 ws_id = Some(id);
4122 }
4123 }
4124
4125 // If moved over a different workspace, reset the config override.
4126 let mut update_config = false;
4127 if let Some((id, _)) = &move_.workspace_config {
4128 if Some(*id) != ws_id {
4129 move_.workspace_config = None;
4130 update_config = true;
4131 }
4132 }
4133
4134 if output != move_.output {
4135 move_.tile.window().output_leave(&move_.output);
4136 move_.tile.window().output_enter(&output);
4137 move_.tile.window().set_preferred_scale_transform(
4138 output.current_scale(),
4139 output.current_transform(),
4140 );
4141 move_.output = output.clone();
4142 self.focus_output(&output);
4143
4144 move_.output_config = self
4145 .monitor_for_output(&output)
4146 .and_then(|mon| mon.layout_config().cloned());
4147
4148 update_config = true;
4149 }
4150
4151 if update_config {
4152 let view_size = output_size(&output);
4153 let scale = output.current_scale().fractional_scale();
4154 let options = Options::clone(&self.options)
4155 .with_merged_layout(move_.output_config.as_ref())
4156 .with_merged_layout(move_.workspace_config.as_ref().map(|(_, c)| c))
4157 .adjusted_for_scale(scale);
4158 move_.tile.update_config(view_size, scale, Rc::new(options));
4159 }
4160
4161 move_.pointer_pos_within_output = pointer_pos_within_output;
4162
4163 self.interactive_move = Some(InteractiveMoveState::Moving(move_));
4164 }
4165 }
4166
4167 true
4168 }
4169
4170 pub fn interactive_move_end(&mut self, window: &W::Id) {
4171 let Some(move_) = &self.interactive_move else {
4172 return;
4173 };
4174
4175 let move_ = match move_ {
4176 InteractiveMoveState::Starting { window_id, .. } => {
4177 if window_id != window {
4178 return;
4179 }
4180
4181 let Some(InteractiveMoveState::Starting { window_id, .. }) =
4182 self.interactive_move.take()
4183 else {
4184 unreachable!()
4185 };
4186
4187 for mon in self.monitors_mut() {
4188 mon.dnd_scroll_gesture_end();
4189 }
4190
4191 for ws in self.workspaces_mut() {
4192 if let Some(tile) = ws.tiles_mut().find(|tile| *tile.window().id() == window_id)
4193 {
4194 let offset = tile.interactive_move_offset;
4195 tile.interactive_move_offset = Point::from((0., 0.));
4196 tile.animate_move_from(offset);
4197 }
4198
4199 // Unlock the view on the workspaces, but if the moved window was active,
4200 // preserve that.
4201 let moved_tile_was_active =
4202 ws.active_window().is_some_and(|win| *win.id() == window_id);
4203
4204 ws.dnd_scroll_gesture_end();
4205
4206 if moved_tile_was_active {
4207 ws.activate_window(&window_id);
4208 }
4209 }
4210
4211 return;
4212 }
4213 InteractiveMoveState::Moving(move_) => move_,
4214 };
4215
4216 if window != move_.tile.window().id() {
4217 return;
4218 }
4219
4220 let Some(InteractiveMoveState::Moving(mut move_)) = self.interactive_move.take() else {
4221 unreachable!()
4222 };
4223
4224 for mon in self.monitors_mut() {
4225 mon.dnd_scroll_gesture_end();
4226 }
4227
4228 // Unlock the view on the workspaces.
4229 if !move_.is_floating {
4230 for ws in self.workspaces_mut() {
4231 ws.dnd_scroll_gesture_end();
4232 }
4233
4234 // Also animate the tile back to opaque.
4235 move_.tile.animate_alpha(
4236 INTERACTIVE_MOVE_ALPHA,
4237 1.,
4238 self.options.animations.window_movement.0,
4239 );
4240 }
4241
4242 // Dragging in the overview shouldn't switch the workspace and so on.
4243 let allow_to_activate_workspace = !self.overview_open;
4244
4245 match &mut self.monitor_set {
4246 MonitorSet::Normal {
4247 monitors,
4248 active_monitor_idx,
4249 ..
4250 } => {
4251 let (mon, insert_ws, position, offset, zoom) =
4252 if let Some(mon) = monitors.iter_mut().find(|mon| mon.output == move_.output) {
4253 let zoom = mon.overview_zoom();
4254
4255 let (insert_ws, geo) = mon.insert_position(move_.pointer_pos_within_output);
4256 let (position, offset) = match insert_ws {
4257 InsertWorkspace::Existing(ws_id) => {
4258 let ws_idx = mon.idx_of_ws(ws_id).unwrap();
4259
4260 let position = if move_.is_floating {
4261 InsertPosition::Floating
4262 } else {
4263 let pos_within_workspace =
4264 (move_.pointer_pos_within_output - geo.loc).downscale(zoom);
4265 let ws = &mut mon.workspaces[ws_idx];
4266 ws.scrolling_insert_position(pos_within_workspace)
4267 };
4268
4269 (position, Some(geo.loc))
4270 }
4271 InsertWorkspace::NewAt(_) => {
4272 let position = if move_.is_floating {
4273 InsertPosition::Floating
4274 } else {
4275 InsertPosition::NewColumn(0)
4276 };
4277
4278 (position, None)
4279 }
4280 };
4281
4282 (mon, insert_ws, position, offset, zoom)
4283 } else {
4284 let mon = &mut monitors[*active_monitor_idx];
4285 let zoom = mon.overview_zoom();
4286 // No point in trying to use the pointer position on the wrong output.
4287 let ws = &mon.workspaces[0];
4288 let ws_geo = mon.workspaces_render_geo().next().unwrap();
4289
4290 let position = if move_.is_floating {
4291 InsertPosition::Floating
4292 } else {
4293 ws.scrolling_insert_position(Point::from((0., 0.)))
4294 };
4295
4296 let insert_ws = InsertWorkspace::Existing(ws.id());
4297 (mon, insert_ws, position, Some(ws_geo.loc), zoom)
4298 };
4299
4300 let win_id = move_.tile.window().id().clone();
4301 let tile_render_loc = move_.tile_render_location(zoom);
4302
4303 let ws_idx = match insert_ws {
4304 InsertWorkspace::Existing(ws_id) => mon.idx_of_ws(ws_id).unwrap(),
4305 InsertWorkspace::NewAt(ws_idx) => {
4306 if mon.options.layout.empty_workspace_above_first && ws_idx == 0 {
4307 // Reuse the top empty workspace.
4308 0
4309 } else if mon.workspaces.len() - 1 <= ws_idx {
4310 // Reuse the bottom empty workspace.
4311 mon.workspaces.len() - 1
4312 } else {
4313 mon.add_workspace_at(ws_idx);
4314 ws_idx
4315 }
4316 }
4317 };
4318
4319 match position {
4320 InsertPosition::NewColumn(column_idx) => {
4321 let ws_id = mon.workspaces[ws_idx].id();
4322 mon.add_tile(
4323 move_.tile,
4324 MonitorAddWindowTarget::Workspace {
4325 id: ws_id,
4326 column_idx: Some(column_idx),
4327 },
4328 ActivateWindow::Yes,
4329 allow_to_activate_workspace,
4330 move_.width,
4331 move_.is_full_width,
4332 false,
4333 None,
4334 );
4335 }
4336 InsertPosition::InColumn(column_idx, tile_idx) => {
4337 mon.add_tile_to_column(
4338 ws_idx,
4339 column_idx,
4340 Some(tile_idx),
4341 move_.tile,
4342 true,
4343 allow_to_activate_workspace,
4344 );
4345 }
4346 InsertPosition::Floating => {
4347 let mut tile = move_.tile;
4348 tile.floating_pos = None;
4349
4350 match insert_ws {
4351 InsertWorkspace::Existing(_) => {
4352 if let Some(offset) = offset {
4353 let pos = (tile_render_loc - offset).downscale(zoom);
4354 let pos =
4355 mon.workspaces[ws_idx].floating_logical_to_size_frac(pos);
4356 tile.floating_pos = Some(pos);
4357 } else {
4358 error!(
4359 "offset unset for inserting a floating tile \
4360 to existing workspace"
4361 );
4362 }
4363 }
4364 InsertWorkspace::NewAt(_) => {
4365 // When putting a floating tile on a new workspace, we don't really
4366 // have a good pre-existing position.
4367 }
4368 }
4369
4370 // Set the floating size so it takes into account any window resizing that
4371 // took place during the move.
4372 if let Some(size) = tile.window().expected_size() {
4373 tile.floating_window_size = Some(size);
4374 }
4375
4376 let ws_id = mon.workspaces[ws_idx].id();
4377 mon.add_tile(
4378 tile,
4379 MonitorAddWindowTarget::Workspace {
4380 id: ws_id,
4381 column_idx: None,
4382 },
4383 ActivateWindow::Yes,
4384 allow_to_activate_workspace,
4385 move_.width,
4386 move_.is_full_width,
4387 true,
4388 None,
4389 );
4390 }
4391 }
4392
4393 // needed because empty_workspace_above_first could have modified the idx
4394 let (tile, tile_offset, ws_geo) = mon
4395 .workspaces_with_render_geo_mut(false)
4396 .find_map(|(ws, geo)| {
4397 ws.tiles_with_render_positions_mut(false)
4398 .find(|(tile, _)| tile.window().id() == &win_id)
4399 .map(|(tile, tile_offset)| (tile, tile_offset, geo))
4400 })
4401 .unwrap();
4402 let new_tile_render_loc = ws_geo.loc + tile_offset.upscale(zoom);
4403
4404 tile.animate_move_from((tile_render_loc - new_tile_render_loc).downscale(zoom));
4405
4406 // Interactive move into floating barely animates (it doesn't really move after
4407 // being dropped), so setting it as moving between workspaces would just cause it to
4408 // awkwardly sit unclipped for a moment before the animation runs out.
4409 if !matches!(position, InsertPosition::Floating) {
4410 tile.set_anim_y_between_workspaces();
4411 }
4412 }
4413 MonitorSet::NoOutputs { workspaces, .. } => {
4414 if workspaces.is_empty() {
4415 workspaces.push(Workspace::new_no_outputs(
4416 self.clock.clone(),
4417 self.options.clone(),
4418 ));
4419 }
4420 let ws = &mut workspaces[0];
4421
4422 // No point in trying to use the pointer position without outputs.
4423 ws.add_tile(
4424 move_.tile,
4425 WorkspaceAddWindowTarget::Auto,
4426 ActivateWindow::Yes,
4427 move_.width,
4428 move_.is_full_width,
4429 move_.is_floating,
4430 None,
4431 );
4432 }
4433 }
4434 }
4435
4436 pub fn interactive_move_is_moving_above_output(&self, output: &Output) -> bool {
4437 let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move else {
4438 return false;
4439 };
4440
4441 move_.output == *output
4442 }
4443
4444 pub fn dnd_update(&mut self, output: Output, pointer_pos_within_output: Point<f64, Logical>) {
4445 let begin_gesture = self.dnd.is_none();
4446
4447 self.dnd = Some(DndData {
4448 output,
4449 pointer_pos_within_output,
4450 hold: None,
4451 });
4452
4453 if begin_gesture {
4454 for mon in self.monitors_mut() {
4455 mon.dnd_scroll_gesture_begin();
4456 }
4457
4458 for ws in self.workspaces_mut() {
4459 ws.dnd_scroll_gesture_begin();
4460 }
4461 }
4462 }
4463
4464 pub fn dnd_end(&mut self) {
4465 if self.dnd.is_none() {
4466 return;
4467 }
4468
4469 self.dnd = None;
4470
4471 for mon in self.monitors_mut() {
4472 mon.dnd_scroll_gesture_end();
4473 }
4474
4475 for ws in self.workspaces_mut() {
4476 ws.dnd_scroll_gesture_end();
4477 }
4478 }
4479
4480 pub fn interactive_resize_begin(&mut self, window: W::Id, edges: ResizeEdge) -> bool {
4481 match &mut self.monitor_set {
4482 MonitorSet::Normal { monitors, .. } => {
4483 for mon in monitors {
4484 for ws in &mut mon.workspaces {
4485 if ws.has_window(&window) {
4486 return ws.interactive_resize_begin(window, edges);
4487 }
4488 }
4489 }
4490 }
4491 MonitorSet::NoOutputs { workspaces, .. } => {
4492 for ws in workspaces {
4493 if ws.has_window(&window) {
4494 return ws.interactive_resize_begin(window, edges);
4495 }
4496 }
4497 }
4498 }
4499
4500 false
4501 }
4502
4503 pub fn interactive_resize_update(
4504 &mut self,
4505 window: &W::Id,
4506 delta: Point<f64, Logical>,
4507 ) -> bool {
4508 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
4509 if move_.tile.window().id() == window {
4510 return false;
4511 }
4512 }
4513
4514 match &mut self.monitor_set {
4515 MonitorSet::Normal { monitors, .. } => {
4516 for mon in monitors {
4517 for ws in &mut mon.workspaces {
4518 if ws.has_window(window) {
4519 return ws.interactive_resize_update(window, delta);
4520 }
4521 }
4522 }
4523 }
4524 MonitorSet::NoOutputs { workspaces, .. } => {
4525 for ws in workspaces {
4526 if ws.has_window(window) {
4527 return ws.interactive_resize_update(window, delta);
4528 }
4529 }
4530 }
4531 }
4532
4533 false
4534 }
4535
4536 pub fn interactive_resize_end(&mut self, window: &W::Id) {
4537 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
4538 if move_.tile.window().id() == window {
4539 return;
4540 }
4541 }
4542
4543 match &mut self.monitor_set {
4544 MonitorSet::Normal { monitors, .. } => {
4545 for mon in monitors {
4546 for ws in &mut mon.workspaces {
4547 if ws.has_window(window) {
4548 ws.interactive_resize_end(Some(window));
4549 return;
4550 }
4551 }
4552 }
4553 }
4554 MonitorSet::NoOutputs { workspaces, .. } => {
4555 for ws in workspaces {
4556 if ws.has_window(window) {
4557 ws.interactive_resize_end(Some(window));
4558 return;
4559 }
4560 }
4561 }
4562 }
4563 }
4564
4565 pub fn move_workspace_down(&mut self) {
4566 let Some(monitor) = self.active_monitor() else {
4567 return;
4568 };
4569 monitor.move_workspace_down();
4570 }
4571
4572 pub fn move_workspace_up(&mut self) {
4573 let Some(monitor) = self.active_monitor() else {
4574 return;
4575 };
4576 monitor.move_workspace_up();
4577 }
4578
4579 pub fn move_workspace_to_idx(
4580 &mut self,
4581 reference: Option<(Option<Output>, usize)>,
4582 new_idx: usize,
4583 ) {
4584 let (monitor, old_idx) = if let Some((output, old_idx)) = reference {
4585 let monitor = if let Some(output) = output {
4586 let Some(monitor) = self.monitor_for_output_mut(&output) else {
4587 return;
4588 };
4589 monitor
4590 } else {
4591 // In case a numbered workspace reference is used, assume the active monitor
4592 let Some(monitor) = self.active_monitor() else {
4593 return;
4594 };
4595 monitor
4596 };
4597
4598 (monitor, old_idx)
4599 } else {
4600 let Some(monitor) = self.active_monitor() else {
4601 return;
4602 };
4603 let index = monitor.active_workspace_idx;
4604 (monitor, index)
4605 };
4606
4607 monitor.move_workspace_to_idx(old_idx, new_idx);
4608 }
4609
4610 pub fn set_workspace_name(&mut self, name: String, reference: Option<WorkspaceReference>) {
4611 // ignore the request if the name is already used by another workspace
4612 if self.find_workspace_by_name(&name).is_some() {
4613 return;
4614 }
4615
4616 let ws = if let Some(reference) = reference {
4617 self.find_workspace_by_ref(reference)
4618 } else {
4619 self.active_workspace_mut()
4620 };
4621 let Some(ws) = ws else {
4622 return;
4623 };
4624
4625 ws.name.replace(name);
4626
4627 let wsid = ws.id();
4628
4629 // if `empty_workspace_above_first` is set and `ws` is the first
4630 // workspace on a monitor, another empty workspace needs to
4631 // be added before.
4632 // Conversely, if `ws` was the last workspace on a monitor, an
4633 // empty workspace needs to be added after.
4634
4635 if let MonitorSet::Normal {
4636 monitors,
4637 active_monitor_idx,
4638 ..
4639 } = &mut self.monitor_set
4640 {
4641 let monitor = &mut monitors[*active_monitor_idx];
4642 if monitor.options.layout.empty_workspace_above_first
4643 && monitor
4644 .workspaces
4645 .first()
4646 .is_some_and(|first| first.id() == wsid)
4647 {
4648 monitor.add_workspace_top();
4649 }
4650 if monitor
4651 .workspaces
4652 .last()
4653 .is_some_and(|last| last.id() == wsid)
4654 {
4655 monitor.add_workspace_bottom();
4656 }
4657 }
4658 }
4659
4660 pub fn unset_workspace_name(&mut self, reference: Option<WorkspaceReference>) {
4661 let ws = if let Some(reference) = reference {
4662 self.find_workspace_by_ref(reference)
4663 } else {
4664 self.active_workspace_mut()
4665 };
4666 let Some(ws) = ws else {
4667 return;
4668 };
4669 let id = ws.id();
4670
4671 self.unname_workspace_by_id(id);
4672 }
4673
4674 pub fn set_monitors_overview_state(&mut self) {
4675 let MonitorSet::Normal { monitors, .. } = &mut self.monitor_set else {
4676 return;
4677 };
4678
4679 for mon in monitors {
4680 mon.overview_open = self.overview_open;
4681 mon.set_overview_progress(self.overview_progress.as_ref());
4682 }
4683 }
4684
4685 pub fn toggle_overview(&mut self) {
4686 self.overview_open = !self.overview_open;
4687
4688 let from = self.overview_progress.take().map_or(0., |p| p.value());
4689 let to = if self.overview_open { 1. } else { 0. };
4690
4691 self.overview_progress = Some(OverviewProgress::Animation(Animation::new(
4692 self.clock.clone(),
4693 from,
4694 to,
4695 0.,
4696 self.options.animations.overview_open_close.0,
4697 )));
4698
4699 self.set_monitors_overview_state();
4700 }
4701
4702 pub fn open_overview(&mut self) -> bool {
4703 if self.overview_open {
4704 return false;
4705 }
4706
4707 self.toggle_overview();
4708 true
4709 }
4710
4711 pub fn close_overview(&mut self) -> bool {
4712 if !self.overview_open {
4713 return false;
4714 }
4715
4716 self.toggle_overview();
4717 true
4718 }
4719
4720 pub fn toggle_overview_to_workspace(&mut self, ws_idx: usize) {
4721 let config = self.options.animations.overview_open_close.0;
4722 if let Some(mon) = self.active_monitor() {
4723 mon.activate_workspace_with_anim_config(ws_idx, Some(config));
4724 }
4725 self.toggle_overview();
4726 }
4727
4728 pub fn start_open_animation_for_window(&mut self, window: &W::Id) {
4729 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
4730 if move_.tile.window().id() == window {
4731 return;
4732 }
4733 }
4734
4735 for ws in self.workspaces_mut() {
4736 if ws.start_open_animation(window) {
4737 return;
4738 }
4739 }
4740 }
4741
4742 pub fn store_unmap_snapshot(
4743 &mut self,
4744 renderer: &mut GlesRenderer,
4745 xray: Option<&mut Xray>,
4746 xray_has_blocked_out_layers: bool,
4747 window: &W::Id,
4748 ) {
4749 let _span = tracy_client::span!("Layout::store_unmap_snapshot");
4750
4751 let zoom = self.overview_zoom();
4752
4753 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
4754 if move_.tile.window().id() == window {
4755 let pos_within_output = move_.tile_render_location(zoom);
4756
4757 // Computation matches update_render_elements().
4758 let view_rect =
4759 Rectangle::new(pos_within_output.upscale(-1.), output_size(&move_.output))
4760 .downscale(zoom);
4761 move_.tile.update_render_elements(false, view_rect);
4762
4763 move_.tile.store_unmap_snapshot_if_empty(
4764 renderer,
4765 xray,
4766 xray_has_blocked_out_layers,
4767 XrayPos::new(pos_within_output, zoom),
4768 );
4769 return;
4770 }
4771 }
4772
4773 match &mut self.monitor_set {
4774 MonitorSet::Normal { monitors, .. } => {
4775 for mon in monitors {
4776 for (ws, geo) in mon.workspaces_with_render_geo_mut(false) {
4777 if ws.has_window(window) {
4778 ws.store_unmap_snapshot_if_empty(
4779 renderer,
4780 xray,
4781 xray_has_blocked_out_layers,
4782 XrayPos::new(geo.loc, zoom),
4783 window,
4784 );
4785 return;
4786 }
4787 }
4788 }
4789 }
4790 MonitorSet::NoOutputs { workspaces, .. } => {
4791 for ws in workspaces {
4792 if ws.has_window(window) {
4793 ws.store_unmap_snapshot_if_empty(
4794 renderer,
4795 xray,
4796 xray_has_blocked_out_layers,
4797 XrayPos::default(),
4798 window,
4799 );
4800 return;
4801 }
4802 }
4803 }
4804 }
4805 }
4806
4807 pub fn clear_unmap_snapshot(&mut self, window: &W::Id) {
4808 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
4809 if move_.tile.window().id() == window {
4810 let _ = move_.tile.take_unmap_snapshot();
4811 return;
4812 }
4813 }
4814
4815 match &mut self.monitor_set {
4816 MonitorSet::Normal { monitors, .. } => {
4817 for mon in monitors {
4818 for ws in &mut mon.workspaces {
4819 if ws.has_window(window) {
4820 ws.clear_unmap_snapshot(window);
4821 return;
4822 }
4823 }
4824 }
4825 }
4826 MonitorSet::NoOutputs { workspaces, .. } => {
4827 for ws in workspaces {
4828 if ws.has_window(window) {
4829 ws.clear_unmap_snapshot(window);
4830 return;
4831 }
4832 }
4833 }
4834 }
4835 }
4836
4837 pub fn start_close_animation_for_window(
4838 &mut self,
4839 renderer: &mut GlesRenderer,
4840 window: &W::Id,
4841 blocker: TransactionBlocker,
4842 ) {
4843 let _span = tracy_client::span!("Layout::start_close_animation_for_window");
4844
4845 let zoom = self.overview_zoom();
4846
4847 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
4848 if move_.tile.window().id() == window {
4849 let Some(snapshot) = move_.tile.take_unmap_snapshot() else {
4850 return;
4851 };
4852 let tile_pos = move_.tile_render_location(zoom);
4853 let tile_size = move_.tile.tile_size();
4854
4855 let output = move_.output.clone();
4856 let pointer_pos_within_output = move_.pointer_pos_within_output;
4857 let Some(mon) = self.monitor_for_output_mut(&output) else {
4858 return;
4859 };
4860 let Some((ws, ws_geo)) = mon.workspace_under(pointer_pos_within_output) else {
4861 return;
4862 };
4863 let idx = mon.idx_of_ws(ws.id()).unwrap();
4864 let ws = &mut mon.workspaces[idx];
4865
4866 let tile_pos = tile_pos - ws_geo.loc;
4867 ws.start_close_animation_for_tile(renderer, snapshot, tile_size, tile_pos, blocker);
4868 return;
4869 }
4870 }
4871
4872 match &mut self.monitor_set {
4873 MonitorSet::Normal { monitors, .. } => {
4874 for mon in monitors {
4875 for ws in &mut mon.workspaces {
4876 if ws.has_window(window) {
4877 ws.start_close_animation_for_window(renderer, window, blocker);
4878 return;
4879 }
4880 }
4881 }
4882 }
4883 MonitorSet::NoOutputs { workspaces, .. } => {
4884 for ws in workspaces {
4885 if ws.has_window(window) {
4886 ws.start_close_animation_for_window(renderer, window, blocker);
4887 return;
4888 }
4889 }
4890 }
4891 }
4892 }
4893
4894 pub fn render_interactive_move_for_output<R: NiriRenderer>(
4895 &self,
4896 ctx: RenderCtx<R>,
4897 output: &Output,
4898 push: &mut dyn FnMut(RescaleRenderElement<TileRenderElement<R>>),
4899 ) {
4900 if self.update_render_elements_time != self.clock.now() {
4901 error!("clock moved between updating render elements and rendering");
4902 }
4903
4904 let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move else {
4905 return;
4906 };
4907
4908 if &move_.output != output {
4909 return;
4910 }
4911
4912 let scale = Scale::from(move_.output.current_scale().fractional_scale());
4913 let zoom = self.overview_zoom();
4914 let pos_in_backdrop = move_.tile_render_location(zoom);
4915 let xray_pos = XrayPos::new(pos_in_backdrop, zoom);
4916
4917 move_
4918 .tile
4919 .render(ctx, pos_in_backdrop, xray_pos, true, &mut |elem| {
4920 push(RescaleRenderElement::from_element(
4921 elem,
4922 pos_in_backdrop.to_physical_precise_round(scale),
4923 zoom,
4924 ));
4925 });
4926 }
4927
4928 pub fn refresh(&mut self, is_active: bool) {
4929 let _span = tracy_client::span!("Layout::refresh");
4930
4931 self.is_active = is_active;
4932
4933 let mut ongoing_scrolling_dnd = self.dnd.is_some().then_some(true);
4934
4935 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
4936 let win = move_.tile.window_mut();
4937
4938 win.set_active_in_column(true);
4939 win.set_floating(move_.is_floating);
4940 win.set_activated(true);
4941
4942 win.set_interactive_resize(None);
4943
4944 win.set_bounds(output_size(&move_.output).to_i32_round());
4945
4946 win.send_pending_configure();
4947 win.refresh();
4948
4949 ongoing_scrolling_dnd.get_or_insert(!move_.is_floating);
4950 } else if let Some(InteractiveMoveState::Starting { window_id, .. }) =
4951 &self.interactive_move
4952 {
4953 ongoing_scrolling_dnd.get_or_insert_with(|| {
4954 let (_, _, ws) = self
4955 .workspaces()
4956 .find(|(_, _, ws)| ws.has_window(window_id))
4957 .unwrap();
4958 !ws.is_floating(window_id)
4959 });
4960 }
4961
4962 match &mut self.monitor_set {
4963 MonitorSet::Normal {
4964 monitors,
4965 active_monitor_idx,
4966 ..
4967 } => {
4968 for (idx, mon) in monitors.iter_mut().enumerate() {
4969 let is_active = self.is_active
4970 && idx == *active_monitor_idx
4971 && !matches!(self.interactive_move, Some(InteractiveMoveState::Moving(_)));
4972
4973 if ongoing_scrolling_dnd.is_some() && self.overview_open {
4974 // Begin the scroll on new monitors and when opening the overview.
4975 mon.dnd_scroll_gesture_begin();
4976 } else if !self.overview_open {
4977 mon.dnd_scroll_gesture_end();
4978 }
4979
4980 for (ws_idx, ws) in mon.workspaces.iter_mut().enumerate() {
4981 let is_focused = is_active && ws_idx == mon.active_workspace_idx;
4982 ws.refresh(is_active, is_focused);
4983
4984 if let Some(is_scrolling) = ongoing_scrolling_dnd {
4985 // Lock or unlock the view for scrolling interactive move.
4986 if is_scrolling {
4987 ws.dnd_scroll_gesture_begin();
4988 } else {
4989 ws.dnd_scroll_gesture_end();
4990 }
4991 } else {
4992 // Cancel the view offset gesture after workspace switches, moves, etc.
4993 if !self.overview_open && ws_idx != mon.active_workspace_idx {
4994 ws.view_offset_gesture_end(None);
4995 }
4996 }
4997 }
4998 }
4999 }
5000 MonitorSet::NoOutputs { workspaces, .. } => {
5001 for ws in workspaces {
5002 ws.refresh(false, false);
5003 ws.view_offset_gesture_end(None);
5004 }
5005 }
5006 }
5007 }
5008
5009 pub fn workspaces(
5010 &self,
5011 ) -> impl Iterator<Item = (Option<&Monitor<W>>, usize, &Workspace<W>)> + '_ {
5012 let (iter_normal, iter_no_outputs) = match &self.monitor_set {
5013 MonitorSet::Normal { monitors, .. } => {
5014 let it = monitors.iter().flat_map(|mon| {
5015 mon.workspaces
5016 .iter()
5017 .enumerate()
5018 .map(move |(idx, ws)| (Some(mon), idx, ws))
5019 });
5020
5021 (Some(it), None)
5022 }
5023 MonitorSet::NoOutputs { workspaces } => {
5024 let it = workspaces
5025 .iter()
5026 .enumerate()
5027 .map(|(idx, ws)| (None, idx, ws));
5028
5029 (None, Some(it))
5030 }
5031 };
5032
5033 let iter_normal = iter_normal.into_iter().flatten();
5034 let iter_no_outputs = iter_no_outputs.into_iter().flatten();
5035 iter_normal.chain(iter_no_outputs)
5036 }
5037
5038 pub fn workspaces_mut(&mut self) -> impl Iterator<Item = &mut Workspace<W>> + '_ {
5039 let (iter_normal, iter_no_outputs) = match &mut self.monitor_set {
5040 MonitorSet::Normal { monitors, .. } => {
5041 let it = monitors
5042 .iter_mut()
5043 .flat_map(|mon| mon.workspaces.iter_mut());
5044
5045 (Some(it), None)
5046 }
5047 MonitorSet::NoOutputs { workspaces } => {
5048 let it = workspaces.iter_mut();
5049
5050 (None, Some(it))
5051 }
5052 };
5053
5054 let iter_normal = iter_normal.into_iter().flatten();
5055 let iter_no_outputs = iter_no_outputs.into_iter().flatten();
5056 iter_normal.chain(iter_no_outputs)
5057 }
5058
5059 pub fn windows(&self) -> impl Iterator<Item = (Option<&Monitor<W>>, &W)> {
5060 let moving_window = self
5061 .interactive_move
5062 .as_ref()
5063 .and_then(|x| x.moving())
5064 .map(|move_| (self.monitor_for_output(&move_.output), move_.tile.window()))
5065 .into_iter();
5066
5067 let rest = self
5068 .workspaces()
5069 .flat_map(|(mon, _, ws)| ws.windows().map(move |win| (mon, win)));
5070
5071 moving_window.chain(rest)
5072 }
5073
5074 pub fn has_window(&self, window: &W::Id) -> bool {
5075 self.windows().any(|(_, win)| win.id() == window)
5076 }
5077
5078 pub fn is_overview_open(&self) -> bool {
5079 self.overview_open
5080 }
5081}
5082
5083impl<W: LayoutElement> Default for MonitorSet<W> {
5084 fn default() -> Self {
5085 Self::NoOutputs { workspaces: vec![] }
5086 }
5087}
5088
5089fn compute_overview_zoom(options: &Options, overview_progress: Option<f64>) -> f64 {
5090 // Clamp to some sane values.
5091 let zoom = options.overview.zoom.clamp(0.0001, 0.75);
5092
5093 if let Some(p) = overview_progress {
5094 (1. - p * (1. - zoom)).max(0.0001)
5095 } else {
5096 1.
5097 }
5098}