forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

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