forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBb0eb8adIvan Molodetskikh3 months ago2857 commits

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