forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB7b3bef1Suyashtnt2 years ago1225 commits

mod.rs4307 lines, 142.5 KiBHistoryRawDownload
1//! Window layout logic.
2//!
3//! Niri implements scrollable tiling with workspaces. There's one primary output, and potentially
4//! multiple other outputs.
5//!
6//! Our layout has the following invariants:
7//!
8//! 1. Disconnecting and reconnecting the same output must not change the layout.
9//! * This includes both secondary outputs and the primary output.
10//! 2. Connecting an output must not change the layout for any workspaces that were never on that
11//! output.
12//!
13//! Therefore, we implement the following logic: every workspace keeps track of which output it
14//! originated on. When an output disconnects, its workspace (or workspaces, in case of the primary
15//! output disconnecting) are appended to the (potentially new) primary output, but remember their
16//! original output. Then, if the original output connects again, all workspaces originally from
17//! there move back to that output.
18//!
19//! In order to avoid surprising behavior, if the user creates or moves any new windows onto a
20//! workspace, it forgets its original output, and its current output becomes its original output.
21//! Imagine a scenario: the user works with a laptop and a monitor at home, then takes their laptop
22//! with them, disconnecting the monitor, and keeps working as normal, using the second monitor's
23//! workspace just like any other. Then they come back, reconnect the second monitor, and now we
24//! don't want an unassuming workspace to end up on it.
25//!
26//! ## Workspaces-only-on-primary considerations
27//!
28//! If this logic results in more than one workspace present on a secondary output, then as a
29//! compromise we only keep the first workspace there, and move the rest to the primary output,
30//! making the primary output their original output.
31
32use std::cmp::min;
33use std::mem;
34use std::rc::Rc;
35use std::time::Duration;
36
37use niri_config::{CenterFocusedColumn, Config, FloatOrInt, Struts, Workspace as WorkspaceConfig};
38use niri_ipc::SizeChange;
39use smithay::backend::renderer::element::surface::WaylandSurfaceRenderElement;
40use smithay::backend::renderer::element::Id;
41use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
42use smithay::output::{self, Output};
43use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
44use smithay::utils::{Logical, Point, Scale, Serial, Size, Transform};
45
46pub use self::monitor::MonitorRenderElement;
47use self::monitor::{Monitor, WorkspaceSwitch};
48use self::workspace::{compute_working_area, Column, ColumnWidth, OutputId, Workspace};
49use crate::niri_render_elements;
50use crate::render_helpers::renderer::NiriRenderer;
51use crate::render_helpers::snapshot::RenderSnapshot;
52use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
53use crate::render_helpers::texture::TextureBuffer;
54use crate::render_helpers::{BakedBuffer, RenderTarget, SplitElements};
55use crate::utils::{output_size, round_logical_in_physical_max1, ResizeEdge};
56use crate::window::ResolvedWindowRules;
57
58pub mod closing_window;
59pub mod focus_ring;
60pub mod monitor;
61pub mod opening_window;
62pub mod tile;
63pub mod workspace;
64
65/// Size changes up to this many pixels don't animate.
66pub const RESIZE_ANIMATION_THRESHOLD: f64 = 10.;
67
68niri_render_elements! {
69 LayoutElementRenderElement<R> => {
70 Wayland = WaylandSurfaceRenderElement<R>,
71 SolidColor = SolidColorRenderElement,
72 }
73}
74
75pub type LayoutElementRenderSnapshot =
76 RenderSnapshot<BakedBuffer<TextureBuffer<GlesTexture>>, BakedBuffer<SolidColorBuffer>>;
77
78#[derive(Debug, Clone, Copy)]
79pub struct InteractiveResizeData {
80 pub edges: ResizeEdge,
81}
82
83pub trait LayoutElement {
84 /// Type that can be used as a unique ID of this element.
85 type Id: PartialEq + std::fmt::Debug;
86
87 /// Unique ID of this element.
88 fn id(&self) -> &Self::Id;
89
90 /// Visual size of the element.
91 ///
92 /// This is what the user would consider the size, i.e. excluding CSD shadows and whatnot.
93 /// Corresponds to the Wayland window geometry size.
94 fn size(&self) -> Size<i32, Logical>;
95
96 /// Returns the location of the element's buffer relative to the element's visual geometry.
97 ///
98 /// I.e. if the element has CSD shadows, its buffer location will have negative coordinates.
99 fn buf_loc(&self) -> Point<i32, Logical>;
100
101 /// Checks whether a point is in the element's input region.
102 ///
103 /// The point is relative to the element's visual geometry.
104 fn is_in_input_region(&self, point: Point<f64, Logical>) -> bool;
105
106 /// Renders the element at the given visual location.
107 ///
108 /// The element should be rendered in such a way that its visual geometry ends up at the given
109 /// location.
110 fn render<R: NiriRenderer>(
111 &self,
112 renderer: &mut R,
113 location: Point<f64, Logical>,
114 scale: Scale<f64>,
115 alpha: f32,
116 target: RenderTarget,
117 ) -> SplitElements<LayoutElementRenderElement<R>>;
118
119 /// Renders the non-popup parts of the element.
120 fn render_normal<R: NiriRenderer>(
121 &self,
122 renderer: &mut R,
123 location: Point<f64, Logical>,
124 scale: Scale<f64>,
125 alpha: f32,
126 target: RenderTarget,
127 ) -> Vec<LayoutElementRenderElement<R>> {
128 self.render(renderer, location, scale, alpha, target).normal
129 }
130
131 /// Renders the popups of the element.
132 fn render_popups<R: NiriRenderer>(
133 &self,
134 renderer: &mut R,
135 location: Point<f64, Logical>,
136 scale: Scale<f64>,
137 alpha: f32,
138 target: RenderTarget,
139 ) -> Vec<LayoutElementRenderElement<R>> {
140 self.render(renderer, location, scale, alpha, target).popups
141 }
142
143 fn request_size(&mut self, size: Size<i32, Logical>, animate: bool);
144 fn request_fullscreen(&self, size: Size<i32, Logical>);
145 fn min_size(&self) -> Size<i32, Logical>;
146 fn max_size(&self) -> Size<i32, Logical>;
147 fn is_wl_surface(&self, wl_surface: &WlSurface) -> bool;
148 fn has_ssd(&self) -> bool;
149 fn set_preferred_scale_transform(&self, scale: output::Scale, transform: Transform);
150 fn output_enter(&self, output: &Output);
151 fn output_leave(&self, output: &Output);
152 fn set_offscreen_element_id(&self, id: Option<Id>);
153 fn set_activated(&mut self, active: bool);
154 fn set_active_in_column(&mut self, active: bool);
155 fn set_bounds(&self, bounds: Size<i32, Logical>);
156
157 fn send_pending_configure(&mut self);
158
159 /// Whether the element is currently fullscreen.
160 ///
161 /// This will *not* switch immediately after a [`LayoutElement::request_fullscreen()`] call.
162 fn is_fullscreen(&self) -> bool;
163
164 /// Whether we're requesting the element to be fullscreen.
165 ///
166 /// This *will* switch immediately after a [`LayoutElement::request_fullscreen()`] call.
167 fn is_pending_fullscreen(&self) -> bool;
168
169 fn rules(&self) -> &ResolvedWindowRules;
170
171 /// Runs periodic clean-up tasks.
172 fn refresh(&self);
173
174 fn animation_snapshot(&self) -> Option<&LayoutElementRenderSnapshot>;
175 fn take_animation_snapshot(&mut self) -> Option<LayoutElementRenderSnapshot>;
176
177 fn set_interactive_resize(&mut self, data: Option<InteractiveResizeData>);
178 fn cancel_interactive_resize(&mut self);
179 fn update_interactive_resize(&mut self, serial: Serial);
180 fn interactive_resize_data(&self) -> Option<InteractiveResizeData>;
181}
182
183#[derive(Debug)]
184pub struct Layout<W: LayoutElement> {
185 /// Monitors and workspaes in the layout.
186 monitor_set: MonitorSet<W>,
187 /// Configurable properties of the layout.
188 options: Rc<Options>,
189}
190
191#[derive(Debug)]
192enum MonitorSet<W: LayoutElement> {
193 /// At least one output is connected.
194 Normal {
195 /// Connected monitors.
196 monitors: Vec<Monitor<W>>,
197 /// Index of the primary monitor.
198 primary_idx: usize,
199 /// Index of the active monitor.
200 active_monitor_idx: usize,
201 },
202 /// No outputs are connected, and these are the workspaces.
203 NoOutputs {
204 /// The workspaces.
205 workspaces: Vec<Workspace<W>>,
206 },
207}
208
209#[derive(Debug, Clone, PartialEq)]
210pub struct Options {
211 /// Padding around windows in logical pixels.
212 pub gaps: f64,
213 /// Extra padding around the working area in logical pixels.
214 pub struts: Struts,
215 pub focus_ring: niri_config::FocusRing,
216 pub border: niri_config::Border,
217 pub center_focused_column: CenterFocusedColumn,
218 /// Column widths that `toggle_width()` switches between.
219 pub preset_widths: Vec<ColumnWidth>,
220 /// Initial width for new columns.
221 pub default_width: Option<ColumnWidth>,
222 pub animations: niri_config::Animations,
223}
224
225impl Default for Options {
226 fn default() -> Self {
227 Self {
228 gaps: 16.,
229 struts: Default::default(),
230 focus_ring: Default::default(),
231 border: Default::default(),
232 center_focused_column: Default::default(),
233 preset_widths: vec![
234 ColumnWidth::Proportion(1. / 3.),
235 ColumnWidth::Proportion(0.5),
236 ColumnWidth::Proportion(2. / 3.),
237 ],
238 default_width: None,
239 animations: Default::default(),
240 }
241 }
242}
243
244impl Options {
245 fn from_config(config: &Config) -> Self {
246 let layout = &config.layout;
247 let preset_column_widths = &layout.preset_column_widths;
248
249 let preset_widths = if preset_column_widths.is_empty() {
250 Options::default().preset_widths
251 } else {
252 preset_column_widths
253 .iter()
254 .copied()
255 .map(ColumnWidth::from)
256 .collect()
257 };
258
259 // Missing default_column_width maps to Some(ColumnWidth::Proportion(0.5)),
260 // while present, but empty, maps to None.
261 let default_width = layout
262 .default_column_width
263 .as_ref()
264 .map(|w| w.0.map(ColumnWidth::from))
265 .unwrap_or(Some(ColumnWidth::Proportion(0.5)));
266
267 Self {
268 gaps: layout.gaps.0,
269 struts: layout.struts,
270 focus_ring: layout.focus_ring,
271 border: layout.border,
272 center_focused_column: layout.center_focused_column,
273 preset_widths,
274 default_width,
275 animations: config.animations.clone(),
276 }
277 }
278
279 fn adjusted_for_scale(mut self, scale: f64) -> Self {
280 let round = |logical: f64| round_logical_in_physical_max1(scale, logical);
281
282 self.gaps = round(self.gaps);
283 self.focus_ring.width = FloatOrInt(round(self.focus_ring.width.0));
284 self.border.width = FloatOrInt(round(self.border.width.0));
285
286 self
287 }
288}
289
290impl<W: LayoutElement> Layout<W> {
291 pub fn new(config: &Config) -> Self {
292 Self::with_options_and_workspaces(config, Options::from_config(config))
293 }
294
295 pub fn with_options(options: Options) -> Self {
296 Self {
297 monitor_set: MonitorSet::NoOutputs { workspaces: vec![] },
298 options: Rc::new(options),
299 }
300 }
301
302 fn with_options_and_workspaces(config: &Config, options: Options) -> Self {
303 let opts = Rc::new(options);
304
305 let workspaces = config
306 .workspaces
307 .iter()
308 .map(|ws| Workspace::new_with_config_no_outputs(Some(ws.clone()), opts.clone()))
309 .collect();
310
311 Self {
312 monitor_set: MonitorSet::NoOutputs { workspaces },
313 options: opts,
314 }
315 }
316
317 pub fn add_output(&mut self, output: Output) {
318 let id = OutputId::new(&output);
319
320 self.monitor_set = match mem::take(&mut self.monitor_set) {
321 MonitorSet::Normal {
322 mut monitors,
323 primary_idx,
324 active_monitor_idx,
325 } => {
326 let primary = &mut monitors[primary_idx];
327
328 let mut stopped_primary_ws_switch = false;
329
330 let mut workspaces = vec![];
331 for i in (0..primary.workspaces.len()).rev() {
332 if primary.workspaces[i].original_output == id {
333 let ws = primary.workspaces.remove(i);
334
335 // FIXME: this can be coded in a way that the workspace switch won't be
336 // affected if the removed workspace is invisible. But this is good enough
337 // for now.
338 if primary.workspace_switch.is_some() {
339 primary.workspace_switch = None;
340 stopped_primary_ws_switch = true;
341 }
342
343 // The user could've closed a window while remaining on this workspace, on
344 // another monitor. However, we will add an empty workspace in the end
345 // instead.
346 if ws.has_windows() || ws.name.is_some() {
347 workspaces.push(ws);
348 }
349
350 if i <= primary.active_workspace_idx {
351 primary.active_workspace_idx =
352 primary.active_workspace_idx.saturating_sub(1);
353 }
354 }
355 }
356
357 // If we stopped a workspace switch, then we might need to clean up workspaces.
358 if stopped_primary_ws_switch {
359 primary.clean_up_workspaces();
360 }
361
362 workspaces.reverse();
363
364 // Make sure there's always an empty workspace.
365 workspaces.push(Workspace::new(output.clone(), self.options.clone()));
366
367 for ws in &mut workspaces {
368 ws.set_output(Some(output.clone()));
369 }
370
371 monitors.push(Monitor::new(output, workspaces, self.options.clone()));
372 MonitorSet::Normal {
373 monitors,
374 primary_idx,
375 active_monitor_idx,
376 }
377 }
378 MonitorSet::NoOutputs { mut workspaces } => {
379 // We know there are no empty workspaces there, so add one.
380 workspaces.push(Workspace::new(output.clone(), self.options.clone()));
381
382 for workspace in &mut workspaces {
383 workspace.set_output(Some(output.clone()));
384 }
385
386 let monitor = Monitor::new(output, workspaces, self.options.clone());
387
388 MonitorSet::Normal {
389 monitors: vec![monitor],
390 primary_idx: 0,
391 active_monitor_idx: 0,
392 }
393 }
394 }
395 }
396
397 pub fn remove_output(&mut self, output: &Output) {
398 self.monitor_set = match mem::take(&mut self.monitor_set) {
399 MonitorSet::Normal {
400 mut monitors,
401 mut primary_idx,
402 mut active_monitor_idx,
403 } => {
404 let idx = monitors
405 .iter()
406 .position(|mon| &mon.output == output)
407 .expect("trying to remove non-existing output");
408 let monitor = monitors.remove(idx);
409 let mut workspaces = monitor.workspaces;
410
411 for ws in &mut workspaces {
412 ws.set_output(None);
413 }
414
415 // Get rid of empty workspaces.
416 workspaces.retain(|ws| ws.has_windows() || ws.name.is_some());
417
418 if monitors.is_empty() {
419 // Removed the last monitor.
420 MonitorSet::NoOutputs { workspaces }
421 } else {
422 if primary_idx >= idx {
423 // Update primary_idx to either still point at the same monitor, or at some
424 // other monitor if the primary has been removed.
425 primary_idx = primary_idx.saturating_sub(1);
426 }
427 if active_monitor_idx >= idx {
428 // Update active_monitor_idx to either still point at the same monitor, or
429 // at some other monitor if the active monitor has
430 // been removed.
431 active_monitor_idx = active_monitor_idx.saturating_sub(1);
432 }
433
434 let primary = &mut monitors[primary_idx];
435 for ws in &mut workspaces {
436 ws.set_output(Some(primary.output.clone()));
437 }
438
439 let empty_was_focused =
440 primary.active_workspace_idx == primary.workspaces.len() - 1;
441
442 // Push the workspaces from the removed monitor in the end, right before the
443 // last, empty, workspace.
444 let empty = primary.workspaces.remove(primary.workspaces.len() - 1);
445 primary.workspaces.extend(workspaces);
446 primary.workspaces.push(empty);
447
448 // If the empty workspace was focused on the primary monitor, keep it focused.
449 if empty_was_focused {
450 primary.active_workspace_idx = primary.workspaces.len() - 1;
451 }
452
453 MonitorSet::Normal {
454 monitors,
455 primary_idx,
456 active_monitor_idx,
457 }
458 }
459 }
460 MonitorSet::NoOutputs { .. } => {
461 panic!("tried to remove output when there were already none")
462 }
463 }
464 }
465
466 pub fn add_window_by_idx(
467 &mut self,
468 monitor_idx: usize,
469 workspace_idx: usize,
470 window: W,
471 activate: bool,
472 width: ColumnWidth,
473 is_full_width: bool,
474 ) {
475 let MonitorSet::Normal {
476 monitors,
477 active_monitor_idx,
478 ..
479 } = &mut self.monitor_set
480 else {
481 panic!()
482 };
483
484 monitors[monitor_idx].add_window(workspace_idx, window, activate, width, is_full_width);
485
486 if activate {
487 *active_monitor_idx = monitor_idx;
488 }
489 }
490
491 /// Adds a new window to the layout on a specific workspace.
492 pub fn add_window_to_named_workspace(
493 &mut self,
494 workspace_name: &str,
495 window: W,
496 width: Option<ColumnWidth>,
497 is_full_width: bool,
498 ) -> Option<&Output> {
499 let mut width = width.unwrap_or_else(|| ColumnWidth::Fixed(f64::from(window.size().w)));
500 if let ColumnWidth::Fixed(w) = &mut width {
501 let rules = window.rules();
502 let border_config = rules.border.resolve_against(self.options.border);
503 if !border_config.off {
504 *w += border_config.width.0 * 2.;
505 }
506 }
507
508 match &mut self.monitor_set {
509 MonitorSet::Normal {
510 monitors,
511 active_monitor_idx,
512 ..
513 } => {
514 let (mon_idx, mon, ws_idx) = monitors
515 .iter_mut()
516 .enumerate()
517 .find_map(|(mon_idx, mon)| {
518 mon.find_named_workspace_index(workspace_name)
519 .map(move |ws_idx| (mon_idx, mon, ws_idx))
520 })
521 .unwrap();
522
523 // Don't steal focus from an active fullscreen window.
524 let mut activate = true;
525 let ws = &mon.workspaces[ws_idx];
526 if mon_idx == *active_monitor_idx
527 && !ws.columns.is_empty()
528 && ws.columns[ws.active_column_idx].is_fullscreen
529 {
530 activate = false;
531 }
532
533 // Don't activate if on a different workspace.
534 if mon.active_workspace_idx != ws_idx {
535 activate = false;
536 }
537
538 mon.add_window(ws_idx, window, activate, width, is_full_width);
539 Some(&mon.output)
540 }
541 MonitorSet::NoOutputs { workspaces } => {
542 let ws = workspaces
543 .iter_mut()
544 .find(|ws| {
545 ws.name
546 .as_ref()
547 .map_or(false, |name| name.eq_ignore_ascii_case(workspace_name))
548 })
549 .unwrap();
550 ws.add_window(window, true, width, is_full_width);
551 None
552 }
553 }
554 }
555
556 pub fn add_column_by_idx(
557 &mut self,
558 monitor_idx: usize,
559 workspace_idx: usize,
560 column: Column<W>,
561 activate: bool,
562 ) {
563 let MonitorSet::Normal {
564 monitors,
565 active_monitor_idx,
566 ..
567 } = &mut self.monitor_set
568 else {
569 panic!()
570 };
571
572 monitors[monitor_idx].add_column(workspace_idx, column, activate);
573
574 if activate {
575 *active_monitor_idx = monitor_idx;
576 }
577 }
578
579 /// Adds a new window to the layout.
580 ///
581 /// Returns an output that the window was added to, if there were any outputs.
582 pub fn add_window(
583 &mut self,
584 window: W,
585 width: Option<ColumnWidth>,
586 is_full_width: bool,
587 ) -> Option<&Output> {
588 let mut width = width.unwrap_or_else(|| ColumnWidth::Fixed(f64::from(window.size().w)));
589 if let ColumnWidth::Fixed(w) = &mut width {
590 let rules = window.rules();
591 let border_config = rules.border.resolve_against(self.options.border);
592 if !border_config.off {
593 *w += border_config.width.0 * 2.;
594 }
595 }
596
597 match &mut self.monitor_set {
598 MonitorSet::Normal {
599 monitors,
600 active_monitor_idx,
601 ..
602 } => {
603 let mon = &mut monitors[*active_monitor_idx];
604
605 // Don't steal focus from an active fullscreen window.
606 let mut activate = true;
607 let ws = &mon.workspaces[mon.active_workspace_idx];
608 if !ws.columns.is_empty() && ws.columns[ws.active_column_idx].is_fullscreen {
609 activate = false;
610 }
611
612 mon.add_window(
613 mon.active_workspace_idx,
614 window,
615 activate,
616 width,
617 is_full_width,
618 );
619 Some(&mon.output)
620 }
621 MonitorSet::NoOutputs { workspaces } => {
622 let ws = if let Some(ws) = workspaces.get_mut(0) {
623 ws
624 } else {
625 workspaces.push(Workspace::new_no_outputs(self.options.clone()));
626 &mut workspaces[0]
627 };
628 ws.add_window(window, true, width, is_full_width);
629 None
630 }
631 }
632 }
633
634 /// Adds a new window to the layout immediately to the right of another window.
635 ///
636 /// If that another window was active, activates the new window.
637 ///
638 /// Returns an output that the window was added to, if there were any outputs.
639 pub fn add_window_right_of(
640 &mut self,
641 right_of: &W::Id,
642 window: W,
643 width: Option<ColumnWidth>,
644 is_full_width: bool,
645 ) -> Option<&Output> {
646 let mut width = width.unwrap_or_else(|| ColumnWidth::Fixed(f64::from(window.size().w)));
647 if let ColumnWidth::Fixed(w) = &mut width {
648 let rules = window.rules();
649 let border_config = rules.border.resolve_against(self.options.border);
650 if !border_config.off {
651 *w += border_config.width.0 * 2.;
652 }
653 }
654
655 match &mut self.monitor_set {
656 MonitorSet::Normal { monitors, .. } => {
657 let mon = monitors
658 .iter_mut()
659 .find(|mon| mon.workspaces.iter().any(|ws| ws.has_window(right_of)))
660 .unwrap();
661
662 mon.add_window_right_of(right_of, window, width, is_full_width);
663 Some(&mon.output)
664 }
665 MonitorSet::NoOutputs { workspaces } => {
666 let ws = workspaces
667 .iter_mut()
668 .find(|ws| ws.has_window(right_of))
669 .unwrap();
670 ws.add_window_right_of(right_of, window, width, is_full_width);
671 None
672 }
673 }
674 }
675
676 /// Adds a new window to the layout on a specific output.
677 pub fn add_window_on_output(
678 &mut self,
679 output: &Output,
680 window: W,
681 width: Option<ColumnWidth>,
682 is_full_width: bool,
683 ) {
684 let mut width = width.unwrap_or_else(|| ColumnWidth::Fixed(f64::from(window.size().w)));
685 if let ColumnWidth::Fixed(w) = &mut width {
686 let rules = window.rules();
687 let border_config = rules.border.resolve_against(self.options.border);
688 if !border_config.off {
689 *w += border_config.width.0 * 2.;
690 }
691 }
692
693 let MonitorSet::Normal {
694 monitors,
695 active_monitor_idx,
696 ..
697 } = &mut self.monitor_set
698 else {
699 panic!()
700 };
701
702 let (mon_idx, mon) = monitors
703 .iter_mut()
704 .enumerate()
705 .find(|(_, mon)| mon.output == *output)
706 .unwrap();
707
708 // Don't steal focus from an active fullscreen window.
709 let mut activate = true;
710 let ws = &mon.workspaces[mon.active_workspace_idx];
711 if mon_idx == *active_monitor_idx
712 && !ws.columns.is_empty()
713 && ws.columns[ws.active_column_idx].is_fullscreen
714 {
715 activate = false;
716 }
717
718 mon.add_window(
719 mon.active_workspace_idx,
720 window,
721 activate,
722 width,
723 is_full_width,
724 );
725 }
726
727 pub fn remove_window(&mut self, window: &W::Id) -> Option<W> {
728 let mut rv = None;
729
730 match &mut self.monitor_set {
731 MonitorSet::Normal { monitors, .. } => {
732 for mon in monitors {
733 for (idx, ws) in mon.workspaces.iter_mut().enumerate() {
734 if ws.has_window(window) {
735 rv = Some(ws.remove_window(window));
736
737 // Clean up empty workspaces that are not active and not last.
738 if !ws.has_windows()
739 && idx != mon.active_workspace_idx
740 && idx != mon.workspaces.len() - 1
741 && mon.workspace_switch.is_none()
742 && mon.workspaces[idx].name.is_none()
743 {
744 mon.workspaces.remove(idx);
745
746 if idx < mon.active_workspace_idx {
747 mon.active_workspace_idx -= 1;
748 }
749 }
750
751 break;
752 }
753 }
754 }
755 }
756 MonitorSet::NoOutputs { workspaces, .. } => {
757 for (idx, ws) in workspaces.iter_mut().enumerate() {
758 if ws.has_window(window) {
759 rv = Some(ws.remove_window(window));
760
761 // Clean up empty workspaces.
762 if !ws.has_windows() && workspaces[idx].name.is_none() {
763 workspaces.remove(idx);
764 }
765
766 break;
767 }
768 }
769 }
770 }
771
772 rv
773 }
774
775 pub fn update_window(&mut self, window: &W::Id, serial: Option<Serial>) {
776 match &mut self.monitor_set {
777 MonitorSet::Normal { monitors, .. } => {
778 for mon in monitors {
779 for ws in &mut mon.workspaces {
780 if ws.has_window(window) {
781 ws.update_window(window, serial);
782 return;
783 }
784 }
785 }
786 }
787 MonitorSet::NoOutputs { workspaces, .. } => {
788 for ws in workspaces {
789 if ws.has_window(window) {
790 ws.update_window(window, serial);
791 return;
792 }
793 }
794 }
795 }
796 }
797
798 pub fn find_window_and_output(&self, wl_surface: &WlSurface) -> Option<(&W, &Output)> {
799 if let MonitorSet::Normal { monitors, .. } = &self.monitor_set {
800 for mon in monitors {
801 for ws in &mon.workspaces {
802 if let Some(window) = ws.find_wl_surface(wl_surface) {
803 return Some((window, &mon.output));
804 }
805 }
806 }
807 }
808
809 None
810 }
811
812 pub fn find_workspace_by_name(&self, workspace_name: &str) -> Option<(usize, &Workspace<W>)> {
813 match &self.monitor_set {
814 MonitorSet::Normal { ref monitors, .. } => {
815 for mon in monitors {
816 if let Some((index, workspace)) =
817 mon.workspaces.iter().enumerate().find(|(_, w)| {
818 w.name
819 .as_ref()
820 .map_or(false, |name| name.eq_ignore_ascii_case(workspace_name))
821 })
822 {
823 return Some((index, workspace));
824 }
825 }
826 }
827 MonitorSet::NoOutputs { workspaces } => {
828 if let Some((index, workspace)) = workspaces.iter().enumerate().find(|(_, w)| {
829 w.name
830 .as_ref()
831 .map_or(false, |name| name.eq_ignore_ascii_case(workspace_name))
832 }) {
833 return Some((index, workspace));
834 }
835 }
836 }
837
838 None
839 }
840
841 pub fn unname_workspace(&mut self, workspace_name: &str) {
842 match &mut self.monitor_set {
843 MonitorSet::Normal { monitors, .. } => {
844 for mon in monitors {
845 if mon.unname_workspace(workspace_name) {
846 if mon.workspace_switch.is_none() {
847 mon.clean_up_workspaces();
848 }
849 return;
850 }
851 }
852 }
853 MonitorSet::NoOutputs { workspaces } => {
854 for (idx, ws) in workspaces.iter_mut().enumerate() {
855 if ws
856 .name
857 .as_ref()
858 .map_or(false, |name| name.eq_ignore_ascii_case(workspace_name))
859 {
860 ws.unname();
861
862 // Clean up empty workspaces.
863 if !ws.has_windows() {
864 workspaces.remove(idx);
865 }
866
867 return;
868 }
869 }
870 }
871 }
872 }
873
874 pub fn find_window_and_output_mut(
875 &mut self,
876 wl_surface: &WlSurface,
877 ) -> Option<(&mut W, Option<&Output>)> {
878 match &mut self.monitor_set {
879 MonitorSet::Normal { monitors, .. } => {
880 for mon in monitors {
881 for ws in &mut mon.workspaces {
882 if let Some(window) = ws.find_wl_surface_mut(wl_surface) {
883 return Some((window, Some(&mon.output)));
884 }
885 }
886 }
887 }
888 MonitorSet::NoOutputs { workspaces } => {
889 for ws in workspaces {
890 if let Some(window) = ws.find_wl_surface_mut(wl_surface) {
891 return Some((window, None));
892 }
893 }
894 }
895 }
896
897 None
898 }
899
900 pub fn window_loc(&self, window: &W::Id) -> Option<Point<f64, Logical>> {
901 match &self.monitor_set {
902 MonitorSet::Normal { monitors, .. } => {
903 for mon in monitors {
904 for ws in &mon.workspaces {
905 for col in &ws.columns {
906 if let Some(idx) = col.position(window) {
907 return Some(col.window_loc(idx));
908 }
909 }
910 }
911 }
912 }
913 MonitorSet::NoOutputs { workspaces, .. } => {
914 for ws in workspaces {
915 for col in &ws.columns {
916 if let Some(idx) = col.position(window) {
917 return Some(col.window_loc(idx));
918 }
919 }
920 }
921 }
922 }
923
924 None
925 }
926
927 pub fn update_output_size(&mut self, output: &Output) {
928 let _span = tracy_client::span!("Layout::update_output_size");
929
930 let MonitorSet::Normal { monitors, .. } = &mut self.monitor_set else {
931 panic!()
932 };
933
934 for mon in monitors {
935 if &mon.output == output {
936 let scale = output.current_scale();
937 let transform = output.current_transform();
938 let view_size = output_size(output);
939 let working_area = compute_working_area(output, self.options.struts);
940
941 for ws in &mut mon.workspaces {
942 ws.set_view_size(scale, transform, view_size, working_area);
943 }
944
945 break;
946 }
947 }
948 }
949
950 pub fn scroll_amount_to_activate(&self, window: &W::Id) -> f64 {
951 let MonitorSet::Normal { monitors, .. } = &self.monitor_set else {
952 return 0.;
953 };
954
955 for mon in monitors {
956 for ws in &mon.workspaces {
957 if ws.has_window(window) {
958 return ws.scroll_amount_to_activate(window);
959 }
960 }
961 }
962
963 0.
964 }
965
966 pub fn activate_window(&mut self, window: &W::Id) {
967 let MonitorSet::Normal {
968 monitors,
969 active_monitor_idx,
970 ..
971 } = &mut self.monitor_set
972 else {
973 return;
974 };
975
976 for (monitor_idx, mon) in monitors.iter_mut().enumerate() {
977 for (workspace_idx, ws) in mon.workspaces.iter_mut().enumerate() {
978 if ws.has_window(window) {
979 *active_monitor_idx = monitor_idx;
980 ws.activate_window(window);
981
982 // If currently in the middle of a vertical swipe between the target workspace
983 // and some other, don't switch the workspace.
984 match &mon.workspace_switch {
985 Some(WorkspaceSwitch::Gesture(gesture))
986 if gesture.current_idx.floor() == workspace_idx as f64
987 || gesture.current_idx.ceil() == workspace_idx as f64 => {}
988 _ => mon.switch_workspace(workspace_idx, true),
989 }
990
991 break;
992 }
993 }
994 }
995 }
996
997 pub fn activate_output(&mut self, output: &Output) {
998 let MonitorSet::Normal {
999 monitors,
1000 active_monitor_idx,
1001 ..
1002 } = &mut self.monitor_set
1003 else {
1004 return;
1005 };
1006
1007 let idx = monitors
1008 .iter()
1009 .position(|mon| &mon.output == output)
1010 .unwrap();
1011 *active_monitor_idx = idx;
1012 }
1013
1014 pub fn active_output(&self) -> Option<&Output> {
1015 let MonitorSet::Normal {
1016 monitors,
1017 active_monitor_idx,
1018 ..
1019 } = &self.monitor_set
1020 else {
1021 return None;
1022 };
1023
1024 Some(&monitors[*active_monitor_idx].output)
1025 }
1026
1027 pub fn active_workspace(&self) -> Option<&Workspace<W>> {
1028 let MonitorSet::Normal {
1029 monitors,
1030 active_monitor_idx,
1031 ..
1032 } = &self.monitor_set
1033 else {
1034 return None;
1035 };
1036
1037 let mon = &monitors[*active_monitor_idx];
1038 Some(&mon.workspaces[mon.active_workspace_idx])
1039 }
1040
1041 pub fn active_window(&self) -> Option<(&W, &Output)> {
1042 let MonitorSet::Normal {
1043 monitors,
1044 active_monitor_idx,
1045 ..
1046 } = &self.monitor_set
1047 else {
1048 return None;
1049 };
1050
1051 let mon = &monitors[*active_monitor_idx];
1052 let ws = &mon.workspaces[mon.active_workspace_idx];
1053
1054 if ws.columns.is_empty() {
1055 return None;
1056 }
1057
1058 let col = &ws.columns[ws.active_column_idx];
1059 Some((col.tiles[col.active_tile_idx].window(), &mon.output))
1060 }
1061
1062 pub fn windows_for_output(&self, output: &Output) -> impl Iterator<Item = &W> + '_ {
1063 let MonitorSet::Normal { monitors, .. } = &self.monitor_set else {
1064 panic!()
1065 };
1066
1067 let mon = monitors.iter().find(|mon| &mon.output == output).unwrap();
1068 mon.workspaces.iter().flat_map(|ws| ws.windows())
1069 }
1070
1071 pub fn with_windows(&self, mut f: impl FnMut(&W, Option<&Output>)) {
1072 match &self.monitor_set {
1073 MonitorSet::Normal { monitors, .. } => {
1074 for mon in monitors {
1075 for ws in &mon.workspaces {
1076 for win in ws.windows() {
1077 f(win, Some(&mon.output));
1078 }
1079 }
1080 }
1081 }
1082 MonitorSet::NoOutputs { workspaces } => {
1083 for ws in workspaces {
1084 for win in ws.windows() {
1085 f(win, None);
1086 }
1087 }
1088 }
1089 }
1090 }
1091
1092 pub fn with_windows_mut(&mut self, mut f: impl FnMut(&mut W, Option<&Output>)) {
1093 match &mut self.monitor_set {
1094 MonitorSet::Normal { monitors, .. } => {
1095 for mon in monitors {
1096 for ws in &mut mon.workspaces {
1097 for win in ws.windows_mut() {
1098 f(win, Some(&mon.output));
1099 }
1100 }
1101 }
1102 }
1103 MonitorSet::NoOutputs { workspaces } => {
1104 for ws in workspaces {
1105 for win in ws.windows_mut() {
1106 f(win, None);
1107 }
1108 }
1109 }
1110 }
1111 }
1112
1113 fn active_monitor(&mut self) -> Option<&mut Monitor<W>> {
1114 let MonitorSet::Normal {
1115 monitors,
1116 active_monitor_idx,
1117 ..
1118 } = &mut self.monitor_set
1119 else {
1120 return None;
1121 };
1122
1123 Some(&mut monitors[*active_monitor_idx])
1124 }
1125
1126 pub fn active_monitor_ref(&self) -> Option<&Monitor<W>> {
1127 let MonitorSet::Normal {
1128 monitors,
1129 active_monitor_idx,
1130 ..
1131 } = &self.monitor_set
1132 else {
1133 return None;
1134 };
1135
1136 Some(&monitors[*active_monitor_idx])
1137 }
1138
1139 pub fn monitor_for_output(&self, output: &Output) -> Option<&Monitor<W>> {
1140 let MonitorSet::Normal { monitors, .. } = &self.monitor_set else {
1141 return None;
1142 };
1143
1144 monitors.iter().find(|monitor| &monitor.output == output)
1145 }
1146
1147 pub fn monitor_for_workspace(&self, workspace_name: &str) -> Option<&Monitor<W>> {
1148 let MonitorSet::Normal { monitors, .. } = &self.monitor_set else {
1149 return None;
1150 };
1151
1152 monitors.iter().find(|monitor| {
1153 monitor.workspaces.iter().any(|ws| {
1154 ws.name
1155 .as_ref()
1156 .map_or(false, |name| name.eq_ignore_ascii_case(workspace_name))
1157 })
1158 })
1159 }
1160
1161 pub fn outputs(&self) -> impl Iterator<Item = &Output> + '_ {
1162 let monitors = if let MonitorSet::Normal { monitors, .. } = &self.monitor_set {
1163 &monitors[..]
1164 } else {
1165 &[][..]
1166 };
1167
1168 monitors.iter().map(|mon| &mon.output)
1169 }
1170
1171 pub fn move_left(&mut self) {
1172 let Some(monitor) = self.active_monitor() else {
1173 return;
1174 };
1175 monitor.move_left();
1176 }
1177
1178 pub fn move_right(&mut self) {
1179 let Some(monitor) = self.active_monitor() else {
1180 return;
1181 };
1182 monitor.move_right();
1183 }
1184
1185 pub fn move_column_to_first(&mut self) {
1186 let Some(monitor) = self.active_monitor() else {
1187 return;
1188 };
1189 monitor.move_column_to_first();
1190 }
1191
1192 pub fn move_column_to_last(&mut self) {
1193 let Some(monitor) = self.active_monitor() else {
1194 return;
1195 };
1196 monitor.move_column_to_last();
1197 }
1198
1199 pub fn move_down(&mut self) {
1200 let Some(monitor) = self.active_monitor() else {
1201 return;
1202 };
1203 monitor.move_down();
1204 }
1205
1206 pub fn move_up(&mut self) {
1207 let Some(monitor) = self.active_monitor() else {
1208 return;
1209 };
1210 monitor.move_up();
1211 }
1212
1213 pub fn move_down_or_to_workspace_down(&mut self) {
1214 let Some(monitor) = self.active_monitor() else {
1215 return;
1216 };
1217 monitor.move_down_or_to_workspace_down();
1218 }
1219
1220 pub fn move_up_or_to_workspace_up(&mut self) {
1221 let Some(monitor) = self.active_monitor() else {
1222 return;
1223 };
1224 monitor.move_up_or_to_workspace_up();
1225 }
1226
1227 pub fn consume_or_expel_window_left(&mut self) {
1228 let Some(monitor) = self.active_monitor() else {
1229 return;
1230 };
1231 monitor.consume_or_expel_window_left();
1232 }
1233
1234 pub fn consume_or_expel_window_right(&mut self) {
1235 let Some(monitor) = self.active_monitor() else {
1236 return;
1237 };
1238 monitor.consume_or_expel_window_right();
1239 }
1240
1241 pub fn focus_left(&mut self) {
1242 let Some(monitor) = self.active_monitor() else {
1243 return;
1244 };
1245 monitor.focus_left();
1246 }
1247
1248 pub fn focus_right(&mut self) {
1249 let Some(monitor) = self.active_monitor() else {
1250 return;
1251 };
1252 monitor.focus_right();
1253 }
1254
1255 pub fn focus_column_first(&mut self) {
1256 let Some(monitor) = self.active_monitor() else {
1257 return;
1258 };
1259 monitor.focus_column_first();
1260 }
1261
1262 pub fn focus_column_last(&mut self) {
1263 let Some(monitor) = self.active_monitor() else {
1264 return;
1265 };
1266 monitor.focus_column_last();
1267 }
1268
1269 pub fn focus_column_right_or_first(&mut self) {
1270 let Some(monitor) = self.active_monitor() else {
1271 return;
1272 };
1273 monitor.focus_column_right_or_first();
1274 }
1275
1276 pub fn focus_column_left_or_last(&mut self) {
1277 let Some(monitor) = self.active_monitor() else {
1278 return;
1279 };
1280 monitor.focus_column_left_or_last();
1281 }
1282
1283 pub fn focus_window_up_or_output(&mut self, output: &Output) -> bool {
1284 if let Some(monitor) = self.active_monitor() {
1285 let workspace = monitor.active_workspace();
1286
1287 if !workspace.columns.is_empty() {
1288 let curr_idx = workspace.columns[workspace.active_column_idx].active_tile_idx;
1289 let new_idx = curr_idx.saturating_sub(1);
1290 if curr_idx != new_idx {
1291 workspace.focus_up();
1292 return false;
1293 }
1294 }
1295 }
1296
1297 self.focus_output(output);
1298 true
1299 }
1300
1301 pub fn focus_window_down_or_output(&mut self, output: &Output) -> bool {
1302 if let Some(monitor) = self.active_monitor() {
1303 let workspace = monitor.active_workspace();
1304
1305 if !workspace.columns.is_empty() {
1306 let column = &workspace.columns[workspace.active_column_idx];
1307 let curr_idx = column.active_tile_idx;
1308 let new_idx = min(column.active_tile_idx + 1, column.tiles.len() - 1);
1309 if curr_idx != new_idx {
1310 workspace.focus_down();
1311 return false;
1312 }
1313 }
1314 }
1315
1316 self.focus_output(output);
1317 true
1318 }
1319
1320 pub fn focus_column_left_or_output(&mut self, output: &Output) -> bool {
1321 if let Some(monitor) = self.active_monitor() {
1322 let workspace = monitor.active_workspace();
1323 let curr_idx = workspace.active_column_idx;
1324
1325 if !workspace.columns.is_empty() && curr_idx != 0 {
1326 monitor.focus_left();
1327 return false;
1328 }
1329 }
1330
1331 self.focus_output(output);
1332 true
1333 }
1334
1335 pub fn focus_column_right_or_output(&mut self, output: &Output) -> bool {
1336 if let Some(monitor) = self.active_monitor() {
1337 let workspace = monitor.active_workspace();
1338 let curr_idx = workspace.active_column_idx;
1339 let columns = &workspace.columns;
1340
1341 if !workspace.columns.is_empty() && curr_idx != columns.len() - 1 {
1342 monitor.focus_right();
1343 return false;
1344 }
1345 }
1346
1347 self.focus_output(output);
1348 true
1349 }
1350
1351 pub fn focus_down(&mut self) {
1352 let Some(monitor) = self.active_monitor() else {
1353 return;
1354 };
1355 monitor.focus_down();
1356 }
1357
1358 pub fn focus_up(&mut self) {
1359 let Some(monitor) = self.active_monitor() else {
1360 return;
1361 };
1362 monitor.focus_up();
1363 }
1364
1365 pub fn focus_down_or_left(&mut self) {
1366 let Some(monitor) = self.active_monitor() else {
1367 return;
1368 };
1369 monitor.focus_down_or_left();
1370 }
1371
1372 pub fn focus_down_or_right(&mut self) {
1373 let Some(monitor) = self.active_monitor() else {
1374 return;
1375 };
1376 monitor.focus_down_or_right();
1377 }
1378
1379 pub fn focus_up_or_left(&mut self) {
1380 let Some(monitor) = self.active_monitor() else {
1381 return;
1382 };
1383 monitor.focus_up_or_left();
1384 }
1385
1386 pub fn focus_up_or_right(&mut self) {
1387 let Some(monitor) = self.active_monitor() else {
1388 return;
1389 };
1390 monitor.focus_up_or_right();
1391 }
1392
1393 pub fn focus_window_or_workspace_down(&mut self) {
1394 let Some(monitor) = self.active_monitor() else {
1395 return;
1396 };
1397 monitor.focus_window_or_workspace_down();
1398 }
1399
1400 pub fn focus_window_or_workspace_up(&mut self) {
1401 let Some(monitor) = self.active_monitor() else {
1402 return;
1403 };
1404 monitor.focus_window_or_workspace_up();
1405 }
1406
1407 pub fn move_to_workspace_up(&mut self) {
1408 let Some(monitor) = self.active_monitor() else {
1409 return;
1410 };
1411 monitor.move_to_workspace_up();
1412 }
1413
1414 pub fn move_to_workspace_down(&mut self) {
1415 let Some(monitor) = self.active_monitor() else {
1416 return;
1417 };
1418 monitor.move_to_workspace_down();
1419 }
1420
1421 pub fn move_to_workspace(&mut self, idx: usize) {
1422 let Some(monitor) = self.active_monitor() else {
1423 return;
1424 };
1425 monitor.move_to_workspace(idx);
1426 }
1427
1428 pub fn move_to_workspace_on_output(&mut self, output: &Output, idx: usize) {
1429 self.move_to_output(output);
1430 self.focus_output(output);
1431 self.move_to_workspace(idx);
1432 }
1433
1434 pub fn move_column_to_workspace_up(&mut self) {
1435 let Some(monitor) = self.active_monitor() else {
1436 return;
1437 };
1438 monitor.move_column_to_workspace_up();
1439 }
1440
1441 pub fn move_column_to_workspace_down(&mut self) {
1442 let Some(monitor) = self.active_monitor() else {
1443 return;
1444 };
1445 monitor.move_column_to_workspace_down();
1446 }
1447
1448 pub fn move_column_to_workspace(&mut self, idx: usize) {
1449 let Some(monitor) = self.active_monitor() else {
1450 return;
1451 };
1452 monitor.move_column_to_workspace(idx);
1453 }
1454
1455 pub fn move_column_to_workspace_on_output(&mut self, output: &Output, idx: usize) {
1456 self.move_to_output(output);
1457 self.focus_output(output);
1458 self.move_column_to_workspace(idx);
1459 }
1460
1461 pub fn switch_workspace_up(&mut self) {
1462 let Some(monitor) = self.active_monitor() else {
1463 return;
1464 };
1465 monitor.switch_workspace_up();
1466 }
1467
1468 pub fn switch_workspace_down(&mut self) {
1469 let Some(monitor) = self.active_monitor() else {
1470 return;
1471 };
1472 monitor.switch_workspace_down();
1473 }
1474
1475 pub fn switch_workspace(&mut self, idx: usize) {
1476 let Some(monitor) = self.active_monitor() else {
1477 return;
1478 };
1479 monitor.switch_workspace(idx, false);
1480 }
1481
1482 pub fn switch_workspace_auto_back_and_forth(&mut self, idx: usize) {
1483 let Some(monitor) = self.active_monitor() else {
1484 return;
1485 };
1486 monitor.switch_workspace_auto_back_and_forth(idx);
1487 }
1488
1489 pub fn switch_workspace_previous(&mut self) {
1490 let Some(monitor) = self.active_monitor() else {
1491 return;
1492 };
1493 monitor.switch_workspace_previous();
1494 }
1495
1496 pub fn consume_into_column(&mut self) {
1497 let Some(monitor) = self.active_monitor() else {
1498 return;
1499 };
1500 monitor.consume_into_column();
1501 }
1502
1503 pub fn expel_from_column(&mut self) {
1504 let Some(monitor) = self.active_monitor() else {
1505 return;
1506 };
1507 monitor.expel_from_column();
1508 }
1509
1510 pub fn center_column(&mut self) {
1511 let Some(monitor) = self.active_monitor() else {
1512 return;
1513 };
1514 monitor.center_column();
1515 }
1516
1517 pub fn focus(&self) -> Option<&W> {
1518 let MonitorSet::Normal {
1519 monitors,
1520 active_monitor_idx,
1521 ..
1522 } = &self.monitor_set
1523 else {
1524 return None;
1525 };
1526
1527 monitors[*active_monitor_idx].focus()
1528 }
1529
1530 /// Returns the window under the cursor and the position of its toplevel surface within the
1531 /// output.
1532 ///
1533 /// `Some((w, Some(p)))` means that the cursor is within the window's input region and can be
1534 /// used for delivering events to the window. `Some((w, None))` means that the cursor is within
1535 /// the window's activation region, but not within the window's input region. For example, the
1536 /// cursor may be on the window's server-side border.
1537 pub fn window_under(
1538 &self,
1539 output: &Output,
1540 pos_within_output: Point<f64, Logical>,
1541 ) -> Option<(&W, Option<Point<f64, Logical>>)> {
1542 let MonitorSet::Normal { monitors, .. } = &self.monitor_set else {
1543 return None;
1544 };
1545
1546 let mon = monitors.iter().find(|mon| &mon.output == output)?;
1547 mon.window_under(pos_within_output)
1548 }
1549
1550 pub fn resize_edges_under(
1551 &self,
1552 output: &Output,
1553 pos_within_output: Point<f64, Logical>,
1554 ) -> Option<ResizeEdge> {
1555 let MonitorSet::Normal { monitors, .. } = &self.monitor_set else {
1556 return None;
1557 };
1558
1559 let mon = monitors.iter().find(|mon| &mon.output == output)?;
1560 mon.resize_edges_under(pos_within_output)
1561 }
1562
1563 #[cfg(test)]
1564 fn verify_invariants(&self) {
1565 use std::collections::HashSet;
1566
1567 use crate::layout::monitor::WorkspaceSwitch;
1568
1569 let mut seen_workspace_id = HashSet::new();
1570 let mut seen_workspace_name = Vec::<String>::new();
1571
1572 let (monitors, &primary_idx, &active_monitor_idx) = match &self.monitor_set {
1573 MonitorSet::Normal {
1574 monitors,
1575 primary_idx,
1576 active_monitor_idx,
1577 } => (monitors, primary_idx, active_monitor_idx),
1578 MonitorSet::NoOutputs { workspaces } => {
1579 for workspace in workspaces {
1580 assert!(
1581 workspace.has_windows() || workspace.name.is_some(),
1582 "with no outputs there cannot be empty unnamed workspaces"
1583 );
1584
1585 assert_eq!(
1586 workspace.base_options, self.options,
1587 "workspace base options must be synchronized with layout"
1588 );
1589
1590 let options = Options::clone(&workspace.base_options)
1591 .adjusted_for_scale(workspace.scale().fractional_scale());
1592 assert_eq!(
1593 &*workspace.options, &options,
1594 "workspace options must be base options adjusted for workspace scale"
1595 );
1596
1597 assert!(
1598 seen_workspace_id.insert(workspace.id()),
1599 "workspace id must be unique"
1600 );
1601
1602 if let Some(name) = &workspace.name {
1603 assert!(
1604 !seen_workspace_name
1605 .iter()
1606 .any(|n| n.eq_ignore_ascii_case(name)),
1607 "workspace name must be unique"
1608 );
1609 seen_workspace_name.push(name.clone());
1610 }
1611
1612 workspace.verify_invariants();
1613 }
1614
1615 return;
1616 }
1617 };
1618
1619 assert!(primary_idx < monitors.len());
1620 assert!(active_monitor_idx < monitors.len());
1621
1622 for (idx, monitor) in monitors.iter().enumerate() {
1623 assert!(
1624 !monitor.workspaces.is_empty(),
1625 "monitor must have at least one workspace"
1626 );
1627 assert!(monitor.active_workspace_idx < monitor.workspaces.len());
1628
1629 assert_eq!(
1630 monitor.options, self.options,
1631 "monitor options must be synchronized with layout"
1632 );
1633
1634 if let Some(WorkspaceSwitch::Animation(anim)) = &monitor.workspace_switch {
1635 let before_idx = anim.from() as usize;
1636 let after_idx = anim.to() as usize;
1637
1638 assert!(before_idx < monitor.workspaces.len());
1639 assert!(after_idx < monitor.workspaces.len());
1640 }
1641
1642 let monitor_id = OutputId::new(&monitor.output);
1643
1644 if idx == primary_idx {
1645 for ws in &monitor.workspaces {
1646 if ws.original_output == monitor_id {
1647 // This is the primary monitor's own workspace.
1648 continue;
1649 }
1650
1651 let own_monitor_exists = monitors
1652 .iter()
1653 .any(|m| OutputId::new(&m.output) == ws.original_output);
1654 assert!(
1655 !own_monitor_exists,
1656 "primary monitor cannot have workspaces for which their own monitor exists"
1657 );
1658 }
1659 } else {
1660 assert!(
1661 monitor
1662 .workspaces
1663 .iter()
1664 .any(|workspace| workspace.original_output == monitor_id),
1665 "secondary monitor must not have any non-own workspaces"
1666 );
1667 }
1668
1669 assert!(
1670 monitor.workspaces.last().unwrap().columns.is_empty(),
1671 "monitor must have an empty workspace in the end"
1672 );
1673
1674 assert!(
1675 monitor.workspaces.last().unwrap().name.is_none(),
1676 "monitor must have an unnamed workspace in the end"
1677 );
1678
1679 // If there's no workspace switch in progress, there can't be any non-last non-active
1680 // empty workspaces.
1681 if monitor.workspace_switch.is_none() {
1682 for (idx, ws) in monitor.workspaces.iter().enumerate().rev().skip(1) {
1683 if idx != monitor.active_workspace_idx {
1684 assert!(
1685 !ws.columns.is_empty() || ws.name.is_some(),
1686 "non-active workspace can't be empty and unnamed except the last one"
1687 );
1688 }
1689 }
1690 }
1691
1692 // FIXME: verify that primary doesn't have any workspaces for which their own monitor
1693 // exists.
1694
1695 for workspace in &monitor.workspaces {
1696 assert_eq!(
1697 workspace.base_options, self.options,
1698 "workspace options must be synchronized with layout"
1699 );
1700
1701 let options = Options::clone(&workspace.base_options)
1702 .adjusted_for_scale(workspace.scale().fractional_scale());
1703 assert_eq!(
1704 &*workspace.options, &options,
1705 "workspace options must be base options adjusted for workspace scale"
1706 );
1707
1708 assert!(
1709 seen_workspace_id.insert(workspace.id()),
1710 "workspace id must be unique"
1711 );
1712
1713 if let Some(name) = &workspace.name {
1714 assert!(
1715 !seen_workspace_name
1716 .iter()
1717 .any(|n| n.eq_ignore_ascii_case(name)),
1718 "workspace name must be unique"
1719 );
1720 seen_workspace_name.push(name.clone());
1721 }
1722
1723 workspace.verify_invariants();
1724 }
1725 }
1726 }
1727
1728 pub fn advance_animations(&mut self, current_time: Duration) {
1729 let _span = tracy_client::span!("Layout::advance_animations");
1730
1731 match &mut self.monitor_set {
1732 MonitorSet::Normal { monitors, .. } => {
1733 for mon in monitors {
1734 mon.advance_animations(current_time);
1735 }
1736 }
1737 MonitorSet::NoOutputs { workspaces, .. } => {
1738 for ws in workspaces {
1739 ws.advance_animations(current_time);
1740 }
1741 }
1742 }
1743 }
1744
1745 pub fn update_render_elements(&mut self, output: &Output) {
1746 let _span = tracy_client::span!("Layout::update_render_elements");
1747
1748 let MonitorSet::Normal {
1749 monitors,
1750 active_monitor_idx,
1751 ..
1752 } = &mut self.monitor_set
1753 else {
1754 error!("update_render_elements called with no monitors");
1755 return;
1756 };
1757
1758 for (idx, mon) in monitors.iter_mut().enumerate() {
1759 if mon.output == *output {
1760 mon.update_render_elements(idx == *active_monitor_idx);
1761 return;
1762 }
1763 }
1764 }
1765
1766 pub fn update_render_elements_all(&mut self) {
1767 let _span = tracy_client::span!("Layout::update_render_elements_all");
1768
1769 let MonitorSet::Normal {
1770 monitors,
1771 active_monitor_idx,
1772 ..
1773 } = &mut self.monitor_set
1774 else {
1775 error!("update_render_elements_all called with no monitors");
1776 return;
1777 };
1778
1779 for (idx, mon) in monitors.iter_mut().enumerate() {
1780 mon.update_render_elements(idx == *active_monitor_idx);
1781 }
1782 }
1783
1784 pub fn update_shaders(&mut self) {
1785 match &mut self.monitor_set {
1786 MonitorSet::Normal { monitors, .. } => {
1787 for mon in monitors {
1788 for ws in &mut mon.workspaces {
1789 ws.update_shaders();
1790 }
1791 }
1792 }
1793 MonitorSet::NoOutputs { workspaces, .. } => {
1794 for ws in workspaces {
1795 ws.update_shaders();
1796 }
1797 }
1798 }
1799 }
1800
1801 pub fn ensure_named_workspace(&mut self, ws_config: &WorkspaceConfig) {
1802 if self.find_workspace_by_name(&ws_config.name.0).is_some() {
1803 return;
1804 }
1805
1806 let options = self.options.clone();
1807
1808 match &mut self.monitor_set {
1809 MonitorSet::Normal {
1810 monitors,
1811 primary_idx,
1812 active_monitor_idx,
1813 } => {
1814 let mon_idx = ws_config
1815 .open_on_output
1816 .as_deref()
1817 .map(|name| {
1818 monitors
1819 .iter_mut()
1820 .position(|monitor| monitor.output.name().eq_ignore_ascii_case(name))
1821 .unwrap_or(*primary_idx)
1822 })
1823 .unwrap_or(*active_monitor_idx);
1824 let mon = &mut monitors[mon_idx];
1825
1826 let ws = Workspace::new_with_config(
1827 mon.output.clone(),
1828 Some(ws_config.clone()),
1829 options,
1830 );
1831 mon.workspaces.insert(0, ws);
1832 mon.active_workspace_idx += 1;
1833 mon.workspace_switch = None;
1834 mon.clean_up_workspaces();
1835 }
1836 MonitorSet::NoOutputs { workspaces } => {
1837 let ws = Workspace::new_with_config_no_outputs(Some(ws_config.clone()), options);
1838 workspaces.insert(0, ws);
1839 }
1840 }
1841 }
1842
1843 pub fn update_config(&mut self, config: &Config) {
1844 let options = Rc::new(Options::from_config(config));
1845
1846 match &mut self.monitor_set {
1847 MonitorSet::Normal { monitors, .. } => {
1848 for mon in monitors {
1849 mon.update_config(options.clone());
1850 }
1851 }
1852 MonitorSet::NoOutputs { workspaces } => {
1853 for ws in workspaces {
1854 ws.update_config(options.clone());
1855 }
1856 }
1857 }
1858
1859 self.options = options;
1860 }
1861
1862 pub fn toggle_width(&mut self) {
1863 let Some(monitor) = self.active_monitor() else {
1864 return;
1865 };
1866 monitor.toggle_width();
1867 }
1868
1869 pub fn toggle_full_width(&mut self) {
1870 let Some(monitor) = self.active_monitor() else {
1871 return;
1872 };
1873 monitor.toggle_full_width();
1874 }
1875
1876 pub fn set_column_width(&mut self, change: SizeChange) {
1877 let Some(monitor) = self.active_monitor() else {
1878 return;
1879 };
1880 monitor.set_column_width(change);
1881 }
1882
1883 pub fn set_window_height(&mut self, change: SizeChange) {
1884 let Some(monitor) = self.active_monitor() else {
1885 return;
1886 };
1887 monitor.set_window_height(change);
1888 }
1889
1890 pub fn reset_window_height(&mut self) {
1891 let Some(monitor) = self.active_monitor() else {
1892 return;
1893 };
1894 monitor.reset_window_height();
1895 }
1896
1897 pub fn focus_output(&mut self, output: &Output) {
1898 if let MonitorSet::Normal {
1899 monitors,
1900 active_monitor_idx,
1901 ..
1902 } = &mut self.monitor_set
1903 {
1904 for (idx, mon) in monitors.iter().enumerate() {
1905 if &mon.output == output {
1906 *active_monitor_idx = idx;
1907 return;
1908 }
1909 }
1910 }
1911 }
1912
1913 pub fn move_to_output(&mut self, output: &Output) {
1914 if let MonitorSet::Normal {
1915 monitors,
1916 active_monitor_idx,
1917 ..
1918 } = &mut self.monitor_set
1919 {
1920 let new_idx = monitors
1921 .iter()
1922 .position(|mon| &mon.output == output)
1923 .unwrap();
1924
1925 let current = &mut monitors[*active_monitor_idx];
1926 let ws = current.active_workspace();
1927 if !ws.has_windows() {
1928 return;
1929 }
1930 let column = &ws.columns[ws.active_column_idx];
1931 let width = column.width;
1932 let is_full_width = column.is_full_width;
1933 let window = ws
1934 .remove_tile_by_idx(ws.active_column_idx, column.active_tile_idx, None)
1935 .into_window();
1936
1937 let workspace_idx = monitors[new_idx].active_workspace_idx;
1938 self.add_window_by_idx(new_idx, workspace_idx, window, true, width, is_full_width);
1939 }
1940 }
1941
1942 pub fn move_column_to_output(&mut self, output: &Output) {
1943 if let MonitorSet::Normal {
1944 monitors,
1945 active_monitor_idx,
1946 ..
1947 } = &mut self.monitor_set
1948 {
1949 let new_idx = monitors
1950 .iter()
1951 .position(|mon| &mon.output == output)
1952 .unwrap();
1953
1954 let current = &mut monitors[*active_monitor_idx];
1955 let ws = current.active_workspace();
1956 if !ws.has_windows() {
1957 return;
1958 }
1959 let column = ws.remove_column_by_idx(ws.active_column_idx);
1960
1961 let workspace_idx = monitors[new_idx].active_workspace_idx;
1962 self.add_column_by_idx(new_idx, workspace_idx, column, true);
1963 }
1964 }
1965
1966 pub fn move_window_to_output(&mut self, window: &W::Id, output: &Output) {
1967 let mut width = None;
1968 let mut is_full_width = false;
1969
1970 if let MonitorSet::Normal { monitors, .. } = &mut self.monitor_set {
1971 for mon in &*monitors {
1972 for ws in &mon.workspaces {
1973 for col in &ws.columns {
1974 if col.contains(window) {
1975 width = Some(col.width);
1976 is_full_width = col.is_full_width;
1977 break;
1978 }
1979 }
1980 }
1981 }
1982 }
1983
1984 let Some(width) = width else { return };
1985
1986 let window = self.remove_window(window).unwrap();
1987
1988 if let MonitorSet::Normal { monitors, .. } = &mut self.monitor_set {
1989 let new_idx = monitors
1990 .iter()
1991 .position(|mon| &mon.output == output)
1992 .unwrap();
1993
1994 let workspace_idx = monitors[new_idx].active_workspace_idx;
1995 // FIXME: activate only if it was already active and focused.
1996 self.add_window_by_idx(new_idx, workspace_idx, window, true, width, is_full_width);
1997 }
1998 }
1999
2000 pub fn move_workspace_to_output(&mut self, output: &Output) {
2001 let MonitorSet::Normal {
2002 monitors,
2003 active_monitor_idx,
2004 ..
2005 } = &mut self.monitor_set
2006 else {
2007 return;
2008 };
2009
2010 let current = &mut monitors[*active_monitor_idx];
2011 if current.active_workspace_idx == current.workspaces.len() - 1 {
2012 // Insert a new empty workspace.
2013 let ws = Workspace::new(current.output.clone(), current.options.clone());
2014 current.workspaces.push(ws);
2015 }
2016 let mut ws = current.workspaces.remove(current.active_workspace_idx);
2017 current.active_workspace_idx = current.active_workspace_idx.saturating_sub(1);
2018 current.workspace_switch = None;
2019 current.clean_up_workspaces();
2020
2021 ws.set_output(Some(output.clone()));
2022 ws.original_output = OutputId::new(output);
2023
2024 let target_idx = monitors
2025 .iter()
2026 .position(|mon| &mon.output == output)
2027 .unwrap();
2028 let target = &mut monitors[target_idx];
2029
2030 target.previous_workspace_id = Some(target.workspaces[target.active_workspace_idx].id());
2031
2032 // Insert the workspace after the currently active one. Unless the currently active one is
2033 // the last empty workspace, then insert before.
2034 let target_ws_idx = min(target.active_workspace_idx + 1, target.workspaces.len() - 1);
2035 target.workspaces.insert(target_ws_idx, ws);
2036 target.active_workspace_idx = target_ws_idx;
2037 target.workspace_switch = None;
2038 target.clean_up_workspaces();
2039
2040 *active_monitor_idx = target_idx;
2041 }
2042
2043 pub fn set_fullscreen(&mut self, window: &W::Id, is_fullscreen: bool) {
2044 match &mut self.monitor_set {
2045 MonitorSet::Normal { monitors, .. } => {
2046 for mon in monitors {
2047 for ws in &mut mon.workspaces {
2048 if ws.has_window(window) {
2049 ws.set_fullscreen(window, is_fullscreen);
2050 return;
2051 }
2052 }
2053 }
2054 }
2055 MonitorSet::NoOutputs { workspaces, .. } => {
2056 for ws in workspaces {
2057 if ws.has_window(window) {
2058 ws.set_fullscreen(window, is_fullscreen);
2059 return;
2060 }
2061 }
2062 }
2063 }
2064 }
2065
2066 pub fn toggle_fullscreen(&mut self, window: &W::Id) {
2067 match &mut self.monitor_set {
2068 MonitorSet::Normal { monitors, .. } => {
2069 for mon in monitors {
2070 for ws in &mut mon.workspaces {
2071 if ws.has_window(window) {
2072 ws.toggle_fullscreen(window);
2073 return;
2074 }
2075 }
2076 }
2077 }
2078 MonitorSet::NoOutputs { workspaces, .. } => {
2079 for ws in workspaces {
2080 if ws.has_window(window) {
2081 ws.toggle_fullscreen(window);
2082 return;
2083 }
2084 }
2085 }
2086 }
2087 }
2088
2089 pub fn workspace_switch_gesture_begin(&mut self, output: &Output, is_touchpad: bool) {
2090 let monitors = match &mut self.monitor_set {
2091 MonitorSet::Normal { monitors, .. } => monitors,
2092 MonitorSet::NoOutputs { .. } => unreachable!(),
2093 };
2094
2095 for monitor in monitors {
2096 // Cancel the gesture on other outputs.
2097 if &monitor.output != output {
2098 monitor.workspace_switch_gesture_end(true, None);
2099 continue;
2100 }
2101
2102 monitor.workspace_switch_gesture_begin(is_touchpad);
2103 }
2104 }
2105
2106 pub fn workspace_switch_gesture_update(
2107 &mut self,
2108 delta_y: f64,
2109 timestamp: Duration,
2110 is_touchpad: bool,
2111 ) -> Option<Option<Output>> {
2112 let monitors = match &mut self.monitor_set {
2113 MonitorSet::Normal { monitors, .. } => monitors,
2114 MonitorSet::NoOutputs { .. } => return None,
2115 };
2116
2117 for monitor in monitors {
2118 if let Some(refresh) =
2119 monitor.workspace_switch_gesture_update(delta_y, timestamp, is_touchpad)
2120 {
2121 if refresh {
2122 return Some(Some(monitor.output.clone()));
2123 } else {
2124 return Some(None);
2125 }
2126 }
2127 }
2128
2129 None
2130 }
2131
2132 pub fn workspace_switch_gesture_end(
2133 &mut self,
2134 cancelled: bool,
2135 is_touchpad: Option<bool>,
2136 ) -> Option<Output> {
2137 let monitors = match &mut self.monitor_set {
2138 MonitorSet::Normal { monitors, .. } => monitors,
2139 MonitorSet::NoOutputs { .. } => return None,
2140 };
2141
2142 for monitor in monitors {
2143 if monitor.workspace_switch_gesture_end(cancelled, is_touchpad) {
2144 return Some(monitor.output.clone());
2145 }
2146 }
2147
2148 None
2149 }
2150
2151 pub fn view_offset_gesture_begin(&mut self, output: &Output, is_touchpad: bool) {
2152 let monitors = match &mut self.monitor_set {
2153 MonitorSet::Normal { monitors, .. } => monitors,
2154 MonitorSet::NoOutputs { .. } => unreachable!(),
2155 };
2156
2157 for monitor in monitors {
2158 for (idx, ws) in monitor.workspaces.iter_mut().enumerate() {
2159 // Cancel the gesture on other workspaces.
2160 if &monitor.output != output || idx != monitor.active_workspace_idx {
2161 ws.view_offset_gesture_end(true, None);
2162 continue;
2163 }
2164
2165 ws.view_offset_gesture_begin(is_touchpad);
2166 }
2167 }
2168 }
2169
2170 pub fn view_offset_gesture_update(
2171 &mut self,
2172 delta_x: f64,
2173 timestamp: Duration,
2174 is_touchpad: bool,
2175 ) -> Option<Option<Output>> {
2176 let monitors = match &mut self.monitor_set {
2177 MonitorSet::Normal { monitors, .. } => monitors,
2178 MonitorSet::NoOutputs { .. } => return None,
2179 };
2180
2181 for monitor in monitors {
2182 for ws in &mut monitor.workspaces {
2183 if let Some(refresh) =
2184 ws.view_offset_gesture_update(delta_x, timestamp, is_touchpad)
2185 {
2186 if refresh {
2187 return Some(Some(monitor.output.clone()));
2188 } else {
2189 return Some(None);
2190 }
2191 }
2192 }
2193 }
2194
2195 None
2196 }
2197
2198 pub fn view_offset_gesture_end(
2199 &mut self,
2200 cancelled: bool,
2201 is_touchpad: Option<bool>,
2202 ) -> Option<Output> {
2203 let monitors = match &mut self.monitor_set {
2204 MonitorSet::Normal { monitors, .. } => monitors,
2205 MonitorSet::NoOutputs { .. } => return None,
2206 };
2207
2208 for monitor in monitors {
2209 for ws in &mut monitor.workspaces {
2210 if ws.view_offset_gesture_end(cancelled, is_touchpad) {
2211 return Some(monitor.output.clone());
2212 }
2213 }
2214 }
2215
2216 None
2217 }
2218
2219 pub fn interactive_resize_begin(&mut self, window: W::Id, edges: ResizeEdge) -> bool {
2220 match &mut self.monitor_set {
2221 MonitorSet::Normal { monitors, .. } => {
2222 for mon in monitors {
2223 for ws in &mut mon.workspaces {
2224 if ws.has_window(&window) {
2225 return ws.interactive_resize_begin(window, edges);
2226 }
2227 }
2228 }
2229 }
2230 MonitorSet::NoOutputs { workspaces, .. } => {
2231 for ws in workspaces {
2232 if ws.has_window(&window) {
2233 return ws.interactive_resize_begin(window, edges);
2234 }
2235 }
2236 }
2237 }
2238
2239 false
2240 }
2241
2242 pub fn interactive_resize_update(
2243 &mut self,
2244 window: &W::Id,
2245 delta: Point<f64, Logical>,
2246 ) -> bool {
2247 match &mut self.monitor_set {
2248 MonitorSet::Normal { monitors, .. } => {
2249 for mon in monitors {
2250 for ws in &mut mon.workspaces {
2251 if ws.has_window(window) {
2252 return ws.interactive_resize_update(window, delta);
2253 }
2254 }
2255 }
2256 }
2257 MonitorSet::NoOutputs { workspaces, .. } => {
2258 for ws in workspaces {
2259 if ws.has_window(window) {
2260 return ws.interactive_resize_update(window, delta);
2261 }
2262 }
2263 }
2264 }
2265
2266 false
2267 }
2268
2269 pub fn interactive_resize_end(&mut self, window: &W::Id) {
2270 match &mut self.monitor_set {
2271 MonitorSet::Normal { monitors, .. } => {
2272 for mon in monitors {
2273 for ws in &mut mon.workspaces {
2274 if ws.has_window(window) {
2275 ws.interactive_resize_end(Some(window));
2276 return;
2277 }
2278 }
2279 }
2280 }
2281 MonitorSet::NoOutputs { workspaces, .. } => {
2282 for ws in workspaces {
2283 if ws.has_window(window) {
2284 ws.interactive_resize_end(Some(window));
2285 return;
2286 }
2287 }
2288 }
2289 }
2290 }
2291
2292 pub fn move_workspace_down(&mut self) {
2293 let Some(monitor) = self.active_monitor() else {
2294 return;
2295 };
2296 monitor.move_workspace_down();
2297 }
2298
2299 pub fn move_workspace_up(&mut self) {
2300 let Some(monitor) = self.active_monitor() else {
2301 return;
2302 };
2303 monitor.move_workspace_up();
2304 }
2305
2306 pub fn start_open_animation_for_window(&mut self, window: &W::Id) {
2307 match &mut self.monitor_set {
2308 MonitorSet::Normal { monitors, .. } => {
2309 for mon in monitors {
2310 for ws in &mut mon.workspaces {
2311 for col in &mut ws.columns {
2312 for tile in &mut col.tiles {
2313 if tile.window().id() == window {
2314 tile.start_open_animation();
2315 return;
2316 }
2317 }
2318 }
2319 }
2320 }
2321 }
2322 MonitorSet::NoOutputs { workspaces, .. } => {
2323 for ws in workspaces {
2324 for col in &mut ws.columns {
2325 for tile in &mut col.tiles {
2326 if tile.window().id() == window {
2327 tile.start_open_animation();
2328 return;
2329 }
2330 }
2331 }
2332 }
2333 }
2334 }
2335 }
2336
2337 pub fn store_unmap_snapshot(&mut self, renderer: &mut GlesRenderer, window: &W::Id) {
2338 let _span = tracy_client::span!("Layout::store_unmap_snapshot");
2339
2340 match &mut self.monitor_set {
2341 MonitorSet::Normal { monitors, .. } => {
2342 for mon in monitors {
2343 for ws in &mut mon.workspaces {
2344 if ws.has_window(window) {
2345 ws.store_unmap_snapshot_if_empty(renderer, window);
2346 return;
2347 }
2348 }
2349 }
2350 }
2351 MonitorSet::NoOutputs { workspaces, .. } => {
2352 for ws in workspaces {
2353 if ws.has_window(window) {
2354 ws.store_unmap_snapshot_if_empty(renderer, window);
2355 return;
2356 }
2357 }
2358 }
2359 }
2360 }
2361
2362 pub fn clear_unmap_snapshot(&mut self, window: &W::Id) {
2363 match &mut self.monitor_set {
2364 MonitorSet::Normal { monitors, .. } => {
2365 for mon in monitors {
2366 for ws in &mut mon.workspaces {
2367 if ws.has_window(window) {
2368 ws.clear_unmap_snapshot(window);
2369 return;
2370 }
2371 }
2372 }
2373 }
2374 MonitorSet::NoOutputs { workspaces, .. } => {
2375 for ws in workspaces {
2376 if ws.has_window(window) {
2377 ws.clear_unmap_snapshot(window);
2378 return;
2379 }
2380 }
2381 }
2382 }
2383 }
2384
2385 pub fn start_close_animation_for_window(
2386 &mut self,
2387 renderer: &mut GlesRenderer,
2388 window: &W::Id,
2389 ) {
2390 let _span = tracy_client::span!("Layout::start_close_animation_for_window");
2391
2392 match &mut self.monitor_set {
2393 MonitorSet::Normal { monitors, .. } => {
2394 for mon in monitors {
2395 for ws in &mut mon.workspaces {
2396 if ws.has_window(window) {
2397 ws.start_close_animation_for_window(renderer, window);
2398 return;
2399 }
2400 }
2401 }
2402 }
2403 MonitorSet::NoOutputs { workspaces, .. } => {
2404 for ws in workspaces {
2405 if ws.has_window(window) {
2406 ws.start_close_animation_for_window(renderer, window);
2407 return;
2408 }
2409 }
2410 }
2411 }
2412 }
2413
2414 pub fn refresh(&mut self) {
2415 let _span = tracy_client::span!("Layout::refresh");
2416
2417 match &mut self.monitor_set {
2418 MonitorSet::Normal {
2419 monitors,
2420 active_monitor_idx,
2421 ..
2422 } => {
2423 for (idx, mon) in monitors.iter_mut().enumerate() {
2424 let is_active = idx == *active_monitor_idx;
2425 for (ws_idx, ws) in mon.workspaces.iter_mut().enumerate() {
2426 ws.refresh(is_active);
2427
2428 // Cancel the view offset gesture after workspace switches, moves, etc.
2429 if ws_idx != mon.active_workspace_idx {
2430 ws.view_offset_gesture_end(false, None);
2431 }
2432 }
2433 }
2434 }
2435 MonitorSet::NoOutputs { workspaces, .. } => {
2436 for ws in workspaces {
2437 ws.refresh(false);
2438 ws.view_offset_gesture_end(false, None);
2439 }
2440 }
2441 }
2442 }
2443
2444 pub fn ipc_workspaces(&self) -> Vec<niri_ipc::Workspace> {
2445 match &self.monitor_set {
2446 MonitorSet::Normal {
2447 monitors,
2448 primary_idx: _,
2449 active_monitor_idx: _,
2450 } => {
2451 let mut workspaces = Vec::new();
2452
2453 for monitor in monitors {
2454 for (idx, workspace) in monitor.workspaces.iter().enumerate() {
2455 workspaces.push(niri_ipc::Workspace {
2456 idx: u8::try_from(idx + 1).unwrap_or(u8::MAX),
2457 name: workspace.name.clone(),
2458 output: Some(monitor.output.name()),
2459 is_active: monitor.active_workspace_idx == idx,
2460 })
2461 }
2462 }
2463
2464 workspaces
2465 }
2466 MonitorSet::NoOutputs { workspaces } => workspaces
2467 .iter()
2468 .enumerate()
2469 .map(|(idx, ws)| niri_ipc::Workspace {
2470 idx: u8::try_from(idx + 1).unwrap_or(u8::MAX),
2471 name: ws.name.clone(),
2472 output: None,
2473 is_active: false,
2474 })
2475 .collect(),
2476 }
2477 }
2478}
2479
2480impl<W: LayoutElement> Default for MonitorSet<W> {
2481 fn default() -> Self {
2482 Self::NoOutputs { workspaces: vec![] }
2483 }
2484}
2485
2486#[cfg(test)]
2487mod tests {
2488 use std::cell::Cell;
2489
2490 use niri_config::{FloatOrInt, WorkspaceName};
2491 use proptest::prelude::*;
2492 use proptest_derive::Arbitrary;
2493 use smithay::output::{Mode, PhysicalProperties, Subpixel};
2494 use smithay::utils::Rectangle;
2495
2496 use super::*;
2497 use crate::utils::round_logical_in_physical;
2498
2499 impl<W: LayoutElement> Default for Layout<W> {
2500 fn default() -> Self {
2501 Self::with_options(Default::default())
2502 }
2503 }
2504
2505 #[derive(Debug)]
2506 struct TestWindowInner {
2507 id: usize,
2508 bbox: Cell<Rectangle<i32, Logical>>,
2509 initial_bbox: Rectangle<i32, Logical>,
2510 requested_size: Cell<Option<Size<i32, Logical>>>,
2511 min_size: Size<i32, Logical>,
2512 max_size: Size<i32, Logical>,
2513 pending_fullscreen: Cell<bool>,
2514 }
2515
2516 #[derive(Debug, Clone)]
2517 struct TestWindow(Rc<TestWindowInner>);
2518
2519 impl TestWindow {
2520 fn new(
2521 id: usize,
2522 bbox: Rectangle<i32, Logical>,
2523 min_size: Size<i32, Logical>,
2524 max_size: Size<i32, Logical>,
2525 ) -> Self {
2526 Self(Rc::new(TestWindowInner {
2527 id,
2528 bbox: Cell::new(bbox),
2529 initial_bbox: bbox,
2530 requested_size: Cell::new(None),
2531 min_size,
2532 max_size,
2533 pending_fullscreen: Cell::new(false),
2534 }))
2535 }
2536
2537 fn communicate(&self) -> bool {
2538 if let Some(size) = self.0.requested_size.take() {
2539 assert!(size.w >= 0);
2540 assert!(size.h >= 0);
2541
2542 let mut new_bbox = self.0.initial_bbox;
2543 if size.w != 0 {
2544 new_bbox.size.w = size.w;
2545 }
2546 if size.h != 0 {
2547 new_bbox.size.h = size.h;
2548 }
2549
2550 if self.0.bbox.get() != new_bbox {
2551 self.0.bbox.set(new_bbox);
2552 return true;
2553 }
2554 }
2555
2556 false
2557 }
2558 }
2559
2560 impl LayoutElement for TestWindow {
2561 type Id = usize;
2562
2563 fn id(&self) -> &Self::Id {
2564 &self.0.id
2565 }
2566
2567 fn size(&self) -> Size<i32, Logical> {
2568 self.0.bbox.get().size
2569 }
2570
2571 fn buf_loc(&self) -> Point<i32, Logical> {
2572 (0, 0).into()
2573 }
2574
2575 fn is_in_input_region(&self, _point: Point<f64, Logical>) -> bool {
2576 false
2577 }
2578
2579 fn render<R: NiriRenderer>(
2580 &self,
2581 _renderer: &mut R,
2582 _location: Point<f64, Logical>,
2583 _scale: Scale<f64>,
2584 _alpha: f32,
2585 _target: RenderTarget,
2586 ) -> SplitElements<LayoutElementRenderElement<R>> {
2587 SplitElements::default()
2588 }
2589
2590 fn request_size(&mut self, size: Size<i32, Logical>, _animate: bool) {
2591 self.0.requested_size.set(Some(size));
2592 self.0.pending_fullscreen.set(false);
2593 }
2594
2595 fn request_fullscreen(&self, _size: Size<i32, Logical>) {
2596 self.0.pending_fullscreen.set(true);
2597 }
2598
2599 fn min_size(&self) -> Size<i32, Logical> {
2600 self.0.min_size
2601 }
2602
2603 fn max_size(&self) -> Size<i32, Logical> {
2604 self.0.max_size
2605 }
2606
2607 fn is_wl_surface(&self, _wl_surface: &WlSurface) -> bool {
2608 false
2609 }
2610
2611 fn set_preferred_scale_transform(&self, _scale: output::Scale, _transform: Transform) {}
2612
2613 fn has_ssd(&self) -> bool {
2614 false
2615 }
2616
2617 fn output_enter(&self, _output: &Output) {}
2618
2619 fn output_leave(&self, _output: &Output) {}
2620
2621 fn set_offscreen_element_id(&self, _id: Option<Id>) {}
2622
2623 fn set_activated(&mut self, _active: bool) {}
2624
2625 fn set_bounds(&self, _bounds: Size<i32, Logical>) {}
2626
2627 fn send_pending_configure(&mut self) {}
2628
2629 fn set_active_in_column(&mut self, _active: bool) {}
2630
2631 fn is_fullscreen(&self) -> bool {
2632 false
2633 }
2634
2635 fn is_pending_fullscreen(&self) -> bool {
2636 self.0.pending_fullscreen.get()
2637 }
2638
2639 fn refresh(&self) {}
2640
2641 fn rules(&self) -> &ResolvedWindowRules {
2642 static EMPTY: ResolvedWindowRules = ResolvedWindowRules::empty();
2643 &EMPTY
2644 }
2645
2646 fn animation_snapshot(&self) -> Option<&LayoutElementRenderSnapshot> {
2647 None
2648 }
2649
2650 fn take_animation_snapshot(&mut self) -> Option<LayoutElementRenderSnapshot> {
2651 None
2652 }
2653
2654 fn set_interactive_resize(&mut self, _data: Option<InteractiveResizeData>) {}
2655
2656 fn cancel_interactive_resize(&mut self) {}
2657
2658 fn update_interactive_resize(&mut self, _serial: Serial) {}
2659
2660 fn interactive_resize_data(&self) -> Option<InteractiveResizeData> {
2661 None
2662 }
2663 }
2664
2665 fn arbitrary_bbox() -> impl Strategy<Value = Rectangle<i32, Logical>> {
2666 any::<(i16, i16, u16, u16)>().prop_map(|(x, y, w, h)| {
2667 let loc: Point<i32, _> = Point::from((x.into(), y.into()));
2668 let size: Size<i32, _> = Size::from((w.into(), h.into()));
2669 Rectangle::from_loc_and_size(loc, size)
2670 })
2671 }
2672
2673 fn arbitrary_size_change() -> impl Strategy<Value = SizeChange> {
2674 prop_oneof![
2675 (0..).prop_map(SizeChange::SetFixed),
2676 (0f64..).prop_map(SizeChange::SetProportion),
2677 any::<i32>().prop_map(SizeChange::AdjustFixed),
2678 any::<f64>().prop_map(SizeChange::AdjustProportion),
2679 ]
2680 }
2681
2682 fn arbitrary_min_max() -> impl Strategy<Value = (i32, i32)> {
2683 prop_oneof![
2684 Just((0, 0)),
2685 (1..65536).prop_map(|n| (n, n)),
2686 (1..65536).prop_map(|min| (min, 0)),
2687 (1..).prop_map(|max| (0, max)),
2688 (1..65536, 1..).prop_map(|(min, max): (i32, i32)| (min, max.max(min))),
2689 ]
2690 }
2691
2692 fn arbitrary_min_max_size() -> impl Strategy<Value = (Size<i32, Logical>, Size<i32, Logical>)> {
2693 (arbitrary_min_max(), arbitrary_min_max()).prop_map(|((min_w, max_w), (min_h, max_h))| {
2694 let min_size = Size::from((min_w, min_h));
2695 let max_size = Size::from((max_w, max_h));
2696 (min_size, max_size)
2697 })
2698 }
2699
2700 fn arbitrary_view_offset_gesture_delta() -> impl Strategy<Value = f64> {
2701 prop_oneof![(-10f64..10f64), (-50000f64..50000f64),]
2702 }
2703
2704 fn arbitrary_resize_edge() -> impl Strategy<Value = ResizeEdge> {
2705 prop_oneof![
2706 Just(ResizeEdge::RIGHT),
2707 Just(ResizeEdge::BOTTOM),
2708 Just(ResizeEdge::LEFT),
2709 Just(ResizeEdge::TOP),
2710 Just(ResizeEdge::BOTTOM_RIGHT),
2711 Just(ResizeEdge::BOTTOM_LEFT),
2712 Just(ResizeEdge::TOP_RIGHT),
2713 Just(ResizeEdge::TOP_LEFT),
2714 Just(ResizeEdge::empty()),
2715 ]
2716 }
2717
2718 fn arbitrary_scale() -> impl Strategy<Value = f64> {
2719 prop_oneof![Just(1.), Just(1.5), Just(2.),]
2720 }
2721
2722 #[derive(Debug, Clone, Copy, Arbitrary)]
2723 enum Op {
2724 AddOutput(#[proptest(strategy = "1..=5usize")] usize),
2725 AddScaledOutput {
2726 #[proptest(strategy = "1..=5usize")]
2727 id: usize,
2728 #[proptest(strategy = "arbitrary_scale()")]
2729 scale: f64,
2730 },
2731 RemoveOutput(#[proptest(strategy = "1..=5usize")] usize),
2732 FocusOutput(#[proptest(strategy = "1..=5usize")] usize),
2733 AddNamedWorkspace {
2734 #[proptest(strategy = "1..=5usize")]
2735 ws_name: usize,
2736 #[proptest(strategy = "prop::option::of(1..=5usize)")]
2737 output_name: Option<usize>,
2738 },
2739 UnnameWorkspace {
2740 #[proptest(strategy = "1..=5usize")]
2741 ws_name: usize,
2742 },
2743 AddWindow {
2744 #[proptest(strategy = "1..=5usize")]
2745 id: usize,
2746 #[proptest(strategy = "arbitrary_bbox()")]
2747 bbox: Rectangle<i32, Logical>,
2748 #[proptest(strategy = "arbitrary_min_max_size()")]
2749 min_max_size: (Size<i32, Logical>, Size<i32, Logical>),
2750 },
2751 AddWindowRightOf {
2752 #[proptest(strategy = "1..=5usize")]
2753 id: usize,
2754 #[proptest(strategy = "1..=5usize")]
2755 right_of_id: usize,
2756 #[proptest(strategy = "arbitrary_bbox()")]
2757 bbox: Rectangle<i32, Logical>,
2758 #[proptest(strategy = "arbitrary_min_max_size()")]
2759 min_max_size: (Size<i32, Logical>, Size<i32, Logical>),
2760 },
2761 AddWindowToNamedWorkspace {
2762 #[proptest(strategy = "1..=5usize")]
2763 id: usize,
2764 #[proptest(strategy = "1..=5usize")]
2765 ws_name: usize,
2766 #[proptest(strategy = "arbitrary_bbox()")]
2767 bbox: Rectangle<i32, Logical>,
2768 #[proptest(strategy = "arbitrary_min_max_size()")]
2769 min_max_size: (Size<i32, Logical>, Size<i32, Logical>),
2770 },
2771 CloseWindow(#[proptest(strategy = "1..=5usize")] usize),
2772 FullscreenWindow(#[proptest(strategy = "1..=5usize")] usize),
2773 SetFullscreenWindow {
2774 #[proptest(strategy = "1..=5usize")]
2775 window: usize,
2776 is_fullscreen: bool,
2777 },
2778 FocusColumnLeft,
2779 FocusColumnRight,
2780 FocusColumnFirst,
2781 FocusColumnLast,
2782 FocusColumnRightOrFirst,
2783 FocusColumnLeftOrLast,
2784 FocusWindowOrMonitorUp(#[proptest(strategy = "1..=2u8")] u8),
2785 FocusWindowOrMonitorDown(#[proptest(strategy = "1..=2u8")] u8),
2786 FocusColumnOrMonitorLeft(#[proptest(strategy = "1..=2u8")] u8),
2787 FocusColumnOrMonitorRight(#[proptest(strategy = "1..=2u8")] u8),
2788 FocusWindowDown,
2789 FocusWindowUp,
2790 FocusWindowDownOrColumnLeft,
2791 FocusWindowDownOrColumnRight,
2792 FocusWindowUpOrColumnLeft,
2793 FocusWindowUpOrColumnRight,
2794 FocusWindowOrWorkspaceDown,
2795 FocusWindowOrWorkspaceUp,
2796 MoveColumnLeft,
2797 MoveColumnRight,
2798 MoveColumnToFirst,
2799 MoveColumnToLast,
2800 MoveWindowDown,
2801 MoveWindowUp,
2802 MoveWindowDownOrToWorkspaceDown,
2803 MoveWindowUpOrToWorkspaceUp,
2804 ConsumeOrExpelWindowLeft,
2805 ConsumeOrExpelWindowRight,
2806 ConsumeWindowIntoColumn,
2807 ExpelWindowFromColumn,
2808 CenterColumn,
2809 FocusWorkspaceDown,
2810 FocusWorkspaceUp,
2811 FocusWorkspace(#[proptest(strategy = "0..=4usize")] usize),
2812 FocusWorkspaceAutoBackAndForth(#[proptest(strategy = "0..=4usize")] usize),
2813 FocusWorkspacePrevious,
2814 MoveWindowToWorkspaceDown,
2815 MoveWindowToWorkspaceUp,
2816 MoveWindowToWorkspace(#[proptest(strategy = "0..=4usize")] usize),
2817 MoveColumnToWorkspaceDown,
2818 MoveColumnToWorkspaceUp,
2819 MoveColumnToWorkspace(#[proptest(strategy = "0..=4usize")] usize),
2820 MoveWorkspaceDown,
2821 MoveWorkspaceUp,
2822 MoveWindowToOutput(#[proptest(strategy = "1..=5u8")] u8),
2823 MoveColumnToOutput(#[proptest(strategy = "1..=5u8")] u8),
2824 SwitchPresetColumnWidth,
2825 MaximizeColumn,
2826 SetColumnWidth(#[proptest(strategy = "arbitrary_size_change()")] SizeChange),
2827 SetWindowHeight(#[proptest(strategy = "arbitrary_size_change()")] SizeChange),
2828 ResetWindowHeight,
2829 Communicate(#[proptest(strategy = "1..=5usize")] usize),
2830 MoveWorkspaceToOutput(#[proptest(strategy = "1..=5u8")] u8),
2831 ViewOffsetGestureBegin {
2832 #[proptest(strategy = "1..=5usize")]
2833 output_idx: usize,
2834 is_touchpad: bool,
2835 },
2836 ViewOffsetGestureUpdate {
2837 #[proptest(strategy = "arbitrary_view_offset_gesture_delta()")]
2838 delta: f64,
2839 timestamp: Duration,
2840 is_touchpad: bool,
2841 },
2842 ViewOffsetGestureEnd {
2843 is_touchpad: Option<bool>,
2844 },
2845 WorkspaceSwitchGestureBegin {
2846 #[proptest(strategy = "1..=5usize")]
2847 output_idx: usize,
2848 is_touchpad: bool,
2849 },
2850 WorkspaceSwitchGestureUpdate {
2851 #[proptest(strategy = "-400f64..400f64")]
2852 delta: f64,
2853 timestamp: Duration,
2854 is_touchpad: bool,
2855 },
2856 WorkspaceSwitchGestureEnd {
2857 cancelled: bool,
2858 is_touchpad: Option<bool>,
2859 },
2860 InteractiveResizeBegin {
2861 #[proptest(strategy = "1..=5usize")]
2862 window: usize,
2863 #[proptest(strategy = "arbitrary_resize_edge()")]
2864 edges: ResizeEdge,
2865 },
2866 InteractiveResizeUpdate {
2867 #[proptest(strategy = "1..=5usize")]
2868 window: usize,
2869 #[proptest(strategy = "-20000f64..20000f64")]
2870 dx: f64,
2871 #[proptest(strategy = "-20000f64..20000f64")]
2872 dy: f64,
2873 },
2874 InteractiveResizeEnd {
2875 #[proptest(strategy = "1..=5usize")]
2876 window: usize,
2877 },
2878 }
2879
2880 impl Op {
2881 fn apply(self, layout: &mut Layout<TestWindow>) {
2882 match self {
2883 Op::AddOutput(id) => {
2884 let name = format!("output{id}");
2885 if layout.outputs().any(|o| o.name() == name) {
2886 return;
2887 }
2888
2889 let output = Output::new(
2890 name,
2891 PhysicalProperties {
2892 size: Size::from((1280, 720)),
2893 subpixel: Subpixel::Unknown,
2894 make: String::new(),
2895 model: String::new(),
2896 },
2897 );
2898 output.change_current_state(
2899 Some(Mode {
2900 size: Size::from((1280, 720)),
2901 refresh: 60000,
2902 }),
2903 None,
2904 None,
2905 None,
2906 );
2907 layout.add_output(output.clone());
2908 }
2909 Op::AddScaledOutput { id, scale } => {
2910 let name = format!("output{id}");
2911 if layout.outputs().any(|o| o.name() == name) {
2912 return;
2913 }
2914
2915 let output = Output::new(
2916 name,
2917 PhysicalProperties {
2918 size: Size::from((1280, 720)),
2919 subpixel: Subpixel::Unknown,
2920 make: String::new(),
2921 model: String::new(),
2922 },
2923 );
2924 output.change_current_state(
2925 Some(Mode {
2926 size: Size::from((1280, 720)),
2927 refresh: 60000,
2928 }),
2929 None,
2930 Some(smithay::output::Scale::Fractional(scale)),
2931 None,
2932 );
2933 layout.add_output(output.clone());
2934 }
2935 Op::RemoveOutput(id) => {
2936 let name = format!("output{id}");
2937 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
2938 return;
2939 };
2940
2941 layout.remove_output(&output);
2942 }
2943 Op::FocusOutput(id) => {
2944 let name = format!("output{id}");
2945 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
2946 return;
2947 };
2948
2949 layout.focus_output(&output);
2950 }
2951 Op::AddNamedWorkspace {
2952 ws_name,
2953 output_name,
2954 } => {
2955 layout.ensure_named_workspace(&WorkspaceConfig {
2956 name: WorkspaceName(format!("ws{ws_name}")),
2957 open_on_output: output_name.map(|name| format!("output{name}")),
2958 });
2959 }
2960 Op::UnnameWorkspace { ws_name } => {
2961 layout.unname_workspace(&format!("ws{ws_name}"));
2962 }
2963 Op::AddWindow {
2964 id,
2965 bbox,
2966 min_max_size,
2967 } => {
2968 match &mut layout.monitor_set {
2969 MonitorSet::Normal { monitors, .. } => {
2970 for mon in monitors {
2971 for ws in &mut mon.workspaces {
2972 for win in ws.windows() {
2973 if win.0.id == id {
2974 return;
2975 }
2976 }
2977 }
2978 }
2979 }
2980 MonitorSet::NoOutputs { workspaces, .. } => {
2981 for ws in workspaces {
2982 for win in ws.windows() {
2983 if win.0.id == id {
2984 return;
2985 }
2986 }
2987 }
2988 }
2989 }
2990
2991 let win = TestWindow::new(id, bbox, min_max_size.0, min_max_size.1);
2992 layout.add_window(win, None, false);
2993 }
2994 Op::AddWindowRightOf {
2995 id,
2996 right_of_id,
2997 bbox,
2998 min_max_size,
2999 } => {
3000 let mut found_right_of = false;
3001
3002 match &mut layout.monitor_set {
3003 MonitorSet::Normal { monitors, .. } => {
3004 for mon in monitors {
3005 for ws in &mut mon.workspaces {
3006 for win in ws.windows() {
3007 if win.0.id == id {
3008 return;
3009 }
3010
3011 if win.0.id == right_of_id {
3012 found_right_of = true;
3013 }
3014 }
3015 }
3016 }
3017 }
3018 MonitorSet::NoOutputs { workspaces, .. } => {
3019 for ws in workspaces {
3020 for win in ws.windows() {
3021 if win.0.id == id {
3022 return;
3023 }
3024
3025 if win.0.id == right_of_id {
3026 found_right_of = true;
3027 }
3028 }
3029 }
3030 }
3031 }
3032
3033 if !found_right_of {
3034 return;
3035 }
3036
3037 let win = TestWindow::new(id, bbox, min_max_size.0, min_max_size.1);
3038 layout.add_window_right_of(&right_of_id, win, None, false);
3039 }
3040 Op::AddWindowToNamedWorkspace {
3041 id,
3042 ws_name,
3043 bbox,
3044 min_max_size,
3045 } => {
3046 let ws_name = format!("ws{ws_name}");
3047 let mut found_workspace = false;
3048
3049 match &mut layout.monitor_set {
3050 MonitorSet::Normal { monitors, .. } => {
3051 for mon in monitors {
3052 for ws in &mut mon.workspaces {
3053 for win in ws.windows() {
3054 if win.0.id == id {
3055 return;
3056 }
3057 }
3058
3059 if ws
3060 .name
3061 .as_ref()
3062 .map_or(false, |name| name.eq_ignore_ascii_case(&ws_name))
3063 {
3064 found_workspace = true;
3065 }
3066 }
3067 }
3068 }
3069 MonitorSet::NoOutputs { workspaces, .. } => {
3070 for ws in workspaces {
3071 for win in ws.windows() {
3072 if win.0.id == id {
3073 return;
3074 }
3075 }
3076
3077 if ws
3078 .name
3079 .as_ref()
3080 .map_or(false, |name| name.eq_ignore_ascii_case(&ws_name))
3081 {
3082 found_workspace = true;
3083 }
3084 }
3085 }
3086 }
3087
3088 if !found_workspace {
3089 return;
3090 }
3091
3092 let win = TestWindow::new(id, bbox, min_max_size.0, min_max_size.1);
3093 layout.add_window_to_named_workspace(&ws_name, win, None, false);
3094 }
3095 Op::CloseWindow(id) => {
3096 layout.remove_window(&id);
3097 }
3098 Op::FullscreenWindow(id) => {
3099 layout.toggle_fullscreen(&id);
3100 }
3101 Op::SetFullscreenWindow {
3102 window,
3103 is_fullscreen,
3104 } => {
3105 layout.set_fullscreen(&window, is_fullscreen);
3106 }
3107 Op::FocusColumnLeft => layout.focus_left(),
3108 Op::FocusColumnRight => layout.focus_right(),
3109 Op::FocusColumnFirst => layout.focus_column_first(),
3110 Op::FocusColumnLast => layout.focus_column_last(),
3111 Op::FocusColumnRightOrFirst => layout.focus_column_right_or_first(),
3112 Op::FocusColumnLeftOrLast => layout.focus_column_left_or_last(),
3113 Op::FocusWindowOrMonitorUp(id) => {
3114 let name = format!("output{id}");
3115 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3116 return;
3117 };
3118
3119 layout.focus_window_up_or_output(&output);
3120 }
3121 Op::FocusWindowOrMonitorDown(id) => {
3122 let name = format!("output{id}");
3123 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3124 return;
3125 };
3126
3127 layout.focus_window_down_or_output(&output);
3128 }
3129 Op::FocusColumnOrMonitorLeft(id) => {
3130 let name = format!("output{id}");
3131 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3132 return;
3133 };
3134
3135 layout.focus_column_left_or_output(&output);
3136 }
3137 Op::FocusColumnOrMonitorRight(id) => {
3138 let name = format!("output{id}");
3139 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3140 return;
3141 };
3142
3143 layout.focus_column_right_or_output(&output);
3144 }
3145 Op::FocusWindowDown => layout.focus_down(),
3146 Op::FocusWindowUp => layout.focus_up(),
3147 Op::FocusWindowDownOrColumnLeft => layout.focus_down_or_left(),
3148 Op::FocusWindowDownOrColumnRight => layout.focus_down_or_right(),
3149 Op::FocusWindowUpOrColumnLeft => layout.focus_up_or_left(),
3150 Op::FocusWindowUpOrColumnRight => layout.focus_up_or_right(),
3151 Op::FocusWindowOrWorkspaceDown => layout.focus_window_or_workspace_down(),
3152 Op::FocusWindowOrWorkspaceUp => layout.focus_window_or_workspace_up(),
3153 Op::MoveColumnLeft => layout.move_left(),
3154 Op::MoveColumnRight => layout.move_right(),
3155 Op::MoveColumnToFirst => layout.move_column_to_first(),
3156 Op::MoveColumnToLast => layout.move_column_to_last(),
3157 Op::MoveWindowDown => layout.move_down(),
3158 Op::MoveWindowUp => layout.move_up(),
3159 Op::MoveWindowDownOrToWorkspaceDown => layout.move_down_or_to_workspace_down(),
3160 Op::MoveWindowUpOrToWorkspaceUp => layout.move_up_or_to_workspace_up(),
3161 Op::ConsumeOrExpelWindowLeft => layout.consume_or_expel_window_left(),
3162 Op::ConsumeOrExpelWindowRight => layout.consume_or_expel_window_right(),
3163 Op::ConsumeWindowIntoColumn => layout.consume_into_column(),
3164 Op::ExpelWindowFromColumn => layout.expel_from_column(),
3165 Op::CenterColumn => layout.center_column(),
3166 Op::FocusWorkspaceDown => layout.switch_workspace_down(),
3167 Op::FocusWorkspaceUp => layout.switch_workspace_up(),
3168 Op::FocusWorkspace(idx) => layout.switch_workspace(idx),
3169 Op::FocusWorkspaceAutoBackAndForth(idx) => {
3170 layout.switch_workspace_auto_back_and_forth(idx)
3171 }
3172 Op::FocusWorkspacePrevious => layout.switch_workspace_previous(),
3173 Op::MoveWindowToWorkspaceDown => layout.move_to_workspace_down(),
3174 Op::MoveWindowToWorkspaceUp => layout.move_to_workspace_up(),
3175 Op::MoveWindowToWorkspace(idx) => layout.move_to_workspace(idx),
3176 Op::MoveColumnToWorkspaceDown => layout.move_column_to_workspace_down(),
3177 Op::MoveColumnToWorkspaceUp => layout.move_column_to_workspace_up(),
3178 Op::MoveColumnToWorkspace(idx) => layout.move_column_to_workspace(idx),
3179 Op::MoveWindowToOutput(id) => {
3180 let name = format!("output{id}");
3181 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3182 return;
3183 };
3184
3185 layout.move_to_output(&output);
3186 }
3187 Op::MoveColumnToOutput(id) => {
3188 let name = format!("output{id}");
3189 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3190 return;
3191 };
3192
3193 layout.move_column_to_output(&output);
3194 }
3195 Op::MoveWorkspaceDown => layout.move_workspace_down(),
3196 Op::MoveWorkspaceUp => layout.move_workspace_up(),
3197 Op::SwitchPresetColumnWidth => layout.toggle_width(),
3198 Op::MaximizeColumn => layout.toggle_full_width(),
3199 Op::SetColumnWidth(change) => layout.set_column_width(change),
3200 Op::SetWindowHeight(change) => layout.set_window_height(change),
3201 Op::ResetWindowHeight => layout.reset_window_height(),
3202 Op::Communicate(id) => {
3203 let mut update = false;
3204 match &mut layout.monitor_set {
3205 MonitorSet::Normal { monitors, .. } => {
3206 'outer: for mon in monitors {
3207 for ws in &mut mon.workspaces {
3208 for win in ws.windows() {
3209 if win.0.id == id {
3210 if win.communicate() {
3211 update = true;
3212 }
3213 break 'outer;
3214 }
3215 }
3216 }
3217 }
3218 }
3219 MonitorSet::NoOutputs { workspaces, .. } => {
3220 'outer: for ws in workspaces {
3221 for win in ws.windows() {
3222 if win.0.id == id {
3223 if win.communicate() {
3224 update = true;
3225 }
3226 break 'outer;
3227 }
3228 }
3229 }
3230 }
3231 }
3232
3233 if update {
3234 // FIXME: serial.
3235 layout.update_window(&id, None);
3236 }
3237 }
3238 Op::MoveWorkspaceToOutput(id) => {
3239 let name = format!("output{id}");
3240 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3241 return;
3242 };
3243
3244 layout.move_workspace_to_output(&output);
3245 }
3246 Op::ViewOffsetGestureBegin {
3247 output_idx: id,
3248 is_touchpad: normalize,
3249 } => {
3250 let name = format!("output{id}");
3251 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3252 return;
3253 };
3254
3255 layout.view_offset_gesture_begin(&output, normalize);
3256 }
3257 Op::ViewOffsetGestureUpdate {
3258 delta,
3259 timestamp,
3260 is_touchpad,
3261 } => {
3262 layout.view_offset_gesture_update(delta, timestamp, is_touchpad);
3263 }
3264 Op::ViewOffsetGestureEnd { is_touchpad } => {
3265 // We don't handle cancels in this gesture.
3266 layout.view_offset_gesture_end(false, is_touchpad);
3267 }
3268 Op::WorkspaceSwitchGestureBegin {
3269 output_idx: id,
3270 is_touchpad,
3271 } => {
3272 let name = format!("output{id}");
3273 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3274 return;
3275 };
3276
3277 layout.workspace_switch_gesture_begin(&output, is_touchpad);
3278 }
3279 Op::WorkspaceSwitchGestureUpdate {
3280 delta,
3281 timestamp,
3282 is_touchpad,
3283 } => {
3284 layout.workspace_switch_gesture_update(delta, timestamp, is_touchpad);
3285 }
3286 Op::WorkspaceSwitchGestureEnd {
3287 cancelled,
3288 is_touchpad,
3289 } => {
3290 layout.workspace_switch_gesture_end(cancelled, is_touchpad);
3291 }
3292 Op::InteractiveResizeBegin { window, edges } => {
3293 layout.interactive_resize_begin(window, edges);
3294 }
3295 Op::InteractiveResizeUpdate { window, dx, dy } => {
3296 layout.interactive_resize_update(&window, Point::from((dx, dy)));
3297 }
3298 Op::InteractiveResizeEnd { window } => {
3299 layout.interactive_resize_end(&window);
3300 }
3301 }
3302 }
3303 }
3304
3305 #[track_caller]
3306 fn check_ops(ops: &[Op]) {
3307 let mut layout = Layout::default();
3308 for op in ops {
3309 op.apply(&mut layout);
3310 layout.verify_invariants();
3311 }
3312 }
3313
3314 #[track_caller]
3315 fn check_ops_with_options(options: Options, ops: &[Op]) {
3316 let mut layout = Layout::with_options(options);
3317
3318 for op in ops {
3319 op.apply(&mut layout);
3320 layout.verify_invariants();
3321 }
3322 }
3323
3324 #[test]
3325 fn operations_dont_panic() {
3326 let every_op = [
3327 Op::AddOutput(0),
3328 Op::AddOutput(1),
3329 Op::AddOutput(2),
3330 Op::RemoveOutput(0),
3331 Op::RemoveOutput(1),
3332 Op::RemoveOutput(2),
3333 Op::FocusOutput(0),
3334 Op::FocusOutput(1),
3335 Op::FocusOutput(2),
3336 Op::AddNamedWorkspace {
3337 ws_name: 1,
3338 output_name: Some(1),
3339 },
3340 Op::UnnameWorkspace { ws_name: 1 },
3341 Op::AddWindow {
3342 id: 0,
3343 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3344 min_max_size: Default::default(),
3345 },
3346 Op::AddWindow {
3347 id: 1,
3348 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3349 min_max_size: Default::default(),
3350 },
3351 Op::AddWindowRightOf {
3352 id: 2,
3353 right_of_id: 1,
3354 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3355 min_max_size: Default::default(),
3356 },
3357 Op::AddWindowToNamedWorkspace {
3358 id: 3,
3359 ws_name: 1,
3360 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3361 min_max_size: Default::default(),
3362 },
3363 Op::CloseWindow(0),
3364 Op::CloseWindow(1),
3365 Op::CloseWindow(2),
3366 Op::FullscreenWindow(1),
3367 Op::FullscreenWindow(2),
3368 Op::FullscreenWindow(3),
3369 Op::FocusColumnLeft,
3370 Op::FocusColumnRight,
3371 Op::FocusColumnRightOrFirst,
3372 Op::FocusColumnLeftOrLast,
3373 Op::FocusWindowOrMonitorUp(0),
3374 Op::FocusWindowOrMonitorDown(1),
3375 Op::FocusColumnOrMonitorLeft(0),
3376 Op::FocusColumnOrMonitorRight(1),
3377 Op::FocusWindowUp,
3378 Op::FocusWindowUpOrColumnLeft,
3379 Op::FocusWindowUpOrColumnRight,
3380 Op::FocusWindowOrWorkspaceUp,
3381 Op::FocusWindowDown,
3382 Op::FocusWindowDownOrColumnLeft,
3383 Op::FocusWindowDownOrColumnRight,
3384 Op::FocusWindowOrWorkspaceDown,
3385 Op::MoveColumnLeft,
3386 Op::MoveColumnRight,
3387 Op::ConsumeWindowIntoColumn,
3388 Op::ExpelWindowFromColumn,
3389 Op::CenterColumn,
3390 Op::FocusWorkspaceDown,
3391 Op::FocusWorkspaceUp,
3392 Op::FocusWorkspace(1),
3393 Op::FocusWorkspace(2),
3394 Op::MoveWindowToWorkspaceDown,
3395 Op::MoveWindowToWorkspaceUp,
3396 Op::MoveWindowToWorkspace(1),
3397 Op::MoveWindowToWorkspace(2),
3398 Op::MoveColumnToWorkspaceDown,
3399 Op::MoveColumnToWorkspaceUp,
3400 Op::MoveColumnToWorkspace(1),
3401 Op::MoveColumnToWorkspace(2),
3402 Op::MoveWindowDown,
3403 Op::MoveWindowDownOrToWorkspaceDown,
3404 Op::MoveWindowUp,
3405 Op::MoveWindowUpOrToWorkspaceUp,
3406 Op::ConsumeOrExpelWindowLeft,
3407 Op::ConsumeOrExpelWindowRight,
3408 Op::MoveWorkspaceToOutput(1),
3409 ];
3410
3411 for third in every_op {
3412 for second in every_op {
3413 for first in every_op {
3414 // eprintln!("{first:?}, {second:?}, {third:?}");
3415
3416 let mut layout = Layout::default();
3417 first.apply(&mut layout);
3418 layout.verify_invariants();
3419 second.apply(&mut layout);
3420 layout.verify_invariants();
3421 third.apply(&mut layout);
3422 layout.verify_invariants();
3423 }
3424 }
3425 }
3426 }
3427
3428 #[test]
3429 fn operations_from_starting_state_dont_panic() {
3430 if std::env::var_os("RUN_SLOW_TESTS").is_none() {
3431 eprintln!("ignoring slow test");
3432 return;
3433 }
3434
3435 // Running every op from an empty state doesn't get us to all the interesting states. So,
3436 // also run it from a manually-created starting state with more things going on to exercise
3437 // more code paths.
3438 let setup_ops = [
3439 Op::AddOutput(1),
3440 Op::AddWindow {
3441 id: 1,
3442 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3443 min_max_size: Default::default(),
3444 },
3445 Op::MoveWindowToWorkspaceDown,
3446 Op::AddWindow {
3447 id: 2,
3448 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3449 min_max_size: Default::default(),
3450 },
3451 Op::AddWindow {
3452 id: 3,
3453 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3454 min_max_size: Default::default(),
3455 },
3456 Op::FocusColumnLeft,
3457 Op::ConsumeWindowIntoColumn,
3458 Op::AddWindow {
3459 id: 4,
3460 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3461 min_max_size: Default::default(),
3462 },
3463 Op::AddOutput(2),
3464 Op::AddWindow {
3465 id: 5,
3466 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3467 min_max_size: Default::default(),
3468 },
3469 Op::MoveWindowToOutput(2),
3470 Op::FocusOutput(1),
3471 Op::Communicate(1),
3472 Op::Communicate(2),
3473 Op::Communicate(3),
3474 Op::Communicate(4),
3475 Op::Communicate(5),
3476 ];
3477
3478 let every_op = [
3479 Op::AddOutput(0),
3480 Op::AddOutput(1),
3481 Op::AddOutput(2),
3482 Op::RemoveOutput(0),
3483 Op::RemoveOutput(1),
3484 Op::RemoveOutput(2),
3485 Op::FocusOutput(0),
3486 Op::FocusOutput(1),
3487 Op::FocusOutput(2),
3488 Op::AddNamedWorkspace {
3489 ws_name: 1,
3490 output_name: Some(1),
3491 },
3492 Op::UnnameWorkspace { ws_name: 1 },
3493 Op::AddWindow {
3494 id: 0,
3495 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3496 min_max_size: Default::default(),
3497 },
3498 Op::AddWindow {
3499 id: 1,
3500 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3501 min_max_size: Default::default(),
3502 },
3503 Op::AddWindow {
3504 id: 2,
3505 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3506 min_max_size: Default::default(),
3507 },
3508 Op::AddWindowRightOf {
3509 id: 6,
3510 right_of_id: 0,
3511 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3512 min_max_size: Default::default(),
3513 },
3514 Op::AddWindowRightOf {
3515 id: 7,
3516 right_of_id: 1,
3517 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3518 min_max_size: Default::default(),
3519 },
3520 Op::AddWindowToNamedWorkspace {
3521 id: 5,
3522 ws_name: 1,
3523 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3524 min_max_size: Default::default(),
3525 },
3526 Op::CloseWindow(0),
3527 Op::CloseWindow(1),
3528 Op::CloseWindow(2),
3529 Op::FullscreenWindow(1),
3530 Op::FullscreenWindow(2),
3531 Op::FullscreenWindow(3),
3532 Op::SetFullscreenWindow {
3533 window: 1,
3534 is_fullscreen: false,
3535 },
3536 Op::SetFullscreenWindow {
3537 window: 1,
3538 is_fullscreen: true,
3539 },
3540 Op::SetFullscreenWindow {
3541 window: 2,
3542 is_fullscreen: false,
3543 },
3544 Op::SetFullscreenWindow {
3545 window: 2,
3546 is_fullscreen: true,
3547 },
3548 Op::FocusColumnLeft,
3549 Op::FocusColumnRight,
3550 Op::FocusColumnRightOrFirst,
3551 Op::FocusColumnLeftOrLast,
3552 Op::FocusWindowOrMonitorUp(0),
3553 Op::FocusWindowOrMonitorDown(1),
3554 Op::FocusColumnOrMonitorLeft(0),
3555 Op::FocusColumnOrMonitorRight(1),
3556 Op::FocusWindowUp,
3557 Op::FocusWindowUpOrColumnLeft,
3558 Op::FocusWindowUpOrColumnRight,
3559 Op::FocusWindowOrWorkspaceUp,
3560 Op::FocusWindowDown,
3561 Op::FocusWindowDownOrColumnLeft,
3562 Op::FocusWindowDownOrColumnRight,
3563 Op::FocusWindowOrWorkspaceDown,
3564 Op::MoveColumnLeft,
3565 Op::MoveColumnRight,
3566 Op::ConsumeWindowIntoColumn,
3567 Op::ExpelWindowFromColumn,
3568 Op::CenterColumn,
3569 Op::FocusWorkspaceDown,
3570 Op::FocusWorkspaceUp,
3571 Op::FocusWorkspace(1),
3572 Op::FocusWorkspace(2),
3573 Op::FocusWorkspace(3),
3574 Op::MoveWindowToWorkspaceDown,
3575 Op::MoveWindowToWorkspaceUp,
3576 Op::MoveWindowToWorkspace(1),
3577 Op::MoveWindowToWorkspace(2),
3578 Op::MoveWindowToWorkspace(3),
3579 Op::MoveColumnToWorkspaceDown,
3580 Op::MoveColumnToWorkspaceUp,
3581 Op::MoveColumnToWorkspace(1),
3582 Op::MoveColumnToWorkspace(2),
3583 Op::MoveColumnToWorkspace(3),
3584 Op::MoveWindowDown,
3585 Op::MoveWindowDownOrToWorkspaceDown,
3586 Op::MoveWindowUp,
3587 Op::MoveWindowUpOrToWorkspaceUp,
3588 Op::ConsumeOrExpelWindowLeft,
3589 Op::ConsumeOrExpelWindowRight,
3590 ];
3591
3592 for third in every_op {
3593 for second in every_op {
3594 for first in every_op {
3595 // eprintln!("{first:?}, {second:?}, {third:?}");
3596
3597 let mut layout = Layout::default();
3598 for op in setup_ops {
3599 op.apply(&mut layout);
3600 }
3601
3602 first.apply(&mut layout);
3603 layout.verify_invariants();
3604 second.apply(&mut layout);
3605 layout.verify_invariants();
3606 third.apply(&mut layout);
3607 layout.verify_invariants();
3608 }
3609 }
3610 }
3611 }
3612
3613 #[test]
3614 fn primary_active_workspace_idx_not_updated_on_output_add() {
3615 let ops = [
3616 Op::AddOutput(1),
3617 Op::AddOutput(2),
3618 Op::FocusOutput(1),
3619 Op::AddWindow {
3620 id: 0,
3621 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3622 min_max_size: Default::default(),
3623 },
3624 Op::FocusOutput(2),
3625 Op::AddWindow {
3626 id: 1,
3627 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3628 min_max_size: Default::default(),
3629 },
3630 Op::RemoveOutput(2),
3631 Op::FocusWorkspace(3),
3632 Op::AddOutput(2),
3633 ];
3634
3635 check_ops(&ops);
3636 }
3637
3638 #[test]
3639 fn window_closed_on_previous_workspace() {
3640 let ops = [
3641 Op::AddOutput(1),
3642 Op::AddWindow {
3643 id: 0,
3644 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3645 min_max_size: Default::default(),
3646 },
3647 Op::FocusWorkspaceDown,
3648 Op::CloseWindow(0),
3649 ];
3650
3651 check_ops(&ops);
3652 }
3653
3654 #[test]
3655 fn removing_output_must_keep_empty_focus_on_primary() {
3656 let ops = [
3657 Op::AddOutput(1),
3658 Op::AddWindow {
3659 id: 0,
3660 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3661 min_max_size: Default::default(),
3662 },
3663 Op::AddOutput(2),
3664 Op::RemoveOutput(1),
3665 ];
3666
3667 let mut layout = Layout::default();
3668 for op in ops {
3669 op.apply(&mut layout);
3670 }
3671
3672 let MonitorSet::Normal { monitors, .. } = layout.monitor_set else {
3673 unreachable!()
3674 };
3675
3676 // The workspace from the removed output was inserted at position 0, so the active workspace
3677 // must change to 1 to keep the focus on the empty workspace.
3678 assert_eq!(monitors[0].active_workspace_idx, 1);
3679 }
3680
3681 #[test]
3682 fn move_to_workspace_by_idx_does_not_leave_empty_workspaces() {
3683 let ops = [
3684 Op::AddOutput(1),
3685 Op::AddWindow {
3686 id: 0,
3687 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3688 min_max_size: Default::default(),
3689 },
3690 Op::MoveWindowToWorkspace(2),
3691 ];
3692
3693 let mut layout = Layout::default();
3694 for op in ops {
3695 op.apply(&mut layout);
3696 }
3697
3698 let MonitorSet::Normal { monitors, .. } = layout.monitor_set else {
3699 unreachable!()
3700 };
3701
3702 assert!(monitors[0].workspaces[0].has_windows());
3703 }
3704
3705 #[test]
3706 fn focus_workspace_by_idx_does_not_leave_empty_workspaces() {
3707 let ops = [
3708 Op::AddOutput(1),
3709 Op::AddWindow {
3710 id: 0,
3711 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3712 min_max_size: Default::default(),
3713 },
3714 Op::FocusWorkspaceDown,
3715 Op::AddWindow {
3716 id: 1,
3717 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3718 min_max_size: Default::default(),
3719 },
3720 Op::FocusWorkspaceUp,
3721 Op::CloseWindow(0),
3722 Op::FocusWorkspace(3),
3723 ];
3724
3725 let mut layout = Layout::default();
3726 for op in ops {
3727 op.apply(&mut layout);
3728 }
3729
3730 let MonitorSet::Normal { monitors, .. } = layout.monitor_set else {
3731 unreachable!()
3732 };
3733
3734 assert!(monitors[0].workspaces[0].has_windows());
3735 }
3736
3737 #[test]
3738 fn empty_workspaces_dont_move_back_to_original_output() {
3739 let ops = [
3740 Op::AddOutput(1),
3741 Op::AddWindow {
3742 id: 1,
3743 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3744 min_max_size: Default::default(),
3745 },
3746 Op::FocusWorkspaceDown,
3747 Op::AddWindow {
3748 id: 2,
3749 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3750 min_max_size: Default::default(),
3751 },
3752 Op::AddOutput(2),
3753 Op::RemoveOutput(1),
3754 Op::FocusWorkspace(1),
3755 Op::CloseWindow(1),
3756 Op::AddOutput(1),
3757 ];
3758
3759 check_ops(&ops);
3760 }
3761
3762 #[test]
3763 fn large_negative_height_change() {
3764 let ops = [
3765 Op::AddOutput(1),
3766 Op::AddWindow {
3767 id: 1,
3768 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3769 min_max_size: Default::default(),
3770 },
3771 Op::SetWindowHeight(SizeChange::AdjustProportion(-1e129)),
3772 ];
3773
3774 let mut options = Options::default();
3775 options.border.off = false;
3776 options.border.width = FloatOrInt(1.);
3777
3778 check_ops_with_options(options, &ops);
3779 }
3780
3781 #[test]
3782 fn large_max_size() {
3783 let ops = [
3784 Op::AddOutput(1),
3785 Op::AddWindow {
3786 id: 1,
3787 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3788 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3789 },
3790 ];
3791
3792 let mut options = Options::default();
3793 options.border.off = false;
3794 options.border.width = FloatOrInt(1.);
3795
3796 check_ops_with_options(options, &ops);
3797 }
3798
3799 #[test]
3800 fn workspace_cleanup_during_switch() {
3801 let ops = [
3802 Op::AddOutput(1),
3803 Op::AddWindow {
3804 id: 1,
3805 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3806 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3807 },
3808 Op::FocusWorkspaceDown,
3809 Op::CloseWindow(1),
3810 ];
3811
3812 check_ops(&ops);
3813 }
3814
3815 #[test]
3816 fn workspace_transfer_during_switch() {
3817 let ops = [
3818 Op::AddOutput(1),
3819 Op::AddWindow {
3820 id: 1,
3821 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3822 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3823 },
3824 Op::AddOutput(2),
3825 Op::FocusOutput(2),
3826 Op::AddWindow {
3827 id: 2,
3828 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3829 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3830 },
3831 Op::RemoveOutput(1),
3832 Op::FocusWorkspaceDown,
3833 Op::FocusWorkspaceDown,
3834 Op::AddOutput(1),
3835 ];
3836
3837 check_ops(&ops);
3838 }
3839
3840 #[test]
3841 fn workspace_transfer_during_switch_from_last() {
3842 let ops = [
3843 Op::AddOutput(1),
3844 Op::AddWindow {
3845 id: 1,
3846 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3847 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3848 },
3849 Op::AddOutput(2),
3850 Op::RemoveOutput(1),
3851 Op::FocusWorkspaceUp,
3852 Op::AddOutput(1),
3853 ];
3854
3855 check_ops(&ops);
3856 }
3857
3858 #[test]
3859 fn workspace_transfer_during_switch_gets_cleaned_up() {
3860 let ops = [
3861 Op::AddOutput(1),
3862 Op::AddWindow {
3863 id: 1,
3864 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3865 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3866 },
3867 Op::RemoveOutput(1),
3868 Op::AddOutput(2),
3869 Op::MoveColumnToWorkspaceDown,
3870 Op::MoveColumnToWorkspaceDown,
3871 Op::AddOutput(1),
3872 ];
3873
3874 check_ops(&ops);
3875 }
3876
3877 #[test]
3878 fn move_workspace_to_output() {
3879 let ops = [
3880 Op::AddOutput(1),
3881 Op::AddOutput(2),
3882 Op::FocusOutput(1),
3883 Op::AddWindow {
3884 id: 0,
3885 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3886 min_max_size: Default::default(),
3887 },
3888 Op::MoveWorkspaceToOutput(2),
3889 ];
3890
3891 let mut layout = Layout::default();
3892 for op in ops {
3893 op.apply(&mut layout);
3894 }
3895
3896 let MonitorSet::Normal {
3897 monitors,
3898 active_monitor_idx,
3899 ..
3900 } = layout.monitor_set
3901 else {
3902 unreachable!()
3903 };
3904
3905 assert_eq!(active_monitor_idx, 1);
3906 assert_eq!(monitors[0].workspaces.len(), 1);
3907 assert!(!monitors[0].workspaces[0].has_windows());
3908 assert_eq!(monitors[1].active_workspace_idx, 0);
3909 assert_eq!(monitors[1].workspaces.len(), 2);
3910 assert!(monitors[1].workspaces[0].has_windows());
3911 }
3912
3913 #[test]
3914 fn fullscreen() {
3915 let ops = [
3916 Op::AddOutput(1),
3917 Op::AddWindow {
3918 id: 1,
3919 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3920 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3921 },
3922 Op::FullscreenWindow(1),
3923 ];
3924
3925 check_ops(&ops);
3926 }
3927
3928 #[test]
3929 fn unfullscreen_window_in_column() {
3930 let ops = [
3931 Op::AddOutput(1),
3932 Op::AddWindow {
3933 id: 1,
3934 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3935 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3936 },
3937 Op::AddWindow {
3938 id: 2,
3939 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3940 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3941 },
3942 Op::ConsumeOrExpelWindowLeft,
3943 Op::SetFullscreenWindow {
3944 window: 2,
3945 is_fullscreen: false,
3946 },
3947 ];
3948
3949 check_ops(&ops);
3950 }
3951
3952 #[test]
3953 fn open_right_of_on_different_workspace() {
3954 let ops = [
3955 Op::AddOutput(1),
3956 Op::AddWindow {
3957 id: 1,
3958 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3959 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3960 },
3961 Op::FocusWorkspaceDown,
3962 Op::AddWindow {
3963 id: 2,
3964 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3965 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3966 },
3967 Op::AddWindowRightOf {
3968 id: 3,
3969 right_of_id: 1,
3970 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3971 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3972 },
3973 ];
3974
3975 let mut layout = Layout::default();
3976 for op in ops {
3977 op.apply(&mut layout);
3978 }
3979
3980 let MonitorSet::Normal { monitors, .. } = layout.monitor_set else {
3981 unreachable!()
3982 };
3983
3984 let mon = monitors.into_iter().next().unwrap();
3985 assert_eq!(
3986 mon.active_workspace_idx, 1,
3987 "the second workspace must remain active"
3988 );
3989 assert_eq!(
3990 mon.workspaces[0].active_column_idx, 1,
3991 "the new window must become active"
3992 );
3993 }
3994
3995 #[test]
3996 fn unfullscreen_view_offset_not_reset_on_removal() {
3997 let ops = [
3998 Op::AddOutput(1),
3999 Op::AddWindow {
4000 id: 0,
4001 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4002 min_max_size: Default::default(),
4003 },
4004 Op::FullscreenWindow(0),
4005 Op::AddWindow {
4006 id: 1,
4007 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4008 min_max_size: Default::default(),
4009 },
4010 Op::ConsumeOrExpelWindowRight,
4011 ];
4012
4013 check_ops(&ops);
4014 }
4015
4016 #[test]
4017 fn unfullscreen_view_offset_not_reset_on_consume() {
4018 let ops = [
4019 Op::AddOutput(1),
4020 Op::AddWindow {
4021 id: 0,
4022 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4023 min_max_size: Default::default(),
4024 },
4025 Op::FullscreenWindow(0),
4026 Op::AddWindow {
4027 id: 1,
4028 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4029 min_max_size: Default::default(),
4030 },
4031 Op::ConsumeWindowIntoColumn,
4032 ];
4033
4034 check_ops(&ops);
4035 }
4036
4037 #[test]
4038 fn unfullscreen_view_offset_not_reset_on_quick_double_toggle() {
4039 let ops = [
4040 Op::AddOutput(1),
4041 Op::AddWindow {
4042 id: 0,
4043 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4044 min_max_size: Default::default(),
4045 },
4046 Op::FullscreenWindow(0),
4047 Op::FullscreenWindow(0),
4048 ];
4049
4050 check_ops(&ops);
4051 }
4052
4053 #[test]
4054 fn unfullscreen_view_offset_set_on_fullscreening_inactive_tile_in_column() {
4055 let ops = [
4056 Op::AddOutput(1),
4057 Op::AddWindow {
4058 id: 0,
4059 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4060 min_max_size: Default::default(),
4061 },
4062 Op::AddWindow {
4063 id: 1,
4064 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4065 min_max_size: Default::default(),
4066 },
4067 Op::ConsumeOrExpelWindowLeft,
4068 Op::FullscreenWindow(0),
4069 ];
4070
4071 check_ops(&ops);
4072 }
4073
4074 #[test]
4075 fn unfullscreen_view_offset_not_reset_on_gesture() {
4076 let ops = [
4077 Op::AddOutput(1),
4078 Op::AddWindow {
4079 id: 0,
4080 bbox: Rectangle::from_loc_and_size((0, 0), (200, 200)),
4081 min_max_size: Default::default(),
4082 },
4083 Op::AddWindow {
4084 id: 1,
4085 bbox: Rectangle::from_loc_and_size((0, 0), (1280, 200)),
4086 min_max_size: Default::default(),
4087 },
4088 Op::FullscreenWindow(1),
4089 Op::ViewOffsetGestureBegin {
4090 output_idx: 1,
4091 is_touchpad: true,
4092 },
4093 Op::ViewOffsetGestureEnd {
4094 is_touchpad: Some(true),
4095 },
4096 ];
4097
4098 check_ops(&ops);
4099 }
4100
4101 #[test]
4102 fn removing_all_outputs_preserves_empty_named_workspaces() {
4103 let ops = [
4104 Op::AddOutput(1),
4105 Op::AddNamedWorkspace {
4106 ws_name: 1,
4107 output_name: None,
4108 },
4109 Op::AddNamedWorkspace {
4110 ws_name: 2,
4111 output_name: None,
4112 },
4113 Op::RemoveOutput(1),
4114 ];
4115
4116 let mut layout = Layout::default();
4117 for op in ops {
4118 op.apply(&mut layout);
4119 }
4120
4121 let MonitorSet::NoOutputs { workspaces } = layout.monitor_set else {
4122 unreachable!()
4123 };
4124
4125 assert_eq!(workspaces.len(), 2);
4126 }
4127
4128 #[test]
4129 fn config_change_updates_cached_sizes() {
4130 let mut config = Config::default();
4131 config.layout.border.off = false;
4132 config.layout.border.width = FloatOrInt(2.);
4133
4134 let mut layout = Layout::new(&config);
4135
4136 Op::AddWindow {
4137 id: 1,
4138 bbox: Rectangle::from_loc_and_size((0, 0), (1280, 200)),
4139 min_max_size: Default::default(),
4140 }
4141 .apply(&mut layout);
4142
4143 config.layout.border.width = FloatOrInt(4.);
4144 layout.update_config(&config);
4145
4146 layout.verify_invariants();
4147 }
4148
4149 #[test]
4150 fn working_area_starts_at_physical_pixel() {
4151 let struts = Struts {
4152 left: FloatOrInt(0.5),
4153 right: FloatOrInt(1.),
4154 top: FloatOrInt(0.75),
4155 bottom: FloatOrInt(1.),
4156 };
4157
4158 let output = Output::new(
4159 String::from("output"),
4160 PhysicalProperties {
4161 size: Size::from((1280, 720)),
4162 subpixel: Subpixel::Unknown,
4163 make: String::new(),
4164 model: String::new(),
4165 },
4166 );
4167 output.change_current_state(
4168 Some(Mode {
4169 size: Size::from((1280, 720)),
4170 refresh: 60000,
4171 }),
4172 None,
4173 None,
4174 None,
4175 );
4176
4177 let area = compute_working_area(&output, struts);
4178
4179 assert_eq!(round_logical_in_physical(1., area.loc.x), area.loc.x);
4180 assert_eq!(round_logical_in_physical(1., area.loc.y), area.loc.y);
4181 }
4182
4183 #[test]
4184 fn large_fractional_strut() {
4185 let struts = Struts {
4186 left: FloatOrInt(0.),
4187 right: FloatOrInt(0.),
4188 top: FloatOrInt(50000.5),
4189 bottom: FloatOrInt(0.),
4190 };
4191
4192 let output = Output::new(
4193 String::from("output"),
4194 PhysicalProperties {
4195 size: Size::from((1280, 720)),
4196 subpixel: Subpixel::Unknown,
4197 make: String::new(),
4198 model: String::new(),
4199 },
4200 );
4201 output.change_current_state(
4202 Some(Mode {
4203 size: Size::from((1280, 720)),
4204 refresh: 60000,
4205 }),
4206 None,
4207 None,
4208 None,
4209 );
4210
4211 compute_working_area(&output, struts);
4212 }
4213
4214 fn arbitrary_spacing() -> impl Strategy<Value = f64> {
4215 // Give equal weight to:
4216 // - 0: the element is disabled
4217 // - 4: some reasonable value
4218 // - random value, likely unreasonably big
4219 prop_oneof![Just(0.), Just(4.), ((1.)..=65535.)]
4220 }
4221
4222 fn arbitrary_struts() -> impl Strategy<Value = Struts> {
4223 (
4224 arbitrary_spacing(),
4225 arbitrary_spacing(),
4226 arbitrary_spacing(),
4227 arbitrary_spacing(),
4228 )
4229 .prop_map(|(left, right, top, bottom)| Struts {
4230 left: FloatOrInt(left),
4231 right: FloatOrInt(right),
4232 top: FloatOrInt(top),
4233 bottom: FloatOrInt(bottom),
4234 })
4235 }
4236
4237 fn arbitrary_center_focused_column() -> impl Strategy<Value = CenterFocusedColumn> {
4238 prop_oneof![
4239 Just(CenterFocusedColumn::Never),
4240 Just(CenterFocusedColumn::OnOverflow),
4241 Just(CenterFocusedColumn::Always),
4242 ]
4243 }
4244
4245 prop_compose! {
4246 fn arbitrary_focus_ring()(
4247 off in any::<bool>(),
4248 width in arbitrary_spacing(),
4249 ) -> niri_config::FocusRing {
4250 niri_config::FocusRing {
4251 off,
4252 width: FloatOrInt(width),
4253 ..Default::default()
4254 }
4255 }
4256 }
4257
4258 prop_compose! {
4259 fn arbitrary_border()(
4260 off in any::<bool>(),
4261 width in arbitrary_spacing(),
4262 ) -> niri_config::Border {
4263 niri_config::Border {
4264 off,
4265 width: FloatOrInt(width),
4266 ..Default::default()
4267 }
4268 }
4269 }
4270
4271 prop_compose! {
4272 fn arbitrary_options()(
4273 gaps in arbitrary_spacing(),
4274 struts in arbitrary_struts(),
4275 focus_ring in arbitrary_focus_ring(),
4276 border in arbitrary_border(),
4277 center_focused_column in arbitrary_center_focused_column(),
4278 ) -> Options {
4279 Options {
4280 gaps,
4281 struts,
4282 center_focused_column,
4283 focus_ring,
4284 border,
4285 ..Default::default()
4286 }
4287 }
4288 }
4289
4290 proptest! {
4291 #![proptest_config(ProptestConfig {
4292 cases: if std::env::var_os("RUN_SLOW_TESTS").is_none() {
4293 eprintln!("ignoring slow test");
4294 0
4295 } else {
4296 ProptestConfig::default().cases
4297 },
4298 ..ProptestConfig::default()
4299 })]
4300
4301 #[test]
4302 fn random_operations_dont_panic(ops: Vec<Op>, options in arbitrary_options()) {
4303 // eprintln!("{ops:?}");
4304 check_ops_with_options(options, &ops);
4305 }
4306 }
4307}