forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBc658424Ivan Molodetskikh2 years ago1277 commits

mod.rs4368 lines, 144.9 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_column_left_or_to_output(&mut self, output: &Output) -> bool {
1200 if let Some(monitor) = self.active_monitor() {
1201 let workspace = monitor.active_workspace();
1202 let curr_idx = workspace.active_column_idx;
1203
1204 if !workspace.columns.is_empty() && curr_idx != 0 {
1205 monitor.move_left();
1206 return false;
1207 }
1208 }
1209
1210 self.move_column_to_output(output);
1211 true
1212 }
1213
1214 pub fn move_column_right_or_to_output(&mut self, output: &Output) -> bool {
1215 if let Some(monitor) = self.active_monitor() {
1216 let workspace = monitor.active_workspace();
1217 let curr_idx = workspace.active_column_idx;
1218
1219 if !workspace.columns.is_empty() && curr_idx != workspace.columns.len() - 1 {
1220 monitor.move_right();
1221 return false;
1222 }
1223 }
1224
1225 self.move_column_to_output(output);
1226 true
1227 }
1228
1229 pub fn move_down(&mut self) {
1230 let Some(monitor) = self.active_monitor() else {
1231 return;
1232 };
1233 monitor.move_down();
1234 }
1235
1236 pub fn move_up(&mut self) {
1237 let Some(monitor) = self.active_monitor() else {
1238 return;
1239 };
1240 monitor.move_up();
1241 }
1242
1243 pub fn move_down_or_to_workspace_down(&mut self) {
1244 let Some(monitor) = self.active_monitor() else {
1245 return;
1246 };
1247 monitor.move_down_or_to_workspace_down();
1248 }
1249
1250 pub fn move_up_or_to_workspace_up(&mut self) {
1251 let Some(monitor) = self.active_monitor() else {
1252 return;
1253 };
1254 monitor.move_up_or_to_workspace_up();
1255 }
1256
1257 pub fn consume_or_expel_window_left(&mut self) {
1258 let Some(monitor) = self.active_monitor() else {
1259 return;
1260 };
1261 monitor.consume_or_expel_window_left();
1262 }
1263
1264 pub fn consume_or_expel_window_right(&mut self) {
1265 let Some(monitor) = self.active_monitor() else {
1266 return;
1267 };
1268 monitor.consume_or_expel_window_right();
1269 }
1270
1271 pub fn focus_left(&mut self) {
1272 let Some(monitor) = self.active_monitor() else {
1273 return;
1274 };
1275 monitor.focus_left();
1276 }
1277
1278 pub fn focus_right(&mut self) {
1279 let Some(monitor) = self.active_monitor() else {
1280 return;
1281 };
1282 monitor.focus_right();
1283 }
1284
1285 pub fn focus_column_first(&mut self) {
1286 let Some(monitor) = self.active_monitor() else {
1287 return;
1288 };
1289 monitor.focus_column_first();
1290 }
1291
1292 pub fn focus_column_last(&mut self) {
1293 let Some(monitor) = self.active_monitor() else {
1294 return;
1295 };
1296 monitor.focus_column_last();
1297 }
1298
1299 pub fn focus_column_right_or_first(&mut self) {
1300 let Some(monitor) = self.active_monitor() else {
1301 return;
1302 };
1303 monitor.focus_column_right_or_first();
1304 }
1305
1306 pub fn focus_column_left_or_last(&mut self) {
1307 let Some(monitor) = self.active_monitor() else {
1308 return;
1309 };
1310 monitor.focus_column_left_or_last();
1311 }
1312
1313 pub fn focus_window_up_or_output(&mut self, output: &Output) -> bool {
1314 if let Some(monitor) = self.active_monitor() {
1315 let workspace = monitor.active_workspace();
1316
1317 if !workspace.columns.is_empty() {
1318 let curr_idx = workspace.columns[workspace.active_column_idx].active_tile_idx;
1319 let new_idx = curr_idx.saturating_sub(1);
1320 if curr_idx != new_idx {
1321 workspace.focus_up();
1322 return false;
1323 }
1324 }
1325 }
1326
1327 self.focus_output(output);
1328 true
1329 }
1330
1331 pub fn focus_window_down_or_output(&mut self, output: &Output) -> bool {
1332 if let Some(monitor) = self.active_monitor() {
1333 let workspace = monitor.active_workspace();
1334
1335 if !workspace.columns.is_empty() {
1336 let column = &workspace.columns[workspace.active_column_idx];
1337 let curr_idx = column.active_tile_idx;
1338 let new_idx = min(column.active_tile_idx + 1, column.tiles.len() - 1);
1339 if curr_idx != new_idx {
1340 workspace.focus_down();
1341 return false;
1342 }
1343 }
1344 }
1345
1346 self.focus_output(output);
1347 true
1348 }
1349
1350 pub fn focus_column_left_or_output(&mut self, output: &Output) -> bool {
1351 if let Some(monitor) = self.active_monitor() {
1352 let workspace = monitor.active_workspace();
1353 let curr_idx = workspace.active_column_idx;
1354
1355 if !workspace.columns.is_empty() && curr_idx != 0 {
1356 monitor.focus_left();
1357 return false;
1358 }
1359 }
1360
1361 self.focus_output(output);
1362 true
1363 }
1364
1365 pub fn focus_column_right_or_output(&mut self, output: &Output) -> bool {
1366 if let Some(monitor) = self.active_monitor() {
1367 let workspace = monitor.active_workspace();
1368 let curr_idx = workspace.active_column_idx;
1369 let columns = &workspace.columns;
1370
1371 if !workspace.columns.is_empty() && curr_idx != columns.len() - 1 {
1372 monitor.focus_right();
1373 return false;
1374 }
1375 }
1376
1377 self.focus_output(output);
1378 true
1379 }
1380
1381 pub fn focus_down(&mut self) {
1382 let Some(monitor) = self.active_monitor() else {
1383 return;
1384 };
1385 monitor.focus_down();
1386 }
1387
1388 pub fn focus_up(&mut self) {
1389 let Some(monitor) = self.active_monitor() else {
1390 return;
1391 };
1392 monitor.focus_up();
1393 }
1394
1395 pub fn focus_down_or_left(&mut self) {
1396 let Some(monitor) = self.active_monitor() else {
1397 return;
1398 };
1399 monitor.focus_down_or_left();
1400 }
1401
1402 pub fn focus_down_or_right(&mut self) {
1403 let Some(monitor) = self.active_monitor() else {
1404 return;
1405 };
1406 monitor.focus_down_or_right();
1407 }
1408
1409 pub fn focus_up_or_left(&mut self) {
1410 let Some(monitor) = self.active_monitor() else {
1411 return;
1412 };
1413 monitor.focus_up_or_left();
1414 }
1415
1416 pub fn focus_up_or_right(&mut self) {
1417 let Some(monitor) = self.active_monitor() else {
1418 return;
1419 };
1420 monitor.focus_up_or_right();
1421 }
1422
1423 pub fn focus_window_or_workspace_down(&mut self) {
1424 let Some(monitor) = self.active_monitor() else {
1425 return;
1426 };
1427 monitor.focus_window_or_workspace_down();
1428 }
1429
1430 pub fn focus_window_or_workspace_up(&mut self) {
1431 let Some(monitor) = self.active_monitor() else {
1432 return;
1433 };
1434 monitor.focus_window_or_workspace_up();
1435 }
1436
1437 pub fn move_to_workspace_up(&mut self) {
1438 let Some(monitor) = self.active_monitor() else {
1439 return;
1440 };
1441 monitor.move_to_workspace_up();
1442 }
1443
1444 pub fn move_to_workspace_down(&mut self) {
1445 let Some(monitor) = self.active_monitor() else {
1446 return;
1447 };
1448 monitor.move_to_workspace_down();
1449 }
1450
1451 pub fn move_to_workspace(&mut self, idx: usize) {
1452 let Some(monitor) = self.active_monitor() else {
1453 return;
1454 };
1455 monitor.move_to_workspace(idx);
1456 }
1457
1458 pub fn move_to_workspace_on_output(&mut self, output: &Output, idx: usize) {
1459 self.move_to_output(output);
1460 self.focus_output(output);
1461 self.move_to_workspace(idx);
1462 }
1463
1464 pub fn move_column_to_workspace_up(&mut self) {
1465 let Some(monitor) = self.active_monitor() else {
1466 return;
1467 };
1468 monitor.move_column_to_workspace_up();
1469 }
1470
1471 pub fn move_column_to_workspace_down(&mut self) {
1472 let Some(monitor) = self.active_monitor() else {
1473 return;
1474 };
1475 monitor.move_column_to_workspace_down();
1476 }
1477
1478 pub fn move_column_to_workspace(&mut self, idx: usize) {
1479 let Some(monitor) = self.active_monitor() else {
1480 return;
1481 };
1482 monitor.move_column_to_workspace(idx);
1483 }
1484
1485 pub fn move_column_to_workspace_on_output(&mut self, output: &Output, idx: usize) {
1486 self.move_to_output(output);
1487 self.focus_output(output);
1488 self.move_column_to_workspace(idx);
1489 }
1490
1491 pub fn switch_workspace_up(&mut self) {
1492 let Some(monitor) = self.active_monitor() else {
1493 return;
1494 };
1495 monitor.switch_workspace_up();
1496 }
1497
1498 pub fn switch_workspace_down(&mut self) {
1499 let Some(monitor) = self.active_monitor() else {
1500 return;
1501 };
1502 monitor.switch_workspace_down();
1503 }
1504
1505 pub fn switch_workspace(&mut self, idx: usize) {
1506 let Some(monitor) = self.active_monitor() else {
1507 return;
1508 };
1509 monitor.switch_workspace(idx, false);
1510 }
1511
1512 pub fn switch_workspace_auto_back_and_forth(&mut self, idx: usize) {
1513 let Some(monitor) = self.active_monitor() else {
1514 return;
1515 };
1516 monitor.switch_workspace_auto_back_and_forth(idx);
1517 }
1518
1519 pub fn switch_workspace_previous(&mut self) {
1520 let Some(monitor) = self.active_monitor() else {
1521 return;
1522 };
1523 monitor.switch_workspace_previous();
1524 }
1525
1526 pub fn consume_into_column(&mut self) {
1527 let Some(monitor) = self.active_monitor() else {
1528 return;
1529 };
1530 monitor.consume_into_column();
1531 }
1532
1533 pub fn expel_from_column(&mut self) {
1534 let Some(monitor) = self.active_monitor() else {
1535 return;
1536 };
1537 monitor.expel_from_column();
1538 }
1539
1540 pub fn center_column(&mut self) {
1541 let Some(monitor) = self.active_monitor() else {
1542 return;
1543 };
1544 monitor.center_column();
1545 }
1546
1547 pub fn focus(&self) -> Option<&W> {
1548 let MonitorSet::Normal {
1549 monitors,
1550 active_monitor_idx,
1551 ..
1552 } = &self.monitor_set
1553 else {
1554 return None;
1555 };
1556
1557 monitors[*active_monitor_idx].focus()
1558 }
1559
1560 /// Returns the window under the cursor and the position of its toplevel surface within the
1561 /// output.
1562 ///
1563 /// `Some((w, Some(p)))` means that the cursor is within the window's input region and can be
1564 /// used for delivering events to the window. `Some((w, None))` means that the cursor is within
1565 /// the window's activation region, but not within the window's input region. For example, the
1566 /// cursor may be on the window's server-side border.
1567 pub fn window_under(
1568 &self,
1569 output: &Output,
1570 pos_within_output: Point<f64, Logical>,
1571 ) -> Option<(&W, Option<Point<f64, Logical>>)> {
1572 let MonitorSet::Normal { monitors, .. } = &self.monitor_set else {
1573 return None;
1574 };
1575
1576 let mon = monitors.iter().find(|mon| &mon.output == output)?;
1577 mon.window_under(pos_within_output)
1578 }
1579
1580 pub fn resize_edges_under(
1581 &self,
1582 output: &Output,
1583 pos_within_output: Point<f64, Logical>,
1584 ) -> Option<ResizeEdge> {
1585 let MonitorSet::Normal { monitors, .. } = &self.monitor_set else {
1586 return None;
1587 };
1588
1589 let mon = monitors.iter().find(|mon| &mon.output == output)?;
1590 mon.resize_edges_under(pos_within_output)
1591 }
1592
1593 #[cfg(test)]
1594 fn verify_invariants(&self) {
1595 use std::collections::HashSet;
1596
1597 use crate::layout::monitor::WorkspaceSwitch;
1598
1599 let mut seen_workspace_id = HashSet::new();
1600 let mut seen_workspace_name = Vec::<String>::new();
1601
1602 let (monitors, &primary_idx, &active_monitor_idx) = match &self.monitor_set {
1603 MonitorSet::Normal {
1604 monitors,
1605 primary_idx,
1606 active_monitor_idx,
1607 } => (monitors, primary_idx, active_monitor_idx),
1608 MonitorSet::NoOutputs { workspaces } => {
1609 for workspace in workspaces {
1610 assert!(
1611 workspace.has_windows() || workspace.name.is_some(),
1612 "with no outputs there cannot be empty unnamed workspaces"
1613 );
1614
1615 assert_eq!(
1616 workspace.base_options, self.options,
1617 "workspace base options must be synchronized with layout"
1618 );
1619
1620 let options = Options::clone(&workspace.base_options)
1621 .adjusted_for_scale(workspace.scale().fractional_scale());
1622 assert_eq!(
1623 &*workspace.options, &options,
1624 "workspace options must be base options adjusted for workspace scale"
1625 );
1626
1627 assert!(
1628 seen_workspace_id.insert(workspace.id()),
1629 "workspace id must be unique"
1630 );
1631
1632 if let Some(name) = &workspace.name {
1633 assert!(
1634 !seen_workspace_name
1635 .iter()
1636 .any(|n| n.eq_ignore_ascii_case(name)),
1637 "workspace name must be unique"
1638 );
1639 seen_workspace_name.push(name.clone());
1640 }
1641
1642 workspace.verify_invariants();
1643 }
1644
1645 return;
1646 }
1647 };
1648
1649 assert!(primary_idx < monitors.len());
1650 assert!(active_monitor_idx < monitors.len());
1651
1652 for (idx, monitor) in monitors.iter().enumerate() {
1653 assert!(
1654 !monitor.workspaces.is_empty(),
1655 "monitor must have at least one workspace"
1656 );
1657 assert!(monitor.active_workspace_idx < monitor.workspaces.len());
1658
1659 assert_eq!(
1660 monitor.options, self.options,
1661 "monitor options must be synchronized with layout"
1662 );
1663
1664 if let Some(WorkspaceSwitch::Animation(anim)) = &monitor.workspace_switch {
1665 let before_idx = anim.from() as usize;
1666 let after_idx = anim.to() as usize;
1667
1668 assert!(before_idx < monitor.workspaces.len());
1669 assert!(after_idx < monitor.workspaces.len());
1670 }
1671
1672 let monitor_id = OutputId::new(&monitor.output);
1673
1674 if idx == primary_idx {
1675 for ws in &monitor.workspaces {
1676 if ws.original_output == monitor_id {
1677 // This is the primary monitor's own workspace.
1678 continue;
1679 }
1680
1681 let own_monitor_exists = monitors
1682 .iter()
1683 .any(|m| OutputId::new(&m.output) == ws.original_output);
1684 assert!(
1685 !own_monitor_exists,
1686 "primary monitor cannot have workspaces for which their own monitor exists"
1687 );
1688 }
1689 } else {
1690 assert!(
1691 monitor
1692 .workspaces
1693 .iter()
1694 .any(|workspace| workspace.original_output == monitor_id),
1695 "secondary monitor must not have any non-own workspaces"
1696 );
1697 }
1698
1699 assert!(
1700 monitor.workspaces.last().unwrap().columns.is_empty(),
1701 "monitor must have an empty workspace in the end"
1702 );
1703
1704 assert!(
1705 monitor.workspaces.last().unwrap().name.is_none(),
1706 "monitor must have an unnamed workspace in the end"
1707 );
1708
1709 // If there's no workspace switch in progress, there can't be any non-last non-active
1710 // empty workspaces.
1711 if monitor.workspace_switch.is_none() {
1712 for (idx, ws) in monitor.workspaces.iter().enumerate().rev().skip(1) {
1713 if idx != monitor.active_workspace_idx {
1714 assert!(
1715 !ws.columns.is_empty() || ws.name.is_some(),
1716 "non-active workspace can't be empty and unnamed except the last one"
1717 );
1718 }
1719 }
1720 }
1721
1722 // FIXME: verify that primary doesn't have any workspaces for which their own monitor
1723 // exists.
1724
1725 for workspace in &monitor.workspaces {
1726 assert_eq!(
1727 workspace.base_options, self.options,
1728 "workspace options must be synchronized with layout"
1729 );
1730
1731 let options = Options::clone(&workspace.base_options)
1732 .adjusted_for_scale(workspace.scale().fractional_scale());
1733 assert_eq!(
1734 &*workspace.options, &options,
1735 "workspace options must be base options adjusted for workspace scale"
1736 );
1737
1738 assert!(
1739 seen_workspace_id.insert(workspace.id()),
1740 "workspace id must be unique"
1741 );
1742
1743 if let Some(name) = &workspace.name {
1744 assert!(
1745 !seen_workspace_name
1746 .iter()
1747 .any(|n| n.eq_ignore_ascii_case(name)),
1748 "workspace name must be unique"
1749 );
1750 seen_workspace_name.push(name.clone());
1751 }
1752
1753 workspace.verify_invariants();
1754 }
1755 }
1756 }
1757
1758 pub fn advance_animations(&mut self, current_time: Duration) {
1759 let _span = tracy_client::span!("Layout::advance_animations");
1760
1761 match &mut self.monitor_set {
1762 MonitorSet::Normal { monitors, .. } => {
1763 for mon in monitors {
1764 mon.advance_animations(current_time);
1765 }
1766 }
1767 MonitorSet::NoOutputs { workspaces, .. } => {
1768 for ws in workspaces {
1769 ws.advance_animations(current_time);
1770 }
1771 }
1772 }
1773 }
1774
1775 pub fn update_render_elements(&mut self, output: &Output) {
1776 let _span = tracy_client::span!("Layout::update_render_elements");
1777
1778 let MonitorSet::Normal {
1779 monitors,
1780 active_monitor_idx,
1781 ..
1782 } = &mut self.monitor_set
1783 else {
1784 error!("update_render_elements called with no monitors");
1785 return;
1786 };
1787
1788 for (idx, mon) in monitors.iter_mut().enumerate() {
1789 if mon.output == *output {
1790 mon.update_render_elements(idx == *active_monitor_idx);
1791 return;
1792 }
1793 }
1794 }
1795
1796 pub fn update_render_elements_all(&mut self) {
1797 let _span = tracy_client::span!("Layout::update_render_elements_all");
1798
1799 let MonitorSet::Normal {
1800 monitors,
1801 active_monitor_idx,
1802 ..
1803 } = &mut self.monitor_set
1804 else {
1805 error!("update_render_elements_all called with no monitors");
1806 return;
1807 };
1808
1809 for (idx, mon) in monitors.iter_mut().enumerate() {
1810 mon.update_render_elements(idx == *active_monitor_idx);
1811 }
1812 }
1813
1814 pub fn update_shaders(&mut self) {
1815 match &mut self.monitor_set {
1816 MonitorSet::Normal { monitors, .. } => {
1817 for mon in monitors {
1818 for ws in &mut mon.workspaces {
1819 ws.update_shaders();
1820 }
1821 }
1822 }
1823 MonitorSet::NoOutputs { workspaces, .. } => {
1824 for ws in workspaces {
1825 ws.update_shaders();
1826 }
1827 }
1828 }
1829 }
1830
1831 pub fn ensure_named_workspace(&mut self, ws_config: &WorkspaceConfig) {
1832 if self.find_workspace_by_name(&ws_config.name.0).is_some() {
1833 return;
1834 }
1835
1836 let options = self.options.clone();
1837
1838 match &mut self.monitor_set {
1839 MonitorSet::Normal {
1840 monitors,
1841 primary_idx,
1842 active_monitor_idx,
1843 } => {
1844 let mon_idx = ws_config
1845 .open_on_output
1846 .as_deref()
1847 .map(|name| {
1848 monitors
1849 .iter_mut()
1850 .position(|monitor| monitor.output.name().eq_ignore_ascii_case(name))
1851 .unwrap_or(*primary_idx)
1852 })
1853 .unwrap_or(*active_monitor_idx);
1854 let mon = &mut monitors[mon_idx];
1855
1856 let ws = Workspace::new_with_config(
1857 mon.output.clone(),
1858 Some(ws_config.clone()),
1859 options,
1860 );
1861 mon.workspaces.insert(0, ws);
1862 mon.active_workspace_idx += 1;
1863 mon.workspace_switch = None;
1864 mon.clean_up_workspaces();
1865 }
1866 MonitorSet::NoOutputs { workspaces } => {
1867 let ws = Workspace::new_with_config_no_outputs(Some(ws_config.clone()), options);
1868 workspaces.insert(0, ws);
1869 }
1870 }
1871 }
1872
1873 pub fn update_config(&mut self, config: &Config) {
1874 let options = Rc::new(Options::from_config(config));
1875
1876 match &mut self.monitor_set {
1877 MonitorSet::Normal { monitors, .. } => {
1878 for mon in monitors {
1879 mon.update_config(options.clone());
1880 }
1881 }
1882 MonitorSet::NoOutputs { workspaces } => {
1883 for ws in workspaces {
1884 ws.update_config(options.clone());
1885 }
1886 }
1887 }
1888
1889 self.options = options;
1890 }
1891
1892 pub fn toggle_width(&mut self) {
1893 let Some(monitor) = self.active_monitor() else {
1894 return;
1895 };
1896 monitor.toggle_width();
1897 }
1898
1899 pub fn toggle_full_width(&mut self) {
1900 let Some(monitor) = self.active_monitor() else {
1901 return;
1902 };
1903 monitor.toggle_full_width();
1904 }
1905
1906 pub fn set_column_width(&mut self, change: SizeChange) {
1907 let Some(monitor) = self.active_monitor() else {
1908 return;
1909 };
1910 monitor.set_column_width(change);
1911 }
1912
1913 pub fn set_window_height(&mut self, change: SizeChange) {
1914 let Some(monitor) = self.active_monitor() else {
1915 return;
1916 };
1917 monitor.set_window_height(change);
1918 }
1919
1920 pub fn reset_window_height(&mut self) {
1921 let Some(monitor) = self.active_monitor() else {
1922 return;
1923 };
1924 monitor.reset_window_height();
1925 }
1926
1927 pub fn focus_output(&mut self, output: &Output) {
1928 if let MonitorSet::Normal {
1929 monitors,
1930 active_monitor_idx,
1931 ..
1932 } = &mut self.monitor_set
1933 {
1934 for (idx, mon) in monitors.iter().enumerate() {
1935 if &mon.output == output {
1936 *active_monitor_idx = idx;
1937 return;
1938 }
1939 }
1940 }
1941 }
1942
1943 pub fn move_to_output(&mut self, output: &Output) {
1944 if let MonitorSet::Normal {
1945 monitors,
1946 active_monitor_idx,
1947 ..
1948 } = &mut self.monitor_set
1949 {
1950 let new_idx = monitors
1951 .iter()
1952 .position(|mon| &mon.output == output)
1953 .unwrap();
1954
1955 let current = &mut monitors[*active_monitor_idx];
1956 let ws = current.active_workspace();
1957 if !ws.has_windows() {
1958 return;
1959 }
1960 let column = &ws.columns[ws.active_column_idx];
1961 let width = column.width;
1962 let is_full_width = column.is_full_width;
1963 let window = ws
1964 .remove_tile_by_idx(ws.active_column_idx, column.active_tile_idx, None)
1965 .into_window();
1966
1967 let workspace_idx = monitors[new_idx].active_workspace_idx;
1968 self.add_window_by_idx(new_idx, workspace_idx, window, true, width, is_full_width);
1969 }
1970 }
1971
1972 pub fn move_column_to_output(&mut self, output: &Output) {
1973 if let MonitorSet::Normal {
1974 monitors,
1975 active_monitor_idx,
1976 ..
1977 } = &mut self.monitor_set
1978 {
1979 let new_idx = monitors
1980 .iter()
1981 .position(|mon| &mon.output == output)
1982 .unwrap();
1983
1984 let current = &mut monitors[*active_monitor_idx];
1985 let ws = current.active_workspace();
1986 if !ws.has_windows() {
1987 return;
1988 }
1989 let column = ws.remove_column_by_idx(ws.active_column_idx);
1990
1991 let workspace_idx = monitors[new_idx].active_workspace_idx;
1992 self.add_column_by_idx(new_idx, workspace_idx, column, true);
1993 }
1994 }
1995
1996 pub fn move_window_to_output(&mut self, window: &W::Id, output: &Output) {
1997 let mut width = None;
1998 let mut is_full_width = false;
1999
2000 if let MonitorSet::Normal { monitors, .. } = &mut self.monitor_set {
2001 for mon in &*monitors {
2002 for ws in &mon.workspaces {
2003 for col in &ws.columns {
2004 if col.contains(window) {
2005 width = Some(col.width);
2006 is_full_width = col.is_full_width;
2007 break;
2008 }
2009 }
2010 }
2011 }
2012 }
2013
2014 let Some(width) = width else { return };
2015
2016 let window = self.remove_window(window).unwrap();
2017
2018 if let MonitorSet::Normal { monitors, .. } = &mut self.monitor_set {
2019 let new_idx = monitors
2020 .iter()
2021 .position(|mon| &mon.output == output)
2022 .unwrap();
2023
2024 let workspace_idx = monitors[new_idx].active_workspace_idx;
2025 // FIXME: activate only if it was already active and focused.
2026 self.add_window_by_idx(new_idx, workspace_idx, window, true, width, is_full_width);
2027 }
2028 }
2029
2030 pub fn move_workspace_to_output(&mut self, output: &Output) {
2031 let MonitorSet::Normal {
2032 monitors,
2033 active_monitor_idx,
2034 ..
2035 } = &mut self.monitor_set
2036 else {
2037 return;
2038 };
2039
2040 let current = &mut monitors[*active_monitor_idx];
2041 if current.active_workspace_idx == current.workspaces.len() - 1 {
2042 // Insert a new empty workspace.
2043 let ws = Workspace::new(current.output.clone(), current.options.clone());
2044 current.workspaces.push(ws);
2045 }
2046 let mut ws = current.workspaces.remove(current.active_workspace_idx);
2047 current.active_workspace_idx = current.active_workspace_idx.saturating_sub(1);
2048 current.workspace_switch = None;
2049 current.clean_up_workspaces();
2050
2051 ws.set_output(Some(output.clone()));
2052 ws.original_output = OutputId::new(output);
2053
2054 let target_idx = monitors
2055 .iter()
2056 .position(|mon| &mon.output == output)
2057 .unwrap();
2058 let target = &mut monitors[target_idx];
2059
2060 target.previous_workspace_id = Some(target.workspaces[target.active_workspace_idx].id());
2061
2062 // Insert the workspace after the currently active one. Unless the currently active one is
2063 // the last empty workspace, then insert before.
2064 let target_ws_idx = min(target.active_workspace_idx + 1, target.workspaces.len() - 1);
2065 target.workspaces.insert(target_ws_idx, ws);
2066 target.active_workspace_idx = target_ws_idx;
2067 target.workspace_switch = None;
2068 target.clean_up_workspaces();
2069
2070 *active_monitor_idx = target_idx;
2071 }
2072
2073 pub fn set_fullscreen(&mut self, window: &W::Id, is_fullscreen: bool) {
2074 match &mut self.monitor_set {
2075 MonitorSet::Normal { monitors, .. } => {
2076 for mon in monitors {
2077 for ws in &mut mon.workspaces {
2078 if ws.has_window(window) {
2079 ws.set_fullscreen(window, is_fullscreen);
2080 return;
2081 }
2082 }
2083 }
2084 }
2085 MonitorSet::NoOutputs { workspaces, .. } => {
2086 for ws in workspaces {
2087 if ws.has_window(window) {
2088 ws.set_fullscreen(window, is_fullscreen);
2089 return;
2090 }
2091 }
2092 }
2093 }
2094 }
2095
2096 pub fn toggle_fullscreen(&mut self, window: &W::Id) {
2097 match &mut self.monitor_set {
2098 MonitorSet::Normal { monitors, .. } => {
2099 for mon in monitors {
2100 for ws in &mut mon.workspaces {
2101 if ws.has_window(window) {
2102 ws.toggle_fullscreen(window);
2103 return;
2104 }
2105 }
2106 }
2107 }
2108 MonitorSet::NoOutputs { workspaces, .. } => {
2109 for ws in workspaces {
2110 if ws.has_window(window) {
2111 ws.toggle_fullscreen(window);
2112 return;
2113 }
2114 }
2115 }
2116 }
2117 }
2118
2119 pub fn workspace_switch_gesture_begin(&mut self, output: &Output, is_touchpad: bool) {
2120 let monitors = match &mut self.monitor_set {
2121 MonitorSet::Normal { monitors, .. } => monitors,
2122 MonitorSet::NoOutputs { .. } => unreachable!(),
2123 };
2124
2125 for monitor in monitors {
2126 // Cancel the gesture on other outputs.
2127 if &monitor.output != output {
2128 monitor.workspace_switch_gesture_end(true, None);
2129 continue;
2130 }
2131
2132 monitor.workspace_switch_gesture_begin(is_touchpad);
2133 }
2134 }
2135
2136 pub fn workspace_switch_gesture_update(
2137 &mut self,
2138 delta_y: f64,
2139 timestamp: Duration,
2140 is_touchpad: bool,
2141 ) -> Option<Option<Output>> {
2142 let monitors = match &mut self.monitor_set {
2143 MonitorSet::Normal { monitors, .. } => monitors,
2144 MonitorSet::NoOutputs { .. } => return None,
2145 };
2146
2147 for monitor in monitors {
2148 if let Some(refresh) =
2149 monitor.workspace_switch_gesture_update(delta_y, timestamp, is_touchpad)
2150 {
2151 if refresh {
2152 return Some(Some(monitor.output.clone()));
2153 } else {
2154 return Some(None);
2155 }
2156 }
2157 }
2158
2159 None
2160 }
2161
2162 pub fn workspace_switch_gesture_end(
2163 &mut self,
2164 cancelled: bool,
2165 is_touchpad: Option<bool>,
2166 ) -> Option<Output> {
2167 let monitors = match &mut self.monitor_set {
2168 MonitorSet::Normal { monitors, .. } => monitors,
2169 MonitorSet::NoOutputs { .. } => return None,
2170 };
2171
2172 for monitor in monitors {
2173 if monitor.workspace_switch_gesture_end(cancelled, is_touchpad) {
2174 return Some(monitor.output.clone());
2175 }
2176 }
2177
2178 None
2179 }
2180
2181 pub fn view_offset_gesture_begin(&mut self, output: &Output, is_touchpad: bool) {
2182 let monitors = match &mut self.monitor_set {
2183 MonitorSet::Normal { monitors, .. } => monitors,
2184 MonitorSet::NoOutputs { .. } => unreachable!(),
2185 };
2186
2187 for monitor in monitors {
2188 for (idx, ws) in monitor.workspaces.iter_mut().enumerate() {
2189 // Cancel the gesture on other workspaces.
2190 if &monitor.output != output || idx != monitor.active_workspace_idx {
2191 ws.view_offset_gesture_end(true, None);
2192 continue;
2193 }
2194
2195 ws.view_offset_gesture_begin(is_touchpad);
2196 }
2197 }
2198 }
2199
2200 pub fn view_offset_gesture_update(
2201 &mut self,
2202 delta_x: f64,
2203 timestamp: Duration,
2204 is_touchpad: bool,
2205 ) -> Option<Option<Output>> {
2206 let monitors = match &mut self.monitor_set {
2207 MonitorSet::Normal { monitors, .. } => monitors,
2208 MonitorSet::NoOutputs { .. } => return None,
2209 };
2210
2211 for monitor in monitors {
2212 for ws in &mut monitor.workspaces {
2213 if let Some(refresh) =
2214 ws.view_offset_gesture_update(delta_x, timestamp, is_touchpad)
2215 {
2216 if refresh {
2217 return Some(Some(monitor.output.clone()));
2218 } else {
2219 return Some(None);
2220 }
2221 }
2222 }
2223 }
2224
2225 None
2226 }
2227
2228 pub fn view_offset_gesture_end(
2229 &mut self,
2230 cancelled: bool,
2231 is_touchpad: Option<bool>,
2232 ) -> Option<Output> {
2233 let monitors = match &mut self.monitor_set {
2234 MonitorSet::Normal { monitors, .. } => monitors,
2235 MonitorSet::NoOutputs { .. } => return None,
2236 };
2237
2238 for monitor in monitors {
2239 for ws in &mut monitor.workspaces {
2240 if ws.view_offset_gesture_end(cancelled, is_touchpad) {
2241 return Some(monitor.output.clone());
2242 }
2243 }
2244 }
2245
2246 None
2247 }
2248
2249 pub fn interactive_resize_begin(&mut self, window: W::Id, edges: ResizeEdge) -> bool {
2250 match &mut self.monitor_set {
2251 MonitorSet::Normal { monitors, .. } => {
2252 for mon in monitors {
2253 for ws in &mut mon.workspaces {
2254 if ws.has_window(&window) {
2255 return ws.interactive_resize_begin(window, edges);
2256 }
2257 }
2258 }
2259 }
2260 MonitorSet::NoOutputs { workspaces, .. } => {
2261 for ws in workspaces {
2262 if ws.has_window(&window) {
2263 return ws.interactive_resize_begin(window, edges);
2264 }
2265 }
2266 }
2267 }
2268
2269 false
2270 }
2271
2272 pub fn interactive_resize_update(
2273 &mut self,
2274 window: &W::Id,
2275 delta: Point<f64, Logical>,
2276 ) -> bool {
2277 match &mut self.monitor_set {
2278 MonitorSet::Normal { monitors, .. } => {
2279 for mon in monitors {
2280 for ws in &mut mon.workspaces {
2281 if ws.has_window(window) {
2282 return ws.interactive_resize_update(window, delta);
2283 }
2284 }
2285 }
2286 }
2287 MonitorSet::NoOutputs { workspaces, .. } => {
2288 for ws in workspaces {
2289 if ws.has_window(window) {
2290 return ws.interactive_resize_update(window, delta);
2291 }
2292 }
2293 }
2294 }
2295
2296 false
2297 }
2298
2299 pub fn interactive_resize_end(&mut self, window: &W::Id) {
2300 match &mut self.monitor_set {
2301 MonitorSet::Normal { monitors, .. } => {
2302 for mon in monitors {
2303 for ws in &mut mon.workspaces {
2304 if ws.has_window(window) {
2305 ws.interactive_resize_end(Some(window));
2306 return;
2307 }
2308 }
2309 }
2310 }
2311 MonitorSet::NoOutputs { workspaces, .. } => {
2312 for ws in workspaces {
2313 if ws.has_window(window) {
2314 ws.interactive_resize_end(Some(window));
2315 return;
2316 }
2317 }
2318 }
2319 }
2320 }
2321
2322 pub fn move_workspace_down(&mut self) {
2323 let Some(monitor) = self.active_monitor() else {
2324 return;
2325 };
2326 monitor.move_workspace_down();
2327 }
2328
2329 pub fn move_workspace_up(&mut self) {
2330 let Some(monitor) = self.active_monitor() else {
2331 return;
2332 };
2333 monitor.move_workspace_up();
2334 }
2335
2336 pub fn start_open_animation_for_window(&mut self, window: &W::Id) {
2337 match &mut self.monitor_set {
2338 MonitorSet::Normal { monitors, .. } => {
2339 for mon in monitors {
2340 for ws in &mut mon.workspaces {
2341 for col in &mut ws.columns {
2342 for tile in &mut col.tiles {
2343 if tile.window().id() == window {
2344 tile.start_open_animation();
2345 return;
2346 }
2347 }
2348 }
2349 }
2350 }
2351 }
2352 MonitorSet::NoOutputs { workspaces, .. } => {
2353 for ws in workspaces {
2354 for col in &mut ws.columns {
2355 for tile in &mut col.tiles {
2356 if tile.window().id() == window {
2357 tile.start_open_animation();
2358 return;
2359 }
2360 }
2361 }
2362 }
2363 }
2364 }
2365 }
2366
2367 pub fn store_unmap_snapshot(&mut self, renderer: &mut GlesRenderer, window: &W::Id) {
2368 let _span = tracy_client::span!("Layout::store_unmap_snapshot");
2369
2370 match &mut self.monitor_set {
2371 MonitorSet::Normal { monitors, .. } => {
2372 for mon in monitors {
2373 for ws in &mut mon.workspaces {
2374 if ws.has_window(window) {
2375 ws.store_unmap_snapshot_if_empty(renderer, window);
2376 return;
2377 }
2378 }
2379 }
2380 }
2381 MonitorSet::NoOutputs { workspaces, .. } => {
2382 for ws in workspaces {
2383 if ws.has_window(window) {
2384 ws.store_unmap_snapshot_if_empty(renderer, window);
2385 return;
2386 }
2387 }
2388 }
2389 }
2390 }
2391
2392 pub fn clear_unmap_snapshot(&mut self, window: &W::Id) {
2393 match &mut self.monitor_set {
2394 MonitorSet::Normal { monitors, .. } => {
2395 for mon in monitors {
2396 for ws in &mut mon.workspaces {
2397 if ws.has_window(window) {
2398 ws.clear_unmap_snapshot(window);
2399 return;
2400 }
2401 }
2402 }
2403 }
2404 MonitorSet::NoOutputs { workspaces, .. } => {
2405 for ws in workspaces {
2406 if ws.has_window(window) {
2407 ws.clear_unmap_snapshot(window);
2408 return;
2409 }
2410 }
2411 }
2412 }
2413 }
2414
2415 pub fn start_close_animation_for_window(
2416 &mut self,
2417 renderer: &mut GlesRenderer,
2418 window: &W::Id,
2419 ) {
2420 let _span = tracy_client::span!("Layout::start_close_animation_for_window");
2421
2422 match &mut self.monitor_set {
2423 MonitorSet::Normal { monitors, .. } => {
2424 for mon in monitors {
2425 for ws in &mut mon.workspaces {
2426 if ws.has_window(window) {
2427 ws.start_close_animation_for_window(renderer, window);
2428 return;
2429 }
2430 }
2431 }
2432 }
2433 MonitorSet::NoOutputs { workspaces, .. } => {
2434 for ws in workspaces {
2435 if ws.has_window(window) {
2436 ws.start_close_animation_for_window(renderer, window);
2437 return;
2438 }
2439 }
2440 }
2441 }
2442 }
2443
2444 pub fn refresh(&mut self) {
2445 let _span = tracy_client::span!("Layout::refresh");
2446
2447 match &mut self.monitor_set {
2448 MonitorSet::Normal {
2449 monitors,
2450 active_monitor_idx,
2451 ..
2452 } => {
2453 for (idx, mon) in monitors.iter_mut().enumerate() {
2454 let is_active = idx == *active_monitor_idx;
2455 for (ws_idx, ws) in mon.workspaces.iter_mut().enumerate() {
2456 ws.refresh(is_active);
2457
2458 // Cancel the view offset gesture after workspace switches, moves, etc.
2459 if ws_idx != mon.active_workspace_idx {
2460 ws.view_offset_gesture_end(false, None);
2461 }
2462 }
2463 }
2464 }
2465 MonitorSet::NoOutputs { workspaces, .. } => {
2466 for ws in workspaces {
2467 ws.refresh(false);
2468 ws.view_offset_gesture_end(false, None);
2469 }
2470 }
2471 }
2472 }
2473
2474 pub fn ipc_workspaces(&self) -> Vec<niri_ipc::Workspace> {
2475 match &self.monitor_set {
2476 MonitorSet::Normal {
2477 monitors,
2478 primary_idx: _,
2479 active_monitor_idx: _,
2480 } => {
2481 let mut workspaces = Vec::new();
2482
2483 for monitor in monitors {
2484 for (idx, workspace) in monitor.workspaces.iter().enumerate() {
2485 workspaces.push(niri_ipc::Workspace {
2486 idx: u8::try_from(idx + 1).unwrap_or(u8::MAX),
2487 name: workspace.name.clone(),
2488 output: Some(monitor.output.name()),
2489 is_active: monitor.active_workspace_idx == idx,
2490 })
2491 }
2492 }
2493
2494 workspaces
2495 }
2496 MonitorSet::NoOutputs { workspaces } => workspaces
2497 .iter()
2498 .enumerate()
2499 .map(|(idx, ws)| niri_ipc::Workspace {
2500 idx: u8::try_from(idx + 1).unwrap_or(u8::MAX),
2501 name: ws.name.clone(),
2502 output: None,
2503 is_active: false,
2504 })
2505 .collect(),
2506 }
2507 }
2508}
2509
2510impl<W: LayoutElement> Default for MonitorSet<W> {
2511 fn default() -> Self {
2512 Self::NoOutputs { workspaces: vec![] }
2513 }
2514}
2515
2516#[cfg(test)]
2517mod tests {
2518 use std::cell::Cell;
2519
2520 use niri_config::{FloatOrInt, WorkspaceName};
2521 use proptest::prelude::*;
2522 use proptest_derive::Arbitrary;
2523 use smithay::output::{Mode, PhysicalProperties, Subpixel};
2524 use smithay::utils::Rectangle;
2525
2526 use super::*;
2527 use crate::utils::round_logical_in_physical;
2528
2529 impl<W: LayoutElement> Default for Layout<W> {
2530 fn default() -> Self {
2531 Self::with_options(Default::default())
2532 }
2533 }
2534
2535 #[derive(Debug)]
2536 struct TestWindowInner {
2537 id: usize,
2538 bbox: Cell<Rectangle<i32, Logical>>,
2539 initial_bbox: Rectangle<i32, Logical>,
2540 requested_size: Cell<Option<Size<i32, Logical>>>,
2541 min_size: Size<i32, Logical>,
2542 max_size: Size<i32, Logical>,
2543 pending_fullscreen: Cell<bool>,
2544 }
2545
2546 #[derive(Debug, Clone)]
2547 struct TestWindow(Rc<TestWindowInner>);
2548
2549 impl TestWindow {
2550 fn new(
2551 id: usize,
2552 bbox: Rectangle<i32, Logical>,
2553 min_size: Size<i32, Logical>,
2554 max_size: Size<i32, Logical>,
2555 ) -> Self {
2556 Self(Rc::new(TestWindowInner {
2557 id,
2558 bbox: Cell::new(bbox),
2559 initial_bbox: bbox,
2560 requested_size: Cell::new(None),
2561 min_size,
2562 max_size,
2563 pending_fullscreen: Cell::new(false),
2564 }))
2565 }
2566
2567 fn communicate(&self) -> bool {
2568 if let Some(size) = self.0.requested_size.take() {
2569 assert!(size.w >= 0);
2570 assert!(size.h >= 0);
2571
2572 let mut new_bbox = self.0.initial_bbox;
2573 if size.w != 0 {
2574 new_bbox.size.w = size.w;
2575 }
2576 if size.h != 0 {
2577 new_bbox.size.h = size.h;
2578 }
2579
2580 if self.0.bbox.get() != new_bbox {
2581 self.0.bbox.set(new_bbox);
2582 return true;
2583 }
2584 }
2585
2586 false
2587 }
2588 }
2589
2590 impl LayoutElement for TestWindow {
2591 type Id = usize;
2592
2593 fn id(&self) -> &Self::Id {
2594 &self.0.id
2595 }
2596
2597 fn size(&self) -> Size<i32, Logical> {
2598 self.0.bbox.get().size
2599 }
2600
2601 fn buf_loc(&self) -> Point<i32, Logical> {
2602 (0, 0).into()
2603 }
2604
2605 fn is_in_input_region(&self, _point: Point<f64, Logical>) -> bool {
2606 false
2607 }
2608
2609 fn render<R: NiriRenderer>(
2610 &self,
2611 _renderer: &mut R,
2612 _location: Point<f64, Logical>,
2613 _scale: Scale<f64>,
2614 _alpha: f32,
2615 _target: RenderTarget,
2616 ) -> SplitElements<LayoutElementRenderElement<R>> {
2617 SplitElements::default()
2618 }
2619
2620 fn request_size(&mut self, size: Size<i32, Logical>, _animate: bool) {
2621 self.0.requested_size.set(Some(size));
2622 self.0.pending_fullscreen.set(false);
2623 }
2624
2625 fn request_fullscreen(&self, _size: Size<i32, Logical>) {
2626 self.0.pending_fullscreen.set(true);
2627 }
2628
2629 fn min_size(&self) -> Size<i32, Logical> {
2630 self.0.min_size
2631 }
2632
2633 fn max_size(&self) -> Size<i32, Logical> {
2634 self.0.max_size
2635 }
2636
2637 fn is_wl_surface(&self, _wl_surface: &WlSurface) -> bool {
2638 false
2639 }
2640
2641 fn set_preferred_scale_transform(&self, _scale: output::Scale, _transform: Transform) {}
2642
2643 fn has_ssd(&self) -> bool {
2644 false
2645 }
2646
2647 fn output_enter(&self, _output: &Output) {}
2648
2649 fn output_leave(&self, _output: &Output) {}
2650
2651 fn set_offscreen_element_id(&self, _id: Option<Id>) {}
2652
2653 fn set_activated(&mut self, _active: bool) {}
2654
2655 fn set_bounds(&self, _bounds: Size<i32, Logical>) {}
2656
2657 fn send_pending_configure(&mut self) {}
2658
2659 fn set_active_in_column(&mut self, _active: bool) {}
2660
2661 fn is_fullscreen(&self) -> bool {
2662 false
2663 }
2664
2665 fn is_pending_fullscreen(&self) -> bool {
2666 self.0.pending_fullscreen.get()
2667 }
2668
2669 fn refresh(&self) {}
2670
2671 fn rules(&self) -> &ResolvedWindowRules {
2672 static EMPTY: ResolvedWindowRules = ResolvedWindowRules::empty();
2673 &EMPTY
2674 }
2675
2676 fn animation_snapshot(&self) -> Option<&LayoutElementRenderSnapshot> {
2677 None
2678 }
2679
2680 fn take_animation_snapshot(&mut self) -> Option<LayoutElementRenderSnapshot> {
2681 None
2682 }
2683
2684 fn set_interactive_resize(&mut self, _data: Option<InteractiveResizeData>) {}
2685
2686 fn cancel_interactive_resize(&mut self) {}
2687
2688 fn update_interactive_resize(&mut self, _serial: Serial) {}
2689
2690 fn interactive_resize_data(&self) -> Option<InteractiveResizeData> {
2691 None
2692 }
2693 }
2694
2695 fn arbitrary_bbox() -> impl Strategy<Value = Rectangle<i32, Logical>> {
2696 any::<(i16, i16, u16, u16)>().prop_map(|(x, y, w, h)| {
2697 let loc: Point<i32, _> = Point::from((x.into(), y.into()));
2698 let size: Size<i32, _> = Size::from((w.into(), h.into()));
2699 Rectangle::from_loc_and_size(loc, size)
2700 })
2701 }
2702
2703 fn arbitrary_size_change() -> impl Strategy<Value = SizeChange> {
2704 prop_oneof![
2705 (0..).prop_map(SizeChange::SetFixed),
2706 (0f64..).prop_map(SizeChange::SetProportion),
2707 any::<i32>().prop_map(SizeChange::AdjustFixed),
2708 any::<f64>().prop_map(SizeChange::AdjustProportion),
2709 ]
2710 }
2711
2712 fn arbitrary_min_max() -> impl Strategy<Value = (i32, i32)> {
2713 prop_oneof![
2714 Just((0, 0)),
2715 (1..65536).prop_map(|n| (n, n)),
2716 (1..65536).prop_map(|min| (min, 0)),
2717 (1..).prop_map(|max| (0, max)),
2718 (1..65536, 1..).prop_map(|(min, max): (i32, i32)| (min, max.max(min))),
2719 ]
2720 }
2721
2722 fn arbitrary_min_max_size() -> impl Strategy<Value = (Size<i32, Logical>, Size<i32, Logical>)> {
2723 (arbitrary_min_max(), arbitrary_min_max()).prop_map(|((min_w, max_w), (min_h, max_h))| {
2724 let min_size = Size::from((min_w, min_h));
2725 let max_size = Size::from((max_w, max_h));
2726 (min_size, max_size)
2727 })
2728 }
2729
2730 fn arbitrary_view_offset_gesture_delta() -> impl Strategy<Value = f64> {
2731 prop_oneof![(-10f64..10f64), (-50000f64..50000f64),]
2732 }
2733
2734 fn arbitrary_resize_edge() -> impl Strategy<Value = ResizeEdge> {
2735 prop_oneof![
2736 Just(ResizeEdge::RIGHT),
2737 Just(ResizeEdge::BOTTOM),
2738 Just(ResizeEdge::LEFT),
2739 Just(ResizeEdge::TOP),
2740 Just(ResizeEdge::BOTTOM_RIGHT),
2741 Just(ResizeEdge::BOTTOM_LEFT),
2742 Just(ResizeEdge::TOP_RIGHT),
2743 Just(ResizeEdge::TOP_LEFT),
2744 Just(ResizeEdge::empty()),
2745 ]
2746 }
2747
2748 fn arbitrary_scale() -> impl Strategy<Value = f64> {
2749 prop_oneof![Just(1.), Just(1.5), Just(2.),]
2750 }
2751
2752 #[derive(Debug, Clone, Copy, Arbitrary)]
2753 enum Op {
2754 AddOutput(#[proptest(strategy = "1..=5usize")] usize),
2755 AddScaledOutput {
2756 #[proptest(strategy = "1..=5usize")]
2757 id: usize,
2758 #[proptest(strategy = "arbitrary_scale()")]
2759 scale: f64,
2760 },
2761 RemoveOutput(#[proptest(strategy = "1..=5usize")] usize),
2762 FocusOutput(#[proptest(strategy = "1..=5usize")] usize),
2763 AddNamedWorkspace {
2764 #[proptest(strategy = "1..=5usize")]
2765 ws_name: usize,
2766 #[proptest(strategy = "prop::option::of(1..=5usize)")]
2767 output_name: Option<usize>,
2768 },
2769 UnnameWorkspace {
2770 #[proptest(strategy = "1..=5usize")]
2771 ws_name: usize,
2772 },
2773 AddWindow {
2774 #[proptest(strategy = "1..=5usize")]
2775 id: usize,
2776 #[proptest(strategy = "arbitrary_bbox()")]
2777 bbox: Rectangle<i32, Logical>,
2778 #[proptest(strategy = "arbitrary_min_max_size()")]
2779 min_max_size: (Size<i32, Logical>, Size<i32, Logical>),
2780 },
2781 AddWindowRightOf {
2782 #[proptest(strategy = "1..=5usize")]
2783 id: usize,
2784 #[proptest(strategy = "1..=5usize")]
2785 right_of_id: usize,
2786 #[proptest(strategy = "arbitrary_bbox()")]
2787 bbox: Rectangle<i32, Logical>,
2788 #[proptest(strategy = "arbitrary_min_max_size()")]
2789 min_max_size: (Size<i32, Logical>, Size<i32, Logical>),
2790 },
2791 AddWindowToNamedWorkspace {
2792 #[proptest(strategy = "1..=5usize")]
2793 id: usize,
2794 #[proptest(strategy = "1..=5usize")]
2795 ws_name: usize,
2796 #[proptest(strategy = "arbitrary_bbox()")]
2797 bbox: Rectangle<i32, Logical>,
2798 #[proptest(strategy = "arbitrary_min_max_size()")]
2799 min_max_size: (Size<i32, Logical>, Size<i32, Logical>),
2800 },
2801 CloseWindow(#[proptest(strategy = "1..=5usize")] usize),
2802 FullscreenWindow(#[proptest(strategy = "1..=5usize")] usize),
2803 SetFullscreenWindow {
2804 #[proptest(strategy = "1..=5usize")]
2805 window: usize,
2806 is_fullscreen: bool,
2807 },
2808 FocusColumnLeft,
2809 FocusColumnRight,
2810 FocusColumnFirst,
2811 FocusColumnLast,
2812 FocusColumnRightOrFirst,
2813 FocusColumnLeftOrLast,
2814 FocusWindowOrMonitorUp(#[proptest(strategy = "1..=2u8")] u8),
2815 FocusWindowOrMonitorDown(#[proptest(strategy = "1..=2u8")] u8),
2816 FocusColumnOrMonitorLeft(#[proptest(strategy = "1..=2u8")] u8),
2817 FocusColumnOrMonitorRight(#[proptest(strategy = "1..=2u8")] u8),
2818 FocusWindowDown,
2819 FocusWindowUp,
2820 FocusWindowDownOrColumnLeft,
2821 FocusWindowDownOrColumnRight,
2822 FocusWindowUpOrColumnLeft,
2823 FocusWindowUpOrColumnRight,
2824 FocusWindowOrWorkspaceDown,
2825 FocusWindowOrWorkspaceUp,
2826 MoveColumnLeft,
2827 MoveColumnRight,
2828 MoveColumnToFirst,
2829 MoveColumnToLast,
2830 MoveColumnLeftOrToMonitorLeft(#[proptest(strategy = "1..=2u8")] u8),
2831 MoveColumnRightOrToMonitorRight(#[proptest(strategy = "1..=2u8")] u8),
2832 MoveWindowDown,
2833 MoveWindowUp,
2834 MoveWindowDownOrToWorkspaceDown,
2835 MoveWindowUpOrToWorkspaceUp,
2836 ConsumeOrExpelWindowLeft,
2837 ConsumeOrExpelWindowRight,
2838 ConsumeWindowIntoColumn,
2839 ExpelWindowFromColumn,
2840 CenterColumn,
2841 FocusWorkspaceDown,
2842 FocusWorkspaceUp,
2843 FocusWorkspace(#[proptest(strategy = "0..=4usize")] usize),
2844 FocusWorkspaceAutoBackAndForth(#[proptest(strategy = "0..=4usize")] usize),
2845 FocusWorkspacePrevious,
2846 MoveWindowToWorkspaceDown,
2847 MoveWindowToWorkspaceUp,
2848 MoveWindowToWorkspace(#[proptest(strategy = "0..=4usize")] usize),
2849 MoveColumnToWorkspaceDown,
2850 MoveColumnToWorkspaceUp,
2851 MoveColumnToWorkspace(#[proptest(strategy = "0..=4usize")] usize),
2852 MoveWorkspaceDown,
2853 MoveWorkspaceUp,
2854 MoveWindowToOutput(#[proptest(strategy = "1..=5u8")] u8),
2855 MoveColumnToOutput(#[proptest(strategy = "1..=5u8")] u8),
2856 SwitchPresetColumnWidth,
2857 MaximizeColumn,
2858 SetColumnWidth(#[proptest(strategy = "arbitrary_size_change()")] SizeChange),
2859 SetWindowHeight(#[proptest(strategy = "arbitrary_size_change()")] SizeChange),
2860 ResetWindowHeight,
2861 Communicate(#[proptest(strategy = "1..=5usize")] usize),
2862 MoveWorkspaceToOutput(#[proptest(strategy = "1..=5u8")] u8),
2863 ViewOffsetGestureBegin {
2864 #[proptest(strategy = "1..=5usize")]
2865 output_idx: usize,
2866 is_touchpad: bool,
2867 },
2868 ViewOffsetGestureUpdate {
2869 #[proptest(strategy = "arbitrary_view_offset_gesture_delta()")]
2870 delta: f64,
2871 timestamp: Duration,
2872 is_touchpad: bool,
2873 },
2874 ViewOffsetGestureEnd {
2875 is_touchpad: Option<bool>,
2876 },
2877 WorkspaceSwitchGestureBegin {
2878 #[proptest(strategy = "1..=5usize")]
2879 output_idx: usize,
2880 is_touchpad: bool,
2881 },
2882 WorkspaceSwitchGestureUpdate {
2883 #[proptest(strategy = "-400f64..400f64")]
2884 delta: f64,
2885 timestamp: Duration,
2886 is_touchpad: bool,
2887 },
2888 WorkspaceSwitchGestureEnd {
2889 cancelled: bool,
2890 is_touchpad: Option<bool>,
2891 },
2892 InteractiveResizeBegin {
2893 #[proptest(strategy = "1..=5usize")]
2894 window: usize,
2895 #[proptest(strategy = "arbitrary_resize_edge()")]
2896 edges: ResizeEdge,
2897 },
2898 InteractiveResizeUpdate {
2899 #[proptest(strategy = "1..=5usize")]
2900 window: usize,
2901 #[proptest(strategy = "-20000f64..20000f64")]
2902 dx: f64,
2903 #[proptest(strategy = "-20000f64..20000f64")]
2904 dy: f64,
2905 },
2906 InteractiveResizeEnd {
2907 #[proptest(strategy = "1..=5usize")]
2908 window: usize,
2909 },
2910 }
2911
2912 impl Op {
2913 fn apply(self, layout: &mut Layout<TestWindow>) {
2914 match self {
2915 Op::AddOutput(id) => {
2916 let name = format!("output{id}");
2917 if layout.outputs().any(|o| o.name() == name) {
2918 return;
2919 }
2920
2921 let output = Output::new(
2922 name,
2923 PhysicalProperties {
2924 size: Size::from((1280, 720)),
2925 subpixel: Subpixel::Unknown,
2926 make: String::new(),
2927 model: String::new(),
2928 },
2929 );
2930 output.change_current_state(
2931 Some(Mode {
2932 size: Size::from((1280, 720)),
2933 refresh: 60000,
2934 }),
2935 None,
2936 None,
2937 None,
2938 );
2939 layout.add_output(output.clone());
2940 }
2941 Op::AddScaledOutput { id, scale } => {
2942 let name = format!("output{id}");
2943 if layout.outputs().any(|o| o.name() == name) {
2944 return;
2945 }
2946
2947 let output = Output::new(
2948 name,
2949 PhysicalProperties {
2950 size: Size::from((1280, 720)),
2951 subpixel: Subpixel::Unknown,
2952 make: String::new(),
2953 model: String::new(),
2954 },
2955 );
2956 output.change_current_state(
2957 Some(Mode {
2958 size: Size::from((1280, 720)),
2959 refresh: 60000,
2960 }),
2961 None,
2962 Some(smithay::output::Scale::Fractional(scale)),
2963 None,
2964 );
2965 layout.add_output(output.clone());
2966 }
2967 Op::RemoveOutput(id) => {
2968 let name = format!("output{id}");
2969 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
2970 return;
2971 };
2972
2973 layout.remove_output(&output);
2974 }
2975 Op::FocusOutput(id) => {
2976 let name = format!("output{id}");
2977 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
2978 return;
2979 };
2980
2981 layout.focus_output(&output);
2982 }
2983 Op::AddNamedWorkspace {
2984 ws_name,
2985 output_name,
2986 } => {
2987 layout.ensure_named_workspace(&WorkspaceConfig {
2988 name: WorkspaceName(format!("ws{ws_name}")),
2989 open_on_output: output_name.map(|name| format!("output{name}")),
2990 });
2991 }
2992 Op::UnnameWorkspace { ws_name } => {
2993 layout.unname_workspace(&format!("ws{ws_name}"));
2994 }
2995 Op::AddWindow {
2996 id,
2997 bbox,
2998 min_max_size,
2999 } => {
3000 match &mut layout.monitor_set {
3001 MonitorSet::Normal { monitors, .. } => {
3002 for mon in monitors {
3003 for ws in &mut mon.workspaces {
3004 for win in ws.windows() {
3005 if win.0.id == id {
3006 return;
3007 }
3008 }
3009 }
3010 }
3011 }
3012 MonitorSet::NoOutputs { workspaces, .. } => {
3013 for ws in workspaces {
3014 for win in ws.windows() {
3015 if win.0.id == id {
3016 return;
3017 }
3018 }
3019 }
3020 }
3021 }
3022
3023 let win = TestWindow::new(id, bbox, min_max_size.0, min_max_size.1);
3024 layout.add_window(win, None, false);
3025 }
3026 Op::AddWindowRightOf {
3027 id,
3028 right_of_id,
3029 bbox,
3030 min_max_size,
3031 } => {
3032 let mut found_right_of = false;
3033
3034 match &mut layout.monitor_set {
3035 MonitorSet::Normal { monitors, .. } => {
3036 for mon in monitors {
3037 for ws in &mut mon.workspaces {
3038 for win in ws.windows() {
3039 if win.0.id == id {
3040 return;
3041 }
3042
3043 if win.0.id == right_of_id {
3044 found_right_of = true;
3045 }
3046 }
3047 }
3048 }
3049 }
3050 MonitorSet::NoOutputs { workspaces, .. } => {
3051 for ws in workspaces {
3052 for win in ws.windows() {
3053 if win.0.id == id {
3054 return;
3055 }
3056
3057 if win.0.id == right_of_id {
3058 found_right_of = true;
3059 }
3060 }
3061 }
3062 }
3063 }
3064
3065 if !found_right_of {
3066 return;
3067 }
3068
3069 let win = TestWindow::new(id, bbox, min_max_size.0, min_max_size.1);
3070 layout.add_window_right_of(&right_of_id, win, None, false);
3071 }
3072 Op::AddWindowToNamedWorkspace {
3073 id,
3074 ws_name,
3075 bbox,
3076 min_max_size,
3077 } => {
3078 let ws_name = format!("ws{ws_name}");
3079 let mut found_workspace = false;
3080
3081 match &mut layout.monitor_set {
3082 MonitorSet::Normal { monitors, .. } => {
3083 for mon in monitors {
3084 for ws in &mut mon.workspaces {
3085 for win in ws.windows() {
3086 if win.0.id == id {
3087 return;
3088 }
3089 }
3090
3091 if ws
3092 .name
3093 .as_ref()
3094 .map_or(false, |name| name.eq_ignore_ascii_case(&ws_name))
3095 {
3096 found_workspace = true;
3097 }
3098 }
3099 }
3100 }
3101 MonitorSet::NoOutputs { workspaces, .. } => {
3102 for ws in workspaces {
3103 for win in ws.windows() {
3104 if win.0.id == id {
3105 return;
3106 }
3107 }
3108
3109 if ws
3110 .name
3111 .as_ref()
3112 .map_or(false, |name| name.eq_ignore_ascii_case(&ws_name))
3113 {
3114 found_workspace = true;
3115 }
3116 }
3117 }
3118 }
3119
3120 if !found_workspace {
3121 return;
3122 }
3123
3124 let win = TestWindow::new(id, bbox, min_max_size.0, min_max_size.1);
3125 layout.add_window_to_named_workspace(&ws_name, win, None, false);
3126 }
3127 Op::CloseWindow(id) => {
3128 layout.remove_window(&id);
3129 }
3130 Op::FullscreenWindow(id) => {
3131 layout.toggle_fullscreen(&id);
3132 }
3133 Op::SetFullscreenWindow {
3134 window,
3135 is_fullscreen,
3136 } => {
3137 layout.set_fullscreen(&window, is_fullscreen);
3138 }
3139 Op::FocusColumnLeft => layout.focus_left(),
3140 Op::FocusColumnRight => layout.focus_right(),
3141 Op::FocusColumnFirst => layout.focus_column_first(),
3142 Op::FocusColumnLast => layout.focus_column_last(),
3143 Op::FocusColumnRightOrFirst => layout.focus_column_right_or_first(),
3144 Op::FocusColumnLeftOrLast => layout.focus_column_left_or_last(),
3145 Op::FocusWindowOrMonitorUp(id) => {
3146 let name = format!("output{id}");
3147 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3148 return;
3149 };
3150
3151 layout.focus_window_up_or_output(&output);
3152 }
3153 Op::FocusWindowOrMonitorDown(id) => {
3154 let name = format!("output{id}");
3155 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3156 return;
3157 };
3158
3159 layout.focus_window_down_or_output(&output);
3160 }
3161 Op::FocusColumnOrMonitorLeft(id) => {
3162 let name = format!("output{id}");
3163 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3164 return;
3165 };
3166
3167 layout.focus_column_left_or_output(&output);
3168 }
3169 Op::FocusColumnOrMonitorRight(id) => {
3170 let name = format!("output{id}");
3171 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3172 return;
3173 };
3174
3175 layout.focus_column_right_or_output(&output);
3176 }
3177 Op::FocusWindowDown => layout.focus_down(),
3178 Op::FocusWindowUp => layout.focus_up(),
3179 Op::FocusWindowDownOrColumnLeft => layout.focus_down_or_left(),
3180 Op::FocusWindowDownOrColumnRight => layout.focus_down_or_right(),
3181 Op::FocusWindowUpOrColumnLeft => layout.focus_up_or_left(),
3182 Op::FocusWindowUpOrColumnRight => layout.focus_up_or_right(),
3183 Op::FocusWindowOrWorkspaceDown => layout.focus_window_or_workspace_down(),
3184 Op::FocusWindowOrWorkspaceUp => layout.focus_window_or_workspace_up(),
3185 Op::MoveColumnLeft => layout.move_left(),
3186 Op::MoveColumnRight => layout.move_right(),
3187 Op::MoveColumnToFirst => layout.move_column_to_first(),
3188 Op::MoveColumnToLast => layout.move_column_to_last(),
3189 Op::MoveColumnLeftOrToMonitorLeft(id) => {
3190 let name = format!("output{id}");
3191 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3192 return;
3193 };
3194
3195 layout.move_column_left_or_to_output(&output);
3196 }
3197 Op::MoveColumnRightOrToMonitorRight(id) => {
3198 let name = format!("output{id}");
3199 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3200 return;
3201 };
3202
3203 layout.move_column_right_or_to_output(&output);
3204 }
3205 Op::MoveWindowDown => layout.move_down(),
3206 Op::MoveWindowUp => layout.move_up(),
3207 Op::MoveWindowDownOrToWorkspaceDown => layout.move_down_or_to_workspace_down(),
3208 Op::MoveWindowUpOrToWorkspaceUp => layout.move_up_or_to_workspace_up(),
3209 Op::ConsumeOrExpelWindowLeft => layout.consume_or_expel_window_left(),
3210 Op::ConsumeOrExpelWindowRight => layout.consume_or_expel_window_right(),
3211 Op::ConsumeWindowIntoColumn => layout.consume_into_column(),
3212 Op::ExpelWindowFromColumn => layout.expel_from_column(),
3213 Op::CenterColumn => layout.center_column(),
3214 Op::FocusWorkspaceDown => layout.switch_workspace_down(),
3215 Op::FocusWorkspaceUp => layout.switch_workspace_up(),
3216 Op::FocusWorkspace(idx) => layout.switch_workspace(idx),
3217 Op::FocusWorkspaceAutoBackAndForth(idx) => {
3218 layout.switch_workspace_auto_back_and_forth(idx)
3219 }
3220 Op::FocusWorkspacePrevious => layout.switch_workspace_previous(),
3221 Op::MoveWindowToWorkspaceDown => layout.move_to_workspace_down(),
3222 Op::MoveWindowToWorkspaceUp => layout.move_to_workspace_up(),
3223 Op::MoveWindowToWorkspace(idx) => layout.move_to_workspace(idx),
3224 Op::MoveColumnToWorkspaceDown => layout.move_column_to_workspace_down(),
3225 Op::MoveColumnToWorkspaceUp => layout.move_column_to_workspace_up(),
3226 Op::MoveColumnToWorkspace(idx) => layout.move_column_to_workspace(idx),
3227 Op::MoveWindowToOutput(id) => {
3228 let name = format!("output{id}");
3229 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3230 return;
3231 };
3232
3233 layout.move_to_output(&output);
3234 }
3235 Op::MoveColumnToOutput(id) => {
3236 let name = format!("output{id}");
3237 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3238 return;
3239 };
3240
3241 layout.move_column_to_output(&output);
3242 }
3243 Op::MoveWorkspaceDown => layout.move_workspace_down(),
3244 Op::MoveWorkspaceUp => layout.move_workspace_up(),
3245 Op::SwitchPresetColumnWidth => layout.toggle_width(),
3246 Op::MaximizeColumn => layout.toggle_full_width(),
3247 Op::SetColumnWidth(change) => layout.set_column_width(change),
3248 Op::SetWindowHeight(change) => layout.set_window_height(change),
3249 Op::ResetWindowHeight => layout.reset_window_height(),
3250 Op::Communicate(id) => {
3251 let mut update = false;
3252 match &mut layout.monitor_set {
3253 MonitorSet::Normal { monitors, .. } => {
3254 'outer: for mon in monitors {
3255 for ws in &mut mon.workspaces {
3256 for win in ws.windows() {
3257 if win.0.id == id {
3258 if win.communicate() {
3259 update = true;
3260 }
3261 break 'outer;
3262 }
3263 }
3264 }
3265 }
3266 }
3267 MonitorSet::NoOutputs { workspaces, .. } => {
3268 'outer: for ws in workspaces {
3269 for win in ws.windows() {
3270 if win.0.id == id {
3271 if win.communicate() {
3272 update = true;
3273 }
3274 break 'outer;
3275 }
3276 }
3277 }
3278 }
3279 }
3280
3281 if update {
3282 // FIXME: serial.
3283 layout.update_window(&id, None);
3284 }
3285 }
3286 Op::MoveWorkspaceToOutput(id) => {
3287 let name = format!("output{id}");
3288 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3289 return;
3290 };
3291
3292 layout.move_workspace_to_output(&output);
3293 }
3294 Op::ViewOffsetGestureBegin {
3295 output_idx: id,
3296 is_touchpad: normalize,
3297 } => {
3298 let name = format!("output{id}");
3299 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3300 return;
3301 };
3302
3303 layout.view_offset_gesture_begin(&output, normalize);
3304 }
3305 Op::ViewOffsetGestureUpdate {
3306 delta,
3307 timestamp,
3308 is_touchpad,
3309 } => {
3310 layout.view_offset_gesture_update(delta, timestamp, is_touchpad);
3311 }
3312 Op::ViewOffsetGestureEnd { is_touchpad } => {
3313 // We don't handle cancels in this gesture.
3314 layout.view_offset_gesture_end(false, is_touchpad);
3315 }
3316 Op::WorkspaceSwitchGestureBegin {
3317 output_idx: id,
3318 is_touchpad,
3319 } => {
3320 let name = format!("output{id}");
3321 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
3322 return;
3323 };
3324
3325 layout.workspace_switch_gesture_begin(&output, is_touchpad);
3326 }
3327 Op::WorkspaceSwitchGestureUpdate {
3328 delta,
3329 timestamp,
3330 is_touchpad,
3331 } => {
3332 layout.workspace_switch_gesture_update(delta, timestamp, is_touchpad);
3333 }
3334 Op::WorkspaceSwitchGestureEnd {
3335 cancelled,
3336 is_touchpad,
3337 } => {
3338 layout.workspace_switch_gesture_end(cancelled, is_touchpad);
3339 }
3340 Op::InteractiveResizeBegin { window, edges } => {
3341 layout.interactive_resize_begin(window, edges);
3342 }
3343 Op::InteractiveResizeUpdate { window, dx, dy } => {
3344 layout.interactive_resize_update(&window, Point::from((dx, dy)));
3345 }
3346 Op::InteractiveResizeEnd { window } => {
3347 layout.interactive_resize_end(&window);
3348 }
3349 }
3350 }
3351 }
3352
3353 #[track_caller]
3354 fn check_ops(ops: &[Op]) {
3355 let mut layout = Layout::default();
3356 for op in ops {
3357 op.apply(&mut layout);
3358 layout.verify_invariants();
3359 }
3360 }
3361
3362 #[track_caller]
3363 fn check_ops_with_options(options: Options, ops: &[Op]) {
3364 let mut layout = Layout::with_options(options);
3365
3366 for op in ops {
3367 op.apply(&mut layout);
3368 layout.verify_invariants();
3369 }
3370 }
3371
3372 #[test]
3373 fn operations_dont_panic() {
3374 let every_op = [
3375 Op::AddOutput(0),
3376 Op::AddOutput(1),
3377 Op::AddOutput(2),
3378 Op::RemoveOutput(0),
3379 Op::RemoveOutput(1),
3380 Op::RemoveOutput(2),
3381 Op::FocusOutput(0),
3382 Op::FocusOutput(1),
3383 Op::FocusOutput(2),
3384 Op::AddNamedWorkspace {
3385 ws_name: 1,
3386 output_name: Some(1),
3387 },
3388 Op::UnnameWorkspace { ws_name: 1 },
3389 Op::AddWindow {
3390 id: 0,
3391 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3392 min_max_size: Default::default(),
3393 },
3394 Op::AddWindow {
3395 id: 1,
3396 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3397 min_max_size: Default::default(),
3398 },
3399 Op::AddWindowRightOf {
3400 id: 2,
3401 right_of_id: 1,
3402 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3403 min_max_size: Default::default(),
3404 },
3405 Op::AddWindowToNamedWorkspace {
3406 id: 3,
3407 ws_name: 1,
3408 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3409 min_max_size: Default::default(),
3410 },
3411 Op::CloseWindow(0),
3412 Op::CloseWindow(1),
3413 Op::CloseWindow(2),
3414 Op::FullscreenWindow(1),
3415 Op::FullscreenWindow(2),
3416 Op::FullscreenWindow(3),
3417 Op::FocusColumnLeft,
3418 Op::FocusColumnRight,
3419 Op::FocusColumnRightOrFirst,
3420 Op::FocusColumnLeftOrLast,
3421 Op::FocusWindowOrMonitorUp(0),
3422 Op::FocusWindowOrMonitorDown(1),
3423 Op::FocusColumnOrMonitorLeft(0),
3424 Op::FocusColumnOrMonitorRight(1),
3425 Op::FocusWindowUp,
3426 Op::FocusWindowUpOrColumnLeft,
3427 Op::FocusWindowUpOrColumnRight,
3428 Op::FocusWindowOrWorkspaceUp,
3429 Op::FocusWindowDown,
3430 Op::FocusWindowDownOrColumnLeft,
3431 Op::FocusWindowDownOrColumnRight,
3432 Op::FocusWindowOrWorkspaceDown,
3433 Op::MoveColumnLeft,
3434 Op::MoveColumnRight,
3435 Op::MoveColumnLeftOrToMonitorLeft(0),
3436 Op::MoveColumnRightOrToMonitorRight(1),
3437 Op::ConsumeWindowIntoColumn,
3438 Op::ExpelWindowFromColumn,
3439 Op::CenterColumn,
3440 Op::FocusWorkspaceDown,
3441 Op::FocusWorkspaceUp,
3442 Op::FocusWorkspace(1),
3443 Op::FocusWorkspace(2),
3444 Op::MoveWindowToWorkspaceDown,
3445 Op::MoveWindowToWorkspaceUp,
3446 Op::MoveWindowToWorkspace(1),
3447 Op::MoveWindowToWorkspace(2),
3448 Op::MoveColumnToWorkspaceDown,
3449 Op::MoveColumnToWorkspaceUp,
3450 Op::MoveColumnToWorkspace(1),
3451 Op::MoveColumnToWorkspace(2),
3452 Op::MoveWindowDown,
3453 Op::MoveWindowDownOrToWorkspaceDown,
3454 Op::MoveWindowUp,
3455 Op::MoveWindowUpOrToWorkspaceUp,
3456 Op::ConsumeOrExpelWindowLeft,
3457 Op::ConsumeOrExpelWindowRight,
3458 Op::MoveWorkspaceToOutput(1),
3459 ];
3460
3461 for third in every_op {
3462 for second in every_op {
3463 for first in every_op {
3464 // eprintln!("{first:?}, {second:?}, {third:?}");
3465
3466 let mut layout = Layout::default();
3467 first.apply(&mut layout);
3468 layout.verify_invariants();
3469 second.apply(&mut layout);
3470 layout.verify_invariants();
3471 third.apply(&mut layout);
3472 layout.verify_invariants();
3473 }
3474 }
3475 }
3476 }
3477
3478 #[test]
3479 fn operations_from_starting_state_dont_panic() {
3480 if std::env::var_os("RUN_SLOW_TESTS").is_none() {
3481 eprintln!("ignoring slow test");
3482 return;
3483 }
3484
3485 // Running every op from an empty state doesn't get us to all the interesting states. So,
3486 // also run it from a manually-created starting state with more things going on to exercise
3487 // more code paths.
3488 let setup_ops = [
3489 Op::AddOutput(1),
3490 Op::AddWindow {
3491 id: 1,
3492 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3493 min_max_size: Default::default(),
3494 },
3495 Op::MoveWindowToWorkspaceDown,
3496 Op::AddWindow {
3497 id: 2,
3498 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3499 min_max_size: Default::default(),
3500 },
3501 Op::AddWindow {
3502 id: 3,
3503 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3504 min_max_size: Default::default(),
3505 },
3506 Op::FocusColumnLeft,
3507 Op::ConsumeWindowIntoColumn,
3508 Op::AddWindow {
3509 id: 4,
3510 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3511 min_max_size: Default::default(),
3512 },
3513 Op::AddOutput(2),
3514 Op::AddWindow {
3515 id: 5,
3516 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3517 min_max_size: Default::default(),
3518 },
3519 Op::MoveWindowToOutput(2),
3520 Op::FocusOutput(1),
3521 Op::Communicate(1),
3522 Op::Communicate(2),
3523 Op::Communicate(3),
3524 Op::Communicate(4),
3525 Op::Communicate(5),
3526 ];
3527
3528 let every_op = [
3529 Op::AddOutput(0),
3530 Op::AddOutput(1),
3531 Op::AddOutput(2),
3532 Op::RemoveOutput(0),
3533 Op::RemoveOutput(1),
3534 Op::RemoveOutput(2),
3535 Op::FocusOutput(0),
3536 Op::FocusOutput(1),
3537 Op::FocusOutput(2),
3538 Op::AddNamedWorkspace {
3539 ws_name: 1,
3540 output_name: Some(1),
3541 },
3542 Op::UnnameWorkspace { ws_name: 1 },
3543 Op::AddWindow {
3544 id: 0,
3545 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3546 min_max_size: Default::default(),
3547 },
3548 Op::AddWindow {
3549 id: 1,
3550 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3551 min_max_size: Default::default(),
3552 },
3553 Op::AddWindow {
3554 id: 2,
3555 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3556 min_max_size: Default::default(),
3557 },
3558 Op::AddWindowRightOf {
3559 id: 6,
3560 right_of_id: 0,
3561 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3562 min_max_size: Default::default(),
3563 },
3564 Op::AddWindowRightOf {
3565 id: 7,
3566 right_of_id: 1,
3567 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3568 min_max_size: Default::default(),
3569 },
3570 Op::AddWindowToNamedWorkspace {
3571 id: 5,
3572 ws_name: 1,
3573 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3574 min_max_size: Default::default(),
3575 },
3576 Op::CloseWindow(0),
3577 Op::CloseWindow(1),
3578 Op::CloseWindow(2),
3579 Op::FullscreenWindow(1),
3580 Op::FullscreenWindow(2),
3581 Op::FullscreenWindow(3),
3582 Op::SetFullscreenWindow {
3583 window: 1,
3584 is_fullscreen: false,
3585 },
3586 Op::SetFullscreenWindow {
3587 window: 1,
3588 is_fullscreen: true,
3589 },
3590 Op::SetFullscreenWindow {
3591 window: 2,
3592 is_fullscreen: false,
3593 },
3594 Op::SetFullscreenWindow {
3595 window: 2,
3596 is_fullscreen: true,
3597 },
3598 Op::FocusColumnLeft,
3599 Op::FocusColumnRight,
3600 Op::FocusColumnRightOrFirst,
3601 Op::FocusColumnLeftOrLast,
3602 Op::FocusWindowOrMonitorUp(0),
3603 Op::FocusWindowOrMonitorDown(1),
3604 Op::FocusColumnOrMonitorLeft(0),
3605 Op::FocusColumnOrMonitorRight(1),
3606 Op::FocusWindowUp,
3607 Op::FocusWindowUpOrColumnLeft,
3608 Op::FocusWindowUpOrColumnRight,
3609 Op::FocusWindowOrWorkspaceUp,
3610 Op::FocusWindowDown,
3611 Op::FocusWindowDownOrColumnLeft,
3612 Op::FocusWindowDownOrColumnRight,
3613 Op::FocusWindowOrWorkspaceDown,
3614 Op::MoveColumnLeft,
3615 Op::MoveColumnRight,
3616 Op::MoveColumnLeftOrToMonitorLeft(0),
3617 Op::MoveColumnRightOrToMonitorRight(1),
3618 Op::ConsumeWindowIntoColumn,
3619 Op::ExpelWindowFromColumn,
3620 Op::CenterColumn,
3621 Op::FocusWorkspaceDown,
3622 Op::FocusWorkspaceUp,
3623 Op::FocusWorkspace(1),
3624 Op::FocusWorkspace(2),
3625 Op::FocusWorkspace(3),
3626 Op::MoveWindowToWorkspaceDown,
3627 Op::MoveWindowToWorkspaceUp,
3628 Op::MoveWindowToWorkspace(1),
3629 Op::MoveWindowToWorkspace(2),
3630 Op::MoveWindowToWorkspace(3),
3631 Op::MoveColumnToWorkspaceDown,
3632 Op::MoveColumnToWorkspaceUp,
3633 Op::MoveColumnToWorkspace(1),
3634 Op::MoveColumnToWorkspace(2),
3635 Op::MoveColumnToWorkspace(3),
3636 Op::MoveWindowDown,
3637 Op::MoveWindowDownOrToWorkspaceDown,
3638 Op::MoveWindowUp,
3639 Op::MoveWindowUpOrToWorkspaceUp,
3640 Op::ConsumeOrExpelWindowLeft,
3641 Op::ConsumeOrExpelWindowRight,
3642 ];
3643
3644 for third in every_op {
3645 for second in every_op {
3646 for first in every_op {
3647 // eprintln!("{first:?}, {second:?}, {third:?}");
3648
3649 let mut layout = Layout::default();
3650 for op in setup_ops {
3651 op.apply(&mut layout);
3652 }
3653
3654 first.apply(&mut layout);
3655 layout.verify_invariants();
3656 second.apply(&mut layout);
3657 layout.verify_invariants();
3658 third.apply(&mut layout);
3659 layout.verify_invariants();
3660 }
3661 }
3662 }
3663 }
3664
3665 #[test]
3666 fn primary_active_workspace_idx_not_updated_on_output_add() {
3667 let ops = [
3668 Op::AddOutput(1),
3669 Op::AddOutput(2),
3670 Op::FocusOutput(1),
3671 Op::AddWindow {
3672 id: 0,
3673 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3674 min_max_size: Default::default(),
3675 },
3676 Op::FocusOutput(2),
3677 Op::AddWindow {
3678 id: 1,
3679 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3680 min_max_size: Default::default(),
3681 },
3682 Op::RemoveOutput(2),
3683 Op::FocusWorkspace(3),
3684 Op::AddOutput(2),
3685 ];
3686
3687 check_ops(&ops);
3688 }
3689
3690 #[test]
3691 fn window_closed_on_previous_workspace() {
3692 let ops = [
3693 Op::AddOutput(1),
3694 Op::AddWindow {
3695 id: 0,
3696 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3697 min_max_size: Default::default(),
3698 },
3699 Op::FocusWorkspaceDown,
3700 Op::CloseWindow(0),
3701 ];
3702
3703 check_ops(&ops);
3704 }
3705
3706 #[test]
3707 fn removing_output_must_keep_empty_focus_on_primary() {
3708 let ops = [
3709 Op::AddOutput(1),
3710 Op::AddWindow {
3711 id: 0,
3712 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3713 min_max_size: Default::default(),
3714 },
3715 Op::AddOutput(2),
3716 Op::RemoveOutput(1),
3717 ];
3718
3719 let mut layout = Layout::default();
3720 for op in ops {
3721 op.apply(&mut layout);
3722 }
3723
3724 let MonitorSet::Normal { monitors, .. } = layout.monitor_set else {
3725 unreachable!()
3726 };
3727
3728 // The workspace from the removed output was inserted at position 0, so the active workspace
3729 // must change to 1 to keep the focus on the empty workspace.
3730 assert_eq!(monitors[0].active_workspace_idx, 1);
3731 }
3732
3733 #[test]
3734 fn move_to_workspace_by_idx_does_not_leave_empty_workspaces() {
3735 let ops = [
3736 Op::AddOutput(1),
3737 Op::AddWindow {
3738 id: 0,
3739 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3740 min_max_size: Default::default(),
3741 },
3742 Op::MoveWindowToWorkspace(2),
3743 ];
3744
3745 let mut layout = Layout::default();
3746 for op in ops {
3747 op.apply(&mut layout);
3748 }
3749
3750 let MonitorSet::Normal { monitors, .. } = layout.monitor_set else {
3751 unreachable!()
3752 };
3753
3754 assert!(monitors[0].workspaces[0].has_windows());
3755 }
3756
3757 #[test]
3758 fn focus_workspace_by_idx_does_not_leave_empty_workspaces() {
3759 let ops = [
3760 Op::AddOutput(1),
3761 Op::AddWindow {
3762 id: 0,
3763 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3764 min_max_size: Default::default(),
3765 },
3766 Op::FocusWorkspaceDown,
3767 Op::AddWindow {
3768 id: 1,
3769 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3770 min_max_size: Default::default(),
3771 },
3772 Op::FocusWorkspaceUp,
3773 Op::CloseWindow(0),
3774 Op::FocusWorkspace(3),
3775 ];
3776
3777 let mut layout = Layout::default();
3778 for op in ops {
3779 op.apply(&mut layout);
3780 }
3781
3782 let MonitorSet::Normal { monitors, .. } = layout.monitor_set else {
3783 unreachable!()
3784 };
3785
3786 assert!(monitors[0].workspaces[0].has_windows());
3787 }
3788
3789 #[test]
3790 fn empty_workspaces_dont_move_back_to_original_output() {
3791 let ops = [
3792 Op::AddOutput(1),
3793 Op::AddWindow {
3794 id: 1,
3795 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3796 min_max_size: Default::default(),
3797 },
3798 Op::FocusWorkspaceDown,
3799 Op::AddWindow {
3800 id: 2,
3801 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3802 min_max_size: Default::default(),
3803 },
3804 Op::AddOutput(2),
3805 Op::RemoveOutput(1),
3806 Op::FocusWorkspace(1),
3807 Op::CloseWindow(1),
3808 Op::AddOutput(1),
3809 ];
3810
3811 check_ops(&ops);
3812 }
3813
3814 #[test]
3815 fn large_negative_height_change() {
3816 let ops = [
3817 Op::AddOutput(1),
3818 Op::AddWindow {
3819 id: 1,
3820 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3821 min_max_size: Default::default(),
3822 },
3823 Op::SetWindowHeight(SizeChange::AdjustProportion(-1e129)),
3824 ];
3825
3826 let mut options = Options::default();
3827 options.border.off = false;
3828 options.border.width = FloatOrInt(1.);
3829
3830 check_ops_with_options(options, &ops);
3831 }
3832
3833 #[test]
3834 fn large_max_size() {
3835 let ops = [
3836 Op::AddOutput(1),
3837 Op::AddWindow {
3838 id: 1,
3839 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3840 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3841 },
3842 ];
3843
3844 let mut options = Options::default();
3845 options.border.off = false;
3846 options.border.width = FloatOrInt(1.);
3847
3848 check_ops_with_options(options, &ops);
3849 }
3850
3851 #[test]
3852 fn workspace_cleanup_during_switch() {
3853 let ops = [
3854 Op::AddOutput(1),
3855 Op::AddWindow {
3856 id: 1,
3857 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3858 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3859 },
3860 Op::FocusWorkspaceDown,
3861 Op::CloseWindow(1),
3862 ];
3863
3864 check_ops(&ops);
3865 }
3866
3867 #[test]
3868 fn workspace_transfer_during_switch() {
3869 let ops = [
3870 Op::AddOutput(1),
3871 Op::AddWindow {
3872 id: 1,
3873 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3874 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3875 },
3876 Op::AddOutput(2),
3877 Op::FocusOutput(2),
3878 Op::AddWindow {
3879 id: 2,
3880 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3881 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3882 },
3883 Op::RemoveOutput(1),
3884 Op::FocusWorkspaceDown,
3885 Op::FocusWorkspaceDown,
3886 Op::AddOutput(1),
3887 ];
3888
3889 check_ops(&ops);
3890 }
3891
3892 #[test]
3893 fn workspace_transfer_during_switch_from_last() {
3894 let ops = [
3895 Op::AddOutput(1),
3896 Op::AddWindow {
3897 id: 1,
3898 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3899 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3900 },
3901 Op::AddOutput(2),
3902 Op::RemoveOutput(1),
3903 Op::FocusWorkspaceUp,
3904 Op::AddOutput(1),
3905 ];
3906
3907 check_ops(&ops);
3908 }
3909
3910 #[test]
3911 fn workspace_transfer_during_switch_gets_cleaned_up() {
3912 let ops = [
3913 Op::AddOutput(1),
3914 Op::AddWindow {
3915 id: 1,
3916 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3917 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3918 },
3919 Op::RemoveOutput(1),
3920 Op::AddOutput(2),
3921 Op::MoveColumnToWorkspaceDown,
3922 Op::MoveColumnToWorkspaceDown,
3923 Op::AddOutput(1),
3924 ];
3925
3926 check_ops(&ops);
3927 }
3928
3929 #[test]
3930 fn move_workspace_to_output() {
3931 let ops = [
3932 Op::AddOutput(1),
3933 Op::AddOutput(2),
3934 Op::FocusOutput(1),
3935 Op::AddWindow {
3936 id: 0,
3937 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3938 min_max_size: Default::default(),
3939 },
3940 Op::MoveWorkspaceToOutput(2),
3941 ];
3942
3943 let mut layout = Layout::default();
3944 for op in ops {
3945 op.apply(&mut layout);
3946 }
3947
3948 let MonitorSet::Normal {
3949 monitors,
3950 active_monitor_idx,
3951 ..
3952 } = layout.monitor_set
3953 else {
3954 unreachable!()
3955 };
3956
3957 assert_eq!(active_monitor_idx, 1);
3958 assert_eq!(monitors[0].workspaces.len(), 1);
3959 assert!(!monitors[0].workspaces[0].has_windows());
3960 assert_eq!(monitors[1].active_workspace_idx, 0);
3961 assert_eq!(monitors[1].workspaces.len(), 2);
3962 assert!(monitors[1].workspaces[0].has_windows());
3963 }
3964
3965 #[test]
3966 fn fullscreen() {
3967 let ops = [
3968 Op::AddOutput(1),
3969 Op::AddWindow {
3970 id: 1,
3971 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3972 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3973 },
3974 Op::FullscreenWindow(1),
3975 ];
3976
3977 check_ops(&ops);
3978 }
3979
3980 #[test]
3981 fn unfullscreen_window_in_column() {
3982 let ops = [
3983 Op::AddOutput(1),
3984 Op::AddWindow {
3985 id: 1,
3986 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3987 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3988 },
3989 Op::AddWindow {
3990 id: 2,
3991 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3992 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
3993 },
3994 Op::ConsumeOrExpelWindowLeft,
3995 Op::SetFullscreenWindow {
3996 window: 2,
3997 is_fullscreen: false,
3998 },
3999 ];
4000
4001 check_ops(&ops);
4002 }
4003
4004 #[test]
4005 fn open_right_of_on_different_workspace() {
4006 let ops = [
4007 Op::AddOutput(1),
4008 Op::AddWindow {
4009 id: 1,
4010 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4011 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
4012 },
4013 Op::FocusWorkspaceDown,
4014 Op::AddWindow {
4015 id: 2,
4016 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4017 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
4018 },
4019 Op::AddWindowRightOf {
4020 id: 3,
4021 right_of_id: 1,
4022 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4023 min_max_size: (Size::from((0, 0)), Size::from((i32::MAX, i32::MAX))),
4024 },
4025 ];
4026
4027 let mut layout = Layout::default();
4028 for op in ops {
4029 op.apply(&mut layout);
4030 }
4031
4032 let MonitorSet::Normal { monitors, .. } = layout.monitor_set else {
4033 unreachable!()
4034 };
4035
4036 let mon = monitors.into_iter().next().unwrap();
4037 assert_eq!(
4038 mon.active_workspace_idx, 1,
4039 "the second workspace must remain active"
4040 );
4041 assert_eq!(
4042 mon.workspaces[0].active_column_idx, 1,
4043 "the new window must become active"
4044 );
4045 }
4046
4047 #[test]
4048 fn unfullscreen_view_offset_not_reset_on_removal() {
4049 let ops = [
4050 Op::AddOutput(1),
4051 Op::AddWindow {
4052 id: 0,
4053 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4054 min_max_size: Default::default(),
4055 },
4056 Op::FullscreenWindow(0),
4057 Op::AddWindow {
4058 id: 1,
4059 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4060 min_max_size: Default::default(),
4061 },
4062 Op::ConsumeOrExpelWindowRight,
4063 ];
4064
4065 check_ops(&ops);
4066 }
4067
4068 #[test]
4069 fn unfullscreen_view_offset_not_reset_on_consume() {
4070 let ops = [
4071 Op::AddOutput(1),
4072 Op::AddWindow {
4073 id: 0,
4074 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4075 min_max_size: Default::default(),
4076 },
4077 Op::FullscreenWindow(0),
4078 Op::AddWindow {
4079 id: 1,
4080 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4081 min_max_size: Default::default(),
4082 },
4083 Op::ConsumeWindowIntoColumn,
4084 ];
4085
4086 check_ops(&ops);
4087 }
4088
4089 #[test]
4090 fn unfullscreen_view_offset_not_reset_on_quick_double_toggle() {
4091 let ops = [
4092 Op::AddOutput(1),
4093 Op::AddWindow {
4094 id: 0,
4095 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4096 min_max_size: Default::default(),
4097 },
4098 Op::FullscreenWindow(0),
4099 Op::FullscreenWindow(0),
4100 ];
4101
4102 check_ops(&ops);
4103 }
4104
4105 #[test]
4106 fn unfullscreen_view_offset_set_on_fullscreening_inactive_tile_in_column() {
4107 let ops = [
4108 Op::AddOutput(1),
4109 Op::AddWindow {
4110 id: 0,
4111 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4112 min_max_size: Default::default(),
4113 },
4114 Op::AddWindow {
4115 id: 1,
4116 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
4117 min_max_size: Default::default(),
4118 },
4119 Op::ConsumeOrExpelWindowLeft,
4120 Op::FullscreenWindow(0),
4121 ];
4122
4123 check_ops(&ops);
4124 }
4125
4126 #[test]
4127 fn unfullscreen_view_offset_not_reset_on_gesture() {
4128 let ops = [
4129 Op::AddOutput(1),
4130 Op::AddWindow {
4131 id: 0,
4132 bbox: Rectangle::from_loc_and_size((0, 0), (200, 200)),
4133 min_max_size: Default::default(),
4134 },
4135 Op::AddWindow {
4136 id: 1,
4137 bbox: Rectangle::from_loc_and_size((0, 0), (1280, 200)),
4138 min_max_size: Default::default(),
4139 },
4140 Op::FullscreenWindow(1),
4141 Op::ViewOffsetGestureBegin {
4142 output_idx: 1,
4143 is_touchpad: true,
4144 },
4145 Op::ViewOffsetGestureEnd {
4146 is_touchpad: Some(true),
4147 },
4148 ];
4149
4150 check_ops(&ops);
4151 }
4152
4153 #[test]
4154 fn removing_all_outputs_preserves_empty_named_workspaces() {
4155 let ops = [
4156 Op::AddOutput(1),
4157 Op::AddNamedWorkspace {
4158 ws_name: 1,
4159 output_name: None,
4160 },
4161 Op::AddNamedWorkspace {
4162 ws_name: 2,
4163 output_name: None,
4164 },
4165 Op::RemoveOutput(1),
4166 ];
4167
4168 let mut layout = Layout::default();
4169 for op in ops {
4170 op.apply(&mut layout);
4171 }
4172
4173 let MonitorSet::NoOutputs { workspaces } = layout.monitor_set else {
4174 unreachable!()
4175 };
4176
4177 assert_eq!(workspaces.len(), 2);
4178 }
4179
4180 #[test]
4181 fn config_change_updates_cached_sizes() {
4182 let mut config = Config::default();
4183 config.layout.border.off = false;
4184 config.layout.border.width = FloatOrInt(2.);
4185
4186 let mut layout = Layout::new(&config);
4187
4188 Op::AddWindow {
4189 id: 1,
4190 bbox: Rectangle::from_loc_and_size((0, 0), (1280, 200)),
4191 min_max_size: Default::default(),
4192 }
4193 .apply(&mut layout);
4194
4195 config.layout.border.width = FloatOrInt(4.);
4196 layout.update_config(&config);
4197
4198 layout.verify_invariants();
4199 }
4200
4201 #[test]
4202 fn working_area_starts_at_physical_pixel() {
4203 let struts = Struts {
4204 left: FloatOrInt(0.5),
4205 right: FloatOrInt(1.),
4206 top: FloatOrInt(0.75),
4207 bottom: FloatOrInt(1.),
4208 };
4209
4210 let output = Output::new(
4211 String::from("output"),
4212 PhysicalProperties {
4213 size: Size::from((1280, 720)),
4214 subpixel: Subpixel::Unknown,
4215 make: String::new(),
4216 model: String::new(),
4217 },
4218 );
4219 output.change_current_state(
4220 Some(Mode {
4221 size: Size::from((1280, 720)),
4222 refresh: 60000,
4223 }),
4224 None,
4225 None,
4226 None,
4227 );
4228
4229 let area = compute_working_area(&output, struts);
4230
4231 assert_eq!(round_logical_in_physical(1., area.loc.x), area.loc.x);
4232 assert_eq!(round_logical_in_physical(1., area.loc.y), area.loc.y);
4233 }
4234
4235 #[test]
4236 fn large_fractional_strut() {
4237 let struts = Struts {
4238 left: FloatOrInt(0.),
4239 right: FloatOrInt(0.),
4240 top: FloatOrInt(50000.5),
4241 bottom: FloatOrInt(0.),
4242 };
4243
4244 let output = Output::new(
4245 String::from("output"),
4246 PhysicalProperties {
4247 size: Size::from((1280, 720)),
4248 subpixel: Subpixel::Unknown,
4249 make: String::new(),
4250 model: String::new(),
4251 },
4252 );
4253 output.change_current_state(
4254 Some(Mode {
4255 size: Size::from((1280, 720)),
4256 refresh: 60000,
4257 }),
4258 None,
4259 None,
4260 None,
4261 );
4262
4263 compute_working_area(&output, struts);
4264 }
4265
4266 fn arbitrary_spacing() -> impl Strategy<Value = f64> {
4267 // Give equal weight to:
4268 // - 0: the element is disabled
4269 // - 4: some reasonable value
4270 // - random value, likely unreasonably big
4271 prop_oneof![Just(0.), Just(4.), ((1.)..=65535.)]
4272 }
4273
4274 fn arbitrary_spacing_neg() -> impl Strategy<Value = f64> {
4275 // Give equal weight to:
4276 // - 0: the element is disabled
4277 // - 4: some reasonable value
4278 // - -4: some reasonable negative value
4279 // - random value, likely unreasonably big
4280 prop_oneof![Just(0.), Just(4.), Just(-4.), ((1.)..=65535.)]
4281 }
4282
4283 fn arbitrary_struts() -> impl Strategy<Value = Struts> {
4284 (
4285 arbitrary_spacing_neg(),
4286 arbitrary_spacing_neg(),
4287 arbitrary_spacing_neg(),
4288 arbitrary_spacing_neg(),
4289 )
4290 .prop_map(|(left, right, top, bottom)| Struts {
4291 left: FloatOrInt(left),
4292 right: FloatOrInt(right),
4293 top: FloatOrInt(top),
4294 bottom: FloatOrInt(bottom),
4295 })
4296 }
4297
4298 fn arbitrary_center_focused_column() -> impl Strategy<Value = CenterFocusedColumn> {
4299 prop_oneof![
4300 Just(CenterFocusedColumn::Never),
4301 Just(CenterFocusedColumn::OnOverflow),
4302 Just(CenterFocusedColumn::Always),
4303 ]
4304 }
4305
4306 prop_compose! {
4307 fn arbitrary_focus_ring()(
4308 off in any::<bool>(),
4309 width in arbitrary_spacing(),
4310 ) -> niri_config::FocusRing {
4311 niri_config::FocusRing {
4312 off,
4313 width: FloatOrInt(width),
4314 ..Default::default()
4315 }
4316 }
4317 }
4318
4319 prop_compose! {
4320 fn arbitrary_border()(
4321 off in any::<bool>(),
4322 width in arbitrary_spacing(),
4323 ) -> niri_config::Border {
4324 niri_config::Border {
4325 off,
4326 width: FloatOrInt(width),
4327 ..Default::default()
4328 }
4329 }
4330 }
4331
4332 prop_compose! {
4333 fn arbitrary_options()(
4334 gaps in arbitrary_spacing(),
4335 struts in arbitrary_struts(),
4336 focus_ring in arbitrary_focus_ring(),
4337 border in arbitrary_border(),
4338 center_focused_column in arbitrary_center_focused_column(),
4339 ) -> Options {
4340 Options {
4341 gaps,
4342 struts,
4343 center_focused_column,
4344 focus_ring,
4345 border,
4346 ..Default::default()
4347 }
4348 }
4349 }
4350
4351 proptest! {
4352 #![proptest_config(ProptestConfig {
4353 cases: if std::env::var_os("RUN_SLOW_TESTS").is_none() {
4354 eprintln!("ignoring slow test");
4355 0
4356 } else {
4357 ProptestConfig::default().cases
4358 },
4359 ..ProptestConfig::default()
4360 })]
4361
4362 #[test]
4363 fn random_operations_dont_panic(ops: Vec<Op>, options in arbitrary_options()) {
4364 // eprintln!("{ops:?}");
4365 check_ops_with_options(options, &ops);
4366 }
4367 }
4368}