forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB0411fd8Ivan Molodetskikh3 years ago263 commits

layout.rs3004 lines, 93.3 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::{max, min};
33use std::iter::zip;
34use std::mem;
35use std::rc::Rc;
36use std::time::Duration;
37
38use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
39use smithay::backend::renderer::element::surface::WaylandSurfaceRenderElement;
40use smithay::backend::renderer::element::utils::{
41 CropRenderElement, Relocate, RelocateRenderElement,
42};
43use smithay::backend::renderer::element::{AsRenderElements, Kind};
44use smithay::backend::renderer::gles::GlesRenderer;
45use smithay::backend::renderer::ImportAll;
46use smithay::desktop::space::SpaceElement;
47use smithay::desktop::{layer_map_for_output, Window};
48use smithay::output::Output;
49use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
50use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
51use smithay::render_elements;
52use smithay::utils::{Logical, Point, Rectangle, Scale, Size};
53use smithay::wayland::compositor::with_states;
54use smithay::wayland::shell::xdg::SurfaceCachedState;
55
56use crate::animation::Animation;
57use crate::config::{self, Color, Config, PresetWidth, SizeChange};
58
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct OutputId(String);
61
62render_elements! {
63 #[derive(Debug)]
64 pub WorkspaceRenderElement<R> where R: ImportAll;
65 Wayland = WaylandSurfaceRenderElement<R>,
66 FocusRing = SolidColorRenderElement,
67}
68pub type MonitorRenderElement<R> =
69 RelocateRenderElement<CropRenderElement<WorkspaceRenderElement<R>>>;
70
71pub trait LayoutElement: SpaceElement + PartialEq + Clone {
72 fn request_size(&self, size: Size<i32, Logical>);
73 fn request_fullscreen(&self, size: Size<i32, Logical>);
74 fn min_size(&self) -> Size<i32, Logical>;
75 fn max_size(&self) -> Size<i32, Logical>;
76 fn is_wl_surface(&self, wl_surface: &WlSurface) -> bool;
77}
78
79#[derive(Debug)]
80pub struct Layout<W: LayoutElement> {
81 /// Monitors and workspaes in the layout.
82 monitor_set: MonitorSet<W>,
83 /// Configurable properties of the layout.
84 options: Rc<Options>,
85}
86
87#[derive(Debug)]
88enum MonitorSet<W: LayoutElement> {
89 /// At least one output is connected.
90 Normal {
91 /// Connected monitors.
92 monitors: Vec<Monitor<W>>,
93 /// Index of the primary monitor.
94 primary_idx: usize,
95 /// Index of the active monitor.
96 active_monitor_idx: usize,
97 },
98 /// No outputs are connected, and these are the workspaces.
99 NoOutputs {
100 /// The workspaces.
101 workspaces: Vec<Workspace<W>>,
102 },
103}
104
105#[derive(Debug)]
106pub struct Monitor<W: LayoutElement> {
107 /// Output for this monitor.
108 output: Output,
109 // Must always contain at least one.
110 workspaces: Vec<Workspace<W>>,
111 /// Index of the currently active workspace.
112 active_workspace_idx: usize,
113 /// Animation for workspace switching.
114 workspace_idx_anim: Option<Animation>,
115 /// Configurable properties of the layout.
116 options: Rc<Options>,
117}
118
119#[derive(Debug)]
120pub struct Workspace<W: LayoutElement> {
121 /// The original output of this workspace.
122 ///
123 /// Most of the time this will be the workspace's current output, however, after an output
124 /// disconnection, it may remain pointing to the disconnected output.
125 original_output: OutputId,
126
127 /// Current output of this workspace.
128 output: Option<Output>,
129
130 /// Latest known view size for this workspace.
131 ///
132 /// This should be computed from the current workspace output size, or, if all outputs have
133 /// been disconnected, preserved until a new output is connected.
134 view_size: Size<i32, Logical>,
135
136 /// Latest known working area for this workspace.
137 ///
138 /// This is similar to view size, but takes into account things like layer shell exclusive
139 /// zones.
140 working_area: Rectangle<i32, Logical>,
141
142 /// Columns of windows on this workspace.
143 columns: Vec<Column<W>>,
144
145 /// Index of the currently active column, if any.
146 active_column_idx: usize,
147
148 /// Focus ring buffer and parameters.
149 focus_ring: FocusRing,
150
151 /// Offset of the view computed from the active column.
152 ///
153 /// Any gaps, including left padding from work area left exclusive zone, is handled
154 /// with this view offset (rather than added as a constant elsewhere in the code). This allows
155 /// for natural handling of fullscreen windows, which must ignore work area padding.
156 view_offset: i32,
157
158 /// Animation of the view offset, if one is currently ongoing.
159 view_offset_anim: Option<Animation>,
160
161 /// Whether to activate the previous, rather than the next, column upon column removal.
162 ///
163 /// When a new column is created and removed with no focus changes in-between, it is more
164 /// natural to activate the previously-focused column. This variable tracks that.
165 ///
166 /// Since we only create-and-activate columns immediately to the right of the active column (in
167 /// contrast to tabs in Firefox, for example), we can track this as a bool, rather than an
168 /// index of the previous column to activate.
169 activate_prev_column_on_removal: bool,
170
171 /// Configurable properties of the layout.
172 options: Rc<Options>,
173}
174
175#[derive(Debug)]
176struct FocusRing {
177 buffer: SolidColorBuffer,
178 is_off: bool,
179 width: i32,
180 active_color: Color,
181 inactive_color: Color,
182}
183
184#[derive(Debug, PartialEq)]
185struct Options {
186 /// Padding around windows in logical pixels.
187 gaps: i32,
188 focus_ring: config::FocusRing,
189 /// Column widths that `toggle_width()` switches between.
190 preset_widths: Vec<ColumnWidth>,
191}
192
193impl Default for Options {
194 fn default() -> Self {
195 Self {
196 gaps: 16,
197 focus_ring: Default::default(),
198 preset_widths: vec![
199 ColumnWidth::Proportion(1. / 3.),
200 ColumnWidth::Proportion(0.5),
201 ColumnWidth::Proportion(2. / 3.),
202 ],
203 }
204 }
205}
206
207impl Options {
208 fn from_config(config: &Config) -> Self {
209 let preset_column_widths = &config.preset_column_widths;
210
211 let preset_widths = if preset_column_widths.is_empty() {
212 Options::default().preset_widths
213 } else {
214 preset_column_widths
215 .iter()
216 .copied()
217 .map(ColumnWidth::from)
218 .collect()
219 };
220
221 Self {
222 gaps: config.gaps.into(),
223 focus_ring: config.focus_ring,
224 preset_widths,
225 }
226 }
227}
228
229/// Width of a column.
230#[derive(Debug, Clone, Copy, PartialEq)]
231enum ColumnWidth {
232 /// Proportion of the current view width.
233 Proportion(f64),
234 /// One of the proportion presets.
235 ///
236 /// This is separate from Proportion in order to be able to reliably cycle between preset
237 /// proportions.
238 Preset(usize),
239 /// Fixed width in logical pixels.
240 Fixed(i32),
241}
242
243impl From<PresetWidth> for ColumnWidth {
244 fn from(value: PresetWidth) -> Self {
245 match value {
246 PresetWidth::Proportion(p) => Self::Proportion(p.clamp(0., 10000.)),
247 PresetWidth::Fixed(f) => Self::Fixed(f.clamp(1, 100000)),
248 }
249 }
250}
251
252#[derive(Debug)]
253struct Column<W: LayoutElement> {
254 /// Windows in this column.
255 ///
256 /// Must be non-empty.
257 windows: Vec<W>,
258
259 /// Index of the currently active window.
260 active_window_idx: usize,
261
262 /// Desired width of this column.
263 width: ColumnWidth,
264
265 /// Whether this column contains a single full-screened window.
266 is_fullscreen: bool,
267
268 /// Latest known view size for this column's workspace.
269 view_size: Size<i32, Logical>,
270
271 /// Latest known working area for this column's workspace.
272 working_area: Rectangle<i32, Logical>,
273
274 /// Configurable properties of the layout.
275 options: Rc<Options>,
276}
277
278impl OutputId {
279 pub fn new(output: &Output) -> Self {
280 Self(output.name())
281 }
282}
283
284impl LayoutElement for Window {
285 fn request_size(&self, size: Size<i32, Logical>) {
286 self.toplevel().with_pending_state(|state| {
287 state.size = Some(size);
288 state.states.unset(xdg_toplevel::State::Fullscreen);
289 });
290 }
291
292 fn request_fullscreen(&self, size: Size<i32, Logical>) {
293 self.toplevel().with_pending_state(|state| {
294 state.size = Some(size);
295 state.states.set(xdg_toplevel::State::Fullscreen);
296 });
297 }
298
299 fn min_size(&self) -> Size<i32, Logical> {
300 with_states(self.toplevel().wl_surface(), |state| {
301 let curr = state.cached_state.current::<SurfaceCachedState>();
302 curr.min_size
303 })
304 }
305
306 fn max_size(&self) -> Size<i32, Logical> {
307 with_states(self.toplevel().wl_surface(), |state| {
308 let curr = state.cached_state.current::<SurfaceCachedState>();
309 curr.max_size
310 })
311 }
312
313 fn is_wl_surface(&self, wl_surface: &WlSurface) -> bool {
314 self.toplevel().wl_surface() == wl_surface
315 }
316}
317
318impl FocusRing {
319 fn resize(&mut self, size: Size<i32, Logical>) {
320 let size = size + Size::from((self.width * 2, self.width * 2));
321 self.buffer.resize(size);
322 }
323
324 fn set_active(&mut self, is_active: bool) {
325 self.buffer.set_color(if is_active {
326 self.active_color.into()
327 } else {
328 self.inactive_color.into()
329 });
330 }
331
332 fn render(
333 &self,
334 loc: Point<i32, Logical>,
335 scale: Scale<f64>,
336 ) -> Option<SolidColorRenderElement> {
337 if self.is_off {
338 return None;
339 }
340
341 let offset = Point::from((self.width, self.width));
342 Some(SolidColorRenderElement::from_buffer(
343 &self.buffer,
344 (loc - offset).to_physical_precise_round(scale),
345 scale,
346 1.,
347 Kind::Unspecified,
348 ))
349 }
350}
351
352impl FocusRing {
353 fn new(config: config::FocusRing) -> Self {
354 Self {
355 buffer: SolidColorBuffer::new((0, 0), [0., 0., 0., 0.]),
356 is_off: config.off,
357 width: config.width.into(),
358 active_color: config.active_color,
359 inactive_color: config.inactive_color,
360 }
361 }
362}
363
364impl ColumnWidth {
365 fn resolve(self, options: &Options, view_width: i32) -> i32 {
366 match self {
367 ColumnWidth::Proportion(proportion) => {
368 ((view_width - options.gaps) as f64 * proportion).floor() as i32 - options.gaps
369 }
370 ColumnWidth::Preset(idx) => options.preset_widths[idx].resolve(options, view_width),
371 ColumnWidth::Fixed(width) => width,
372 }
373 }
374}
375
376impl Default for ColumnWidth {
377 fn default() -> Self {
378 Self::Proportion(0.5)
379 }
380}
381
382impl<W: LayoutElement> Layout<W> {
383 pub fn new(config: &Config) -> Self {
384 Self {
385 monitor_set: MonitorSet::NoOutputs { workspaces: vec![] },
386 options: Rc::new(Options::from_config(config)),
387 }
388 }
389
390 pub fn add_output(&mut self, output: Output) {
391 let id = OutputId::new(&output);
392
393 self.monitor_set = match mem::take(&mut self.monitor_set) {
394 MonitorSet::Normal {
395 mut monitors,
396 primary_idx,
397 active_monitor_idx,
398 } => {
399 let primary = &mut monitors[primary_idx];
400
401 let mut workspaces = vec![];
402 for i in (0..primary.workspaces.len()).rev() {
403 if primary.workspaces[i].original_output == id {
404 let ws = primary.workspaces.remove(i);
405 workspaces.push(ws);
406
407 if i <= primary.active_workspace_idx {
408 primary.active_workspace_idx =
409 primary.active_workspace_idx.saturating_sub(1);
410 }
411 }
412 }
413 workspaces.reverse();
414 if workspaces.iter().all(|ws| ws.has_windows()) {
415 // Make sure there's always an empty workspace.
416 workspaces.push(Workspace::new(output.clone(), self.options.clone()));
417 }
418
419 for ws in &mut workspaces {
420 ws.set_output(Some(output.clone()));
421 }
422
423 monitors.push(Monitor::new(output, workspaces, self.options.clone()));
424 MonitorSet::Normal {
425 monitors,
426 primary_idx,
427 active_monitor_idx,
428 }
429 }
430 MonitorSet::NoOutputs { mut workspaces } => {
431 // We know there are no empty workspaces there, so add one.
432 workspaces.push(Workspace::new(output.clone(), self.options.clone()));
433
434 for workspace in &mut workspaces {
435 workspace.set_output(Some(output.clone()));
436 }
437
438 let monitor = Monitor::new(output, workspaces, self.options.clone());
439
440 MonitorSet::Normal {
441 monitors: vec![monitor],
442 primary_idx: 0,
443 active_monitor_idx: 0,
444 }
445 }
446 }
447 }
448
449 pub fn remove_output(&mut self, output: &Output) {
450 self.monitor_set = match mem::take(&mut self.monitor_set) {
451 MonitorSet::Normal {
452 mut monitors,
453 mut primary_idx,
454 mut active_monitor_idx,
455 } => {
456 let idx = monitors
457 .iter()
458 .position(|mon| &mon.output == output)
459 .expect("trying to remove non-existing output");
460 let monitor = monitors.remove(idx);
461 let mut workspaces = monitor.workspaces;
462
463 for ws in &mut workspaces {
464 ws.set_output(None);
465 }
466
467 // Get rid of empty workspaces.
468 workspaces.retain(|ws| ws.has_windows());
469
470 if monitors.is_empty() {
471 // Removed the last monitor.
472 MonitorSet::NoOutputs { workspaces }
473 } else {
474 if primary_idx >= idx {
475 // Update primary_idx to either still point at the same monitor, or at some
476 // other monitor if the primary has been removed.
477 primary_idx = primary_idx.saturating_sub(1);
478 }
479 if active_monitor_idx >= idx {
480 // Update active_monitor_idx to either still point at the same monitor, or
481 // at some other monitor if the active monitor has
482 // been removed.
483 active_monitor_idx = active_monitor_idx.saturating_sub(1);
484 }
485
486 let primary = &mut monitors[primary_idx];
487 for ws in &mut workspaces {
488 ws.set_output(Some(primary.output.clone()));
489 }
490
491 let empty = primary.workspaces.remove(primary.workspaces.len() - 1);
492 primary.workspaces.extend(workspaces);
493 primary.workspaces.push(empty);
494
495 MonitorSet::Normal {
496 monitors,
497 primary_idx,
498 active_monitor_idx,
499 }
500 }
501 }
502 MonitorSet::NoOutputs { .. } => {
503 panic!("tried to remove output when there were already none")
504 }
505 }
506 }
507
508 pub fn add_window_by_idx(
509 &mut self,
510 monitor_idx: usize,
511 workspace_idx: usize,
512 window: W,
513 activate: bool,
514 ) {
515 let MonitorSet::Normal {
516 monitors,
517 active_monitor_idx,
518 ..
519 } = &mut self.monitor_set
520 else {
521 panic!()
522 };
523
524 monitors[monitor_idx].add_window(workspace_idx, window, activate);
525
526 if activate {
527 *active_monitor_idx = monitor_idx;
528 }
529 }
530
531 /// Adds a new window to the layout.
532 ///
533 /// Returns an output that the window was added to, if there were any outputs.
534 pub fn add_window(&mut self, window: W, activate: bool) -> Option<&Output> {
535 match &mut self.monitor_set {
536 MonitorSet::Normal {
537 monitors,
538 active_monitor_idx,
539 ..
540 } => {
541 let mon = &mut monitors[*active_monitor_idx];
542 mon.add_window(mon.active_workspace_idx, window, activate);
543 Some(&mon.output)
544 }
545 MonitorSet::NoOutputs { workspaces } => {
546 let ws = if let Some(ws) = workspaces.get_mut(0) {
547 ws
548 } else {
549 workspaces.push(Workspace::new_no_outputs(self.options.clone()));
550 &mut workspaces[0]
551 };
552 ws.add_window(window, activate);
553 None
554 }
555 }
556 }
557
558 pub fn remove_window(&mut self, window: &W) {
559 match &mut self.monitor_set {
560 MonitorSet::Normal { monitors, .. } => {
561 for mon in monitors {
562 for (idx, ws) in mon.workspaces.iter_mut().enumerate() {
563 if ws.has_window(window) {
564 ws.remove_window(window);
565
566 // Clean up empty workspaces that are not active and not last.
567 if !ws.has_windows()
568 && idx != mon.active_workspace_idx
569 && idx != mon.workspaces.len() - 1
570 {
571 mon.workspaces.remove(idx);
572
573 if idx < mon.active_workspace_idx {
574 mon.active_workspace_idx -= 1;
575 }
576 }
577
578 break;
579 }
580 }
581 }
582 }
583 MonitorSet::NoOutputs { workspaces, .. } => {
584 for (idx, ws) in workspaces.iter_mut().enumerate() {
585 if ws.has_window(window) {
586 ws.remove_window(window);
587
588 // Clean up empty workspaces.
589 if !ws.has_windows() {
590 workspaces.remove(idx);
591 }
592
593 break;
594 }
595 }
596 }
597 }
598 }
599
600 pub fn update_window(&mut self, window: &W) {
601 match &mut self.monitor_set {
602 MonitorSet::Normal { monitors, .. } => {
603 for mon in monitors {
604 for ws in &mut mon.workspaces {
605 if ws.has_window(window) {
606 ws.update_window(window);
607 return;
608 }
609 }
610 }
611 }
612 MonitorSet::NoOutputs { workspaces, .. } => {
613 for ws in workspaces {
614 if ws.has_window(window) {
615 ws.update_window(window);
616 return;
617 }
618 }
619 }
620 }
621 }
622
623 pub fn find_window_and_output(&self, wl_surface: &WlSurface) -> Option<(W, Output)> {
624 if let MonitorSet::Normal { monitors, .. } = &self.monitor_set {
625 for mon in monitors {
626 for ws in &mon.workspaces {
627 if let Some(window) = ws.find_wl_surface(wl_surface) {
628 return Some((window.clone(), mon.output.clone()));
629 }
630 }
631 }
632 }
633
634 None
635 }
636
637 pub fn update_output_size(&mut self, output: &Output) {
638 let MonitorSet::Normal { monitors, .. } = &mut self.monitor_set else {
639 panic!()
640 };
641
642 for mon in monitors {
643 if &mon.output == output {
644 let view_size = output_size(output);
645 let working_area = layer_map_for_output(output).non_exclusive_zone();
646
647 for ws in &mut mon.workspaces {
648 ws.set_view_size(view_size, working_area);
649 }
650
651 break;
652 }
653 }
654 }
655
656 pub fn activate_window(&mut self, window: &W) {
657 let MonitorSet::Normal {
658 monitors,
659 active_monitor_idx,
660 ..
661 } = &mut self.monitor_set
662 else {
663 todo!()
664 };
665
666 for (monitor_idx, mon) in monitors.iter_mut().enumerate() {
667 for (workspace_idx, ws) in mon.workspaces.iter_mut().enumerate() {
668 if ws.has_window(window) {
669 *active_monitor_idx = monitor_idx;
670 // TODO
671 assert_eq!(mon.active_workspace_idx, workspace_idx);
672 ws.activate_window(window);
673 break;
674 }
675 }
676 }
677 }
678
679 pub fn activate_output(&mut self, output: &Output) {
680 let MonitorSet::Normal {
681 monitors,
682 active_monitor_idx,
683 ..
684 } = &mut self.monitor_set
685 else {
686 return;
687 };
688
689 let idx = monitors
690 .iter()
691 .position(|mon| &mon.output == output)
692 .unwrap();
693 *active_monitor_idx = idx;
694 }
695
696 pub fn active_output(&self) -> Option<&Output> {
697 let MonitorSet::Normal {
698 monitors,
699 active_monitor_idx,
700 ..
701 } = &self.monitor_set
702 else {
703 return None;
704 };
705
706 Some(&monitors[*active_monitor_idx].output)
707 }
708
709 pub fn active_workspace(&self) -> Option<&Workspace<W>> {
710 let MonitorSet::Normal {
711 monitors,
712 active_monitor_idx,
713 ..
714 } = &self.monitor_set
715 else {
716 return None;
717 };
718
719 let mon = &monitors[*active_monitor_idx];
720 Some(&mon.workspaces[mon.active_workspace_idx])
721 }
722
723 pub fn workspace_for_output(&self, output: &Output) -> Option<&Workspace<W>> {
724 let MonitorSet::Normal { monitors, .. } = &self.monitor_set else {
725 return None;
726 };
727
728 monitors.iter().find_map(|monitor| {
729 if &monitor.output == output {
730 Some(&monitor.workspaces[monitor.active_workspace_idx])
731 } else {
732 None
733 }
734 })
735 }
736
737 pub fn windows_for_output(&self, output: &Output) -> impl Iterator<Item = &W> + '_ {
738 let MonitorSet::Normal { monitors, .. } = &self.monitor_set else {
739 panic!()
740 };
741
742 let mon = monitors.iter().find(|mon| &mon.output == output).unwrap();
743 mon.workspaces.iter().flat_map(|ws| ws.windows())
744 }
745
746 fn active_monitor(&mut self) -> Option<&mut Monitor<W>> {
747 let MonitorSet::Normal {
748 monitors,
749 active_monitor_idx,
750 ..
751 } = &mut self.monitor_set
752 else {
753 return None;
754 };
755
756 Some(&mut monitors[*active_monitor_idx])
757 }
758
759 pub fn monitor_for_output(&self, output: &Output) -> Option<&Monitor<W>> {
760 let MonitorSet::Normal { monitors, .. } = &self.monitor_set else {
761 return None;
762 };
763
764 monitors.iter().find(|monitor| &monitor.output == output)
765 }
766
767 pub fn outputs(&self) -> impl Iterator<Item = &Output> + '_ {
768 let monitors = if let MonitorSet::Normal { monitors, .. } = &self.monitor_set {
769 &monitors[..]
770 } else {
771 &[][..]
772 };
773
774 monitors.iter().map(|mon| &mon.output)
775 }
776
777 pub fn move_left(&mut self) {
778 let Some(monitor) = self.active_monitor() else {
779 return;
780 };
781 monitor.move_left();
782 }
783
784 pub fn move_right(&mut self) {
785 let Some(monitor) = self.active_monitor() else {
786 return;
787 };
788 monitor.move_right();
789 }
790
791 pub fn move_down(&mut self) {
792 let Some(monitor) = self.active_monitor() else {
793 return;
794 };
795 monitor.move_down();
796 }
797
798 pub fn move_up(&mut self) {
799 let Some(monitor) = self.active_monitor() else {
800 return;
801 };
802 monitor.move_up();
803 }
804
805 pub fn focus_left(&mut self) {
806 let Some(monitor) = self.active_monitor() else {
807 return;
808 };
809 monitor.focus_left();
810 }
811
812 pub fn focus_right(&mut self) {
813 let Some(monitor) = self.active_monitor() else {
814 return;
815 };
816 monitor.focus_right();
817 }
818
819 pub fn focus_down(&mut self) {
820 let Some(monitor) = self.active_monitor() else {
821 return;
822 };
823 monitor.focus_down();
824 }
825
826 pub fn focus_up(&mut self) {
827 let Some(monitor) = self.active_monitor() else {
828 return;
829 };
830 monitor.focus_up();
831 }
832
833 pub fn move_to_workspace_up(&mut self) {
834 let Some(monitor) = self.active_monitor() else {
835 return;
836 };
837 monitor.move_to_workspace_up();
838 }
839
840 pub fn move_to_workspace_down(&mut self) {
841 let Some(monitor) = self.active_monitor() else {
842 return;
843 };
844 monitor.move_to_workspace_down();
845 }
846
847 pub fn move_to_workspace(&mut self, idx: u8) {
848 let Some(monitor) = self.active_monitor() else {
849 return;
850 };
851 monitor.move_to_workspace(idx);
852 }
853
854 pub fn switch_workspace_up(&mut self) {
855 let Some(monitor) = self.active_monitor() else {
856 return;
857 };
858 monitor.switch_workspace_up();
859 }
860
861 pub fn switch_workspace_down(&mut self) {
862 let Some(monitor) = self.active_monitor() else {
863 return;
864 };
865 monitor.switch_workspace_down();
866 }
867
868 pub fn switch_workspace(&mut self, idx: u8) {
869 let Some(monitor) = self.active_monitor() else {
870 return;
871 };
872 monitor.switch_workspace(idx);
873 }
874
875 pub fn consume_into_column(&mut self) {
876 let Some(monitor) = self.active_monitor() else {
877 return;
878 };
879 monitor.consume_into_column();
880 }
881
882 pub fn expel_from_column(&mut self) {
883 let Some(monitor) = self.active_monitor() else {
884 return;
885 };
886 monitor.expel_from_column();
887 }
888
889 pub fn focus(&self) -> Option<&W> {
890 let MonitorSet::Normal {
891 monitors,
892 active_monitor_idx,
893 ..
894 } = &self.monitor_set
895 else {
896 return None;
897 };
898
899 monitors[*active_monitor_idx].focus()
900 }
901
902 pub fn window_under(
903 &self,
904 output: &Output,
905 pos_within_output: Point<f64, Logical>,
906 ) -> Option<(&W, Point<i32, Logical>)> {
907 let ws = self.workspace_for_output(output).unwrap();
908 ws.window_under(pos_within_output)
909 }
910
911 #[cfg(test)]
912 fn verify_invariants(&self) {
913 let (monitors, &primary_idx, &active_monitor_idx) = match &self.monitor_set {
914 MonitorSet::Normal {
915 monitors,
916 primary_idx,
917 active_monitor_idx,
918 } => (monitors, primary_idx, active_monitor_idx),
919 MonitorSet::NoOutputs { workspaces } => {
920 for workspace in workspaces {
921 assert!(
922 workspace.has_windows(),
923 "with no outputs there cannot be empty workspaces"
924 );
925
926 assert_eq!(
927 workspace.options, self.options,
928 "workspace options must be synchronized with layout"
929 );
930
931 workspace.verify_invariants();
932 }
933
934 return;
935 }
936 };
937
938 assert!(primary_idx < monitors.len());
939 assert!(active_monitor_idx < monitors.len());
940
941 for (idx, monitor) in monitors.iter().enumerate() {
942 assert!(
943 !monitor.workspaces.is_empty(),
944 "monitor monitor must have at least one workspace"
945 );
946 assert!(monitor.active_workspace_idx < monitor.workspaces.len());
947
948 assert_eq!(
949 monitor.options, self.options,
950 "monitor options must be synchronized with layout"
951 );
952
953 let monitor_id = OutputId::new(&monitor.output);
954
955 if idx == primary_idx {
956 } else {
957 assert!(
958 monitor
959 .workspaces
960 .iter()
961 .any(|workspace| workspace.original_output == monitor_id),
962 "secondary monitor must have all own workspaces"
963 );
964 }
965
966 // FIXME: verify that primary doesn't have any workspaces for which their own monitor
967 // exists.
968
969 for workspace in &monitor.workspaces {
970 assert_eq!(
971 workspace.options, self.options,
972 "workspace options must be synchronized with layout"
973 );
974
975 workspace.verify_invariants();
976 }
977 }
978 }
979
980 pub fn advance_animations(&mut self, current_time: Duration) {
981 match &mut self.monitor_set {
982 MonitorSet::Normal {
983 monitors,
984 active_monitor_idx,
985 ..
986 } => {
987 for (idx, mon) in monitors.iter_mut().enumerate() {
988 mon.advance_animations(current_time, idx == *active_monitor_idx);
989 }
990 }
991 MonitorSet::NoOutputs { workspaces, .. } => {
992 for ws in workspaces {
993 ws.advance_animations(current_time, false);
994 }
995 }
996 }
997 }
998
999 pub fn update_config(&mut self, config: &Config) {
1000 let options = Rc::new(Options::from_config(config));
1001
1002 match &mut self.monitor_set {
1003 MonitorSet::Normal { monitors, .. } => {
1004 for mon in monitors {
1005 mon.update_config(options.clone());
1006 }
1007 }
1008 MonitorSet::NoOutputs { workspaces } => {
1009 for ws in workspaces {
1010 ws.update_config(options.clone());
1011 }
1012 }
1013 }
1014
1015 self.options = options;
1016 }
1017
1018 pub fn toggle_width(&mut self) {
1019 let Some(monitor) = self.active_monitor() else {
1020 return;
1021 };
1022 monitor.toggle_width();
1023 }
1024
1025 pub fn toggle_full_width(&mut self) {
1026 let Some(monitor) = self.active_monitor() else {
1027 return;
1028 };
1029 monitor.toggle_full_width();
1030 }
1031
1032 pub fn set_column_width(&mut self, change: SizeChange) {
1033 let Some(monitor) = self.active_monitor() else {
1034 return;
1035 };
1036 monitor.set_column_width(change);
1037 }
1038
1039 pub fn focus_output(&mut self, output: &Output) {
1040 if let MonitorSet::Normal {
1041 monitors,
1042 active_monitor_idx,
1043 ..
1044 } = &mut self.monitor_set
1045 {
1046 for (idx, mon) in monitors.iter().enumerate() {
1047 if &mon.output == output {
1048 *active_monitor_idx = idx;
1049 return;
1050 }
1051 }
1052 }
1053 }
1054
1055 pub fn move_to_output(&mut self, output: &Output) {
1056 if let MonitorSet::Normal {
1057 monitors,
1058 active_monitor_idx,
1059 ..
1060 } = &mut self.monitor_set
1061 {
1062 let new_idx = monitors
1063 .iter()
1064 .position(|mon| &mon.output == output)
1065 .unwrap();
1066
1067 let current = &mut monitors[*active_monitor_idx];
1068 let ws = current.active_workspace();
1069 if !ws.has_windows() {
1070 return;
1071 }
1072 let column = &ws.columns[ws.active_column_idx];
1073 let window = column.windows[column.active_window_idx].clone();
1074 ws.remove_window(&window);
1075
1076 let workspace_idx = monitors[new_idx].active_workspace_idx;
1077 self.add_window_by_idx(new_idx, workspace_idx, window, true);
1078 }
1079 }
1080
1081 pub fn move_window_to_output(&mut self, window: W, output: &Output) {
1082 self.remove_window(&window);
1083
1084 if let MonitorSet::Normal { monitors, .. } = &mut self.monitor_set {
1085 let new_idx = monitors
1086 .iter()
1087 .position(|mon| &mon.output == output)
1088 .unwrap();
1089
1090 let workspace_idx = monitors[new_idx].active_workspace_idx;
1091 // FIXME: activate only if it was already active and focused.
1092 self.add_window_by_idx(new_idx, workspace_idx, window, true);
1093 }
1094 }
1095
1096 pub fn set_fullscreen(&mut self, window: &W, is_fullscreen: bool) {
1097 match &mut self.monitor_set {
1098 MonitorSet::Normal { monitors, .. } => {
1099 for mon in monitors {
1100 for ws in &mut mon.workspaces {
1101 if ws.has_window(window) {
1102 ws.set_fullscreen(window, is_fullscreen);
1103 return;
1104 }
1105 }
1106 }
1107 }
1108 MonitorSet::NoOutputs { workspaces, .. } => {
1109 for ws in workspaces {
1110 if ws.has_window(window) {
1111 ws.set_fullscreen(window, is_fullscreen);
1112 return;
1113 }
1114 }
1115 }
1116 }
1117 }
1118
1119 pub fn toggle_fullscreen(&mut self, window: &W) {
1120 match &mut self.monitor_set {
1121 MonitorSet::Normal { monitors, .. } => {
1122 for mon in monitors {
1123 for ws in &mut mon.workspaces {
1124 if ws.has_window(window) {
1125 ws.toggle_fullscreen(window);
1126 return;
1127 }
1128 }
1129 }
1130 }
1131 MonitorSet::NoOutputs { workspaces, .. } => {
1132 for ws in workspaces {
1133 if ws.has_window(window) {
1134 ws.toggle_fullscreen(window);
1135 return;
1136 }
1137 }
1138 }
1139 }
1140 }
1141}
1142
1143impl Layout<Window> {
1144 pub fn refresh(&self) {
1145 let _span = tracy_client::span!("MonitorSet::refresh");
1146
1147 match &self.monitor_set {
1148 MonitorSet::Normal { monitors, .. } => {
1149 for mon in monitors {
1150 for ws in &mon.workspaces {
1151 ws.refresh();
1152 }
1153 }
1154 }
1155 MonitorSet::NoOutputs { workspaces, .. } => {
1156 for ws in workspaces {
1157 ws.refresh();
1158 }
1159 }
1160 }
1161 }
1162}
1163
1164impl<W: LayoutElement> Default for MonitorSet<W> {
1165 fn default() -> Self {
1166 Self::NoOutputs { workspaces: vec![] }
1167 }
1168}
1169
1170impl<W: LayoutElement> Monitor<W> {
1171 fn new(output: Output, workspaces: Vec<Workspace<W>>, options: Rc<Options>) -> Self {
1172 Self {
1173 output,
1174 workspaces,
1175 active_workspace_idx: 0,
1176 workspace_idx_anim: None,
1177 options,
1178 }
1179 }
1180
1181 fn active_workspace(&mut self) -> &mut Workspace<W> {
1182 &mut self.workspaces[self.active_workspace_idx]
1183 }
1184
1185 fn activate_workspace(&mut self, idx: usize) {
1186 if self.active_workspace_idx == idx {
1187 return;
1188 }
1189
1190 let current_idx = self
1191 .workspace_idx_anim
1192 .as_ref()
1193 .map(|anim| anim.value())
1194 .unwrap_or(self.active_workspace_idx as f64);
1195
1196 self.active_workspace_idx = idx;
1197
1198 self.workspace_idx_anim = Some(Animation::new(
1199 current_idx,
1200 idx as f64,
1201 Duration::from_millis(250),
1202 ));
1203 }
1204
1205 pub fn add_window(&mut self, workspace_idx: usize, window: W, activate: bool) {
1206 let workspace = &mut self.workspaces[workspace_idx];
1207
1208 workspace.add_window(window.clone(), activate);
1209
1210 // After adding a new window, workspace becomes this output's own.
1211 workspace.original_output = OutputId::new(&self.output);
1212
1213 if workspace_idx == self.workspaces.len() - 1 {
1214 // Insert a new empty workspace.
1215 let ws = Workspace::new(self.output.clone(), self.options.clone());
1216 self.workspaces.push(ws);
1217 }
1218
1219 if activate {
1220 self.activate_workspace(workspace_idx);
1221 }
1222 }
1223
1224 fn clean_up_workspaces(&mut self) {
1225 assert!(self.workspace_idx_anim.is_none());
1226
1227 for idx in (0..self.workspaces.len() - 1).rev() {
1228 if self.active_workspace_idx == idx {
1229 continue;
1230 }
1231
1232 if !self.workspaces[idx].has_windows() {
1233 self.workspaces.remove(idx);
1234 if self.active_workspace_idx > idx {
1235 self.active_workspace_idx -= 1;
1236 }
1237 }
1238 }
1239 }
1240
1241 pub fn move_left(&mut self) {
1242 self.active_workspace().move_left();
1243 }
1244
1245 pub fn move_right(&mut self) {
1246 self.active_workspace().move_right();
1247 }
1248
1249 pub fn move_down(&mut self) {
1250 self.active_workspace().move_down();
1251 }
1252
1253 pub fn move_up(&mut self) {
1254 self.active_workspace().move_up();
1255 }
1256
1257 pub fn focus_left(&mut self) {
1258 self.active_workspace().focus_left();
1259 }
1260
1261 pub fn focus_right(&mut self) {
1262 self.active_workspace().focus_right();
1263 }
1264
1265 pub fn focus_down(&mut self) {
1266 self.active_workspace().focus_down();
1267 }
1268
1269 pub fn focus_up(&mut self) {
1270 self.active_workspace().focus_up();
1271 }
1272
1273 pub fn move_to_workspace_up(&mut self) {
1274 let source_workspace_idx = self.active_workspace_idx;
1275
1276 let new_idx = source_workspace_idx.saturating_sub(1);
1277 if new_idx == source_workspace_idx {
1278 return;
1279 }
1280
1281 let workspace = &mut self.workspaces[source_workspace_idx];
1282 if workspace.columns.is_empty() {
1283 return;
1284 }
1285
1286 let column = &mut workspace.columns[workspace.active_column_idx];
1287 let window = column.windows[column.active_window_idx].clone();
1288 workspace.remove_window(&window);
1289
1290 self.add_window(new_idx, window, true);
1291 }
1292
1293 pub fn move_to_workspace_down(&mut self) {
1294 let source_workspace_idx = self.active_workspace_idx;
1295
1296 let new_idx = min(source_workspace_idx + 1, self.workspaces.len() - 1);
1297 if new_idx == source_workspace_idx {
1298 return;
1299 }
1300
1301 let workspace = &mut self.workspaces[source_workspace_idx];
1302 if workspace.columns.is_empty() {
1303 return;
1304 }
1305
1306 let column = &mut workspace.columns[workspace.active_column_idx];
1307 let window = column.windows[column.active_window_idx].clone();
1308 workspace.remove_window(&window);
1309
1310 self.add_window(new_idx, window, true);
1311 }
1312
1313 pub fn move_to_workspace(&mut self, idx: u8) {
1314 let source_workspace_idx = self.active_workspace_idx;
1315
1316 let new_idx = min(idx.saturating_sub(1) as usize, self.workspaces.len() - 1);
1317 if new_idx == source_workspace_idx {
1318 return;
1319 }
1320
1321 let workspace = &mut self.workspaces[source_workspace_idx];
1322 if workspace.columns.is_empty() {
1323 return;
1324 }
1325
1326 let column = &mut workspace.columns[workspace.active_column_idx];
1327 let window = column.windows[column.active_window_idx].clone();
1328 workspace.remove_window(&window);
1329
1330 self.add_window(new_idx, window, true);
1331
1332 // Don't animate this action.
1333 self.workspace_idx_anim = None;
1334 }
1335
1336 pub fn switch_workspace_up(&mut self) {
1337 self.activate_workspace(self.active_workspace_idx.saturating_sub(1));
1338 }
1339
1340 pub fn switch_workspace_down(&mut self) {
1341 self.activate_workspace(min(
1342 self.active_workspace_idx + 1,
1343 self.workspaces.len() - 1,
1344 ));
1345 }
1346
1347 pub fn switch_workspace(&mut self, idx: u8) {
1348 self.activate_workspace(min(
1349 idx.saturating_sub(1) as usize,
1350 self.workspaces.len() - 1,
1351 ));
1352 // Don't animate this action.
1353 self.workspace_idx_anim = None;
1354 }
1355
1356 pub fn consume_into_column(&mut self) {
1357 self.active_workspace().consume_into_column();
1358 }
1359
1360 pub fn expel_from_column(&mut self) {
1361 self.active_workspace().expel_from_column();
1362 }
1363
1364 pub fn focus(&self) -> Option<&W> {
1365 let workspace = &self.workspaces[self.active_workspace_idx];
1366 if !workspace.has_windows() {
1367 return None;
1368 }
1369
1370 let column = &workspace.columns[workspace.active_column_idx];
1371 Some(&column.windows[column.active_window_idx])
1372 }
1373
1374 pub fn advance_animations(&mut self, current_time: Duration, is_active: bool) {
1375 if let Some(anim) = &mut self.workspace_idx_anim {
1376 anim.set_current_time(current_time);
1377 if anim.is_done() {
1378 self.workspace_idx_anim = None;
1379 self.clean_up_workspaces();
1380 }
1381 }
1382
1383 for ws in &mut self.workspaces {
1384 ws.advance_animations(current_time, is_active);
1385 }
1386 }
1387
1388 pub fn are_animations_ongoing(&self) -> bool {
1389 self.workspace_idx_anim.is_some()
1390 || self.workspaces.iter().any(|ws| ws.are_animations_ongoing())
1391 }
1392
1393 fn update_config(&mut self, options: Rc<Options>) {
1394 for ws in &mut self.workspaces {
1395 ws.update_config(options.clone());
1396 }
1397
1398 self.options = options;
1399 }
1400
1401 fn toggle_width(&mut self) {
1402 self.active_workspace().toggle_width();
1403 }
1404
1405 fn toggle_full_width(&mut self) {
1406 self.active_workspace().toggle_full_width();
1407 }
1408
1409 fn set_column_width(&mut self, change: SizeChange) {
1410 self.active_workspace().set_column_width(change);
1411 }
1412}
1413
1414impl Monitor<Window> {
1415 pub fn render_elements(
1416 &self,
1417 renderer: &mut GlesRenderer,
1418 ) -> Vec<MonitorRenderElement<GlesRenderer>> {
1419 let output_scale = Scale::from(self.output.current_scale().fractional_scale());
1420 let output_transform = self.output.current_transform();
1421 let output_mode = self.output.current_mode().unwrap();
1422 let output_size = output_transform.transform_size(output_mode.size);
1423
1424 match &self.workspace_idx_anim {
1425 Some(anim) => {
1426 let render_idx = anim.value();
1427 let below_idx = render_idx.floor() as usize;
1428 let above_idx = render_idx.ceil() as usize;
1429
1430 let offset =
1431 ((render_idx - below_idx as f64) * output_size.h as f64).round() as i32;
1432
1433 let below = self.workspaces[below_idx].render_elements(renderer);
1434 let above = self.workspaces[above_idx].render_elements(renderer);
1435
1436 let below = below.into_iter().filter_map(|elem| {
1437 Some(RelocateRenderElement::from_element(
1438 CropRenderElement::from_element(
1439 elem,
1440 output_scale,
1441 Rectangle::from_loc_and_size((0, 0), output_size),
1442 )?,
1443 (0, -offset),
1444 Relocate::Relative,
1445 ))
1446 });
1447 let above = above.into_iter().filter_map(|elem| {
1448 Some(RelocateRenderElement::from_element(
1449 CropRenderElement::from_element(
1450 elem,
1451 output_scale,
1452 Rectangle::from_loc_and_size((0, 0), output_size),
1453 )?,
1454 (0, -offset + output_size.h),
1455 Relocate::Relative,
1456 ))
1457 });
1458 below.chain(above).collect()
1459 }
1460 None => {
1461 let elements = self.workspaces[self.active_workspace_idx].render_elements(renderer);
1462 elements
1463 .into_iter()
1464 .filter_map(|elem| {
1465 Some(RelocateRenderElement::from_element(
1466 CropRenderElement::from_element(
1467 elem,
1468 output_scale,
1469 Rectangle::from_loc_and_size((0, 0), output_size),
1470 )?,
1471 (0, 0),
1472 Relocate::Relative,
1473 ))
1474 })
1475 .collect()
1476 }
1477 }
1478 }
1479}
1480
1481impl<W: LayoutElement> Workspace<W> {
1482 fn new(output: Output, options: Rc<Options>) -> Self {
1483 let working_area = layer_map_for_output(&output).non_exclusive_zone();
1484 Self {
1485 original_output: OutputId::new(&output),
1486 view_size: output_size(&output),
1487 working_area,
1488 output: Some(output),
1489 columns: vec![],
1490 active_column_idx: 0,
1491 focus_ring: FocusRing::new(options.focus_ring),
1492 view_offset: 0,
1493 view_offset_anim: None,
1494 activate_prev_column_on_removal: false,
1495 options,
1496 }
1497 }
1498
1499 fn new_no_outputs(options: Rc<Options>) -> Self {
1500 Self {
1501 output: None,
1502 original_output: OutputId(String::new()),
1503 view_size: Size::from((1280, 720)),
1504 working_area: Rectangle::from_loc_and_size((0, 0), (1280, 720)),
1505 columns: vec![],
1506 active_column_idx: 0,
1507 focus_ring: FocusRing::new(options.focus_ring),
1508 view_offset: 0,
1509 view_offset_anim: None,
1510 activate_prev_column_on_removal: false,
1511 options,
1512 }
1513 }
1514
1515 pub fn advance_animations(&mut self, current_time: Duration, is_active: bool) {
1516 match &mut self.view_offset_anim {
1517 Some(anim) => {
1518 anim.set_current_time(current_time);
1519 self.view_offset = anim.value().round() as i32;
1520 if anim.is_done() {
1521 self.view_offset_anim = None;
1522 }
1523 }
1524 None => (),
1525 }
1526
1527 // This shall one day become a proper animation.
1528 if !self.columns.is_empty() {
1529 let col = &self.columns[self.active_column_idx];
1530 let active_win = &col.windows[col.active_window_idx];
1531 let geom = active_win.geometry();
1532 self.focus_ring.resize(geom.size);
1533 self.focus_ring.set_active(is_active);
1534 }
1535 }
1536
1537 pub fn are_animations_ongoing(&self) -> bool {
1538 self.view_offset_anim.is_some()
1539 }
1540
1541 fn update_config(&mut self, options: Rc<Options>) {
1542 let c = &options.focus_ring;
1543 self.focus_ring.is_off = c.off;
1544 self.focus_ring.width = c.width.into();
1545 self.focus_ring.active_color = c.active_color;
1546 self.focus_ring.inactive_color = c.inactive_color;
1547 // The focus ring buffer will be updated in a subsequent update_animations call.
1548
1549 for column in &mut self.columns {
1550 column.update_config(options.clone());
1551 }
1552
1553 self.options = options;
1554 }
1555
1556 fn windows(&self) -> impl Iterator<Item = &W> + '_ {
1557 self.columns.iter().flat_map(|col| col.windows.iter())
1558 }
1559
1560 fn set_output(&mut self, output: Option<Output>) {
1561 if self.output == output {
1562 return;
1563 }
1564
1565 if let Some(output) = self.output.take() {
1566 for win in self.windows() {
1567 win.output_leave(&output);
1568 }
1569 }
1570
1571 self.output = output;
1572
1573 if let Some(output) = &self.output {
1574 let working_area = layer_map_for_output(output).non_exclusive_zone();
1575 self.set_view_size(output_size(output), working_area);
1576
1577 for win in self.windows() {
1578 self.enter_output_for_window(win);
1579 }
1580 }
1581 }
1582
1583 fn enter_output_for_window(&self, window: &W) {
1584 if let Some(output) = &self.output {
1585 // FIXME: proper overlap.
1586 window.output_enter(
1587 output,
1588 Rectangle::from_loc_and_size((0, 0), (i32::MAX, i32::MAX)),
1589 );
1590 }
1591 }
1592
1593 fn set_view_size(&mut self, size: Size<i32, Logical>, working_area: Rectangle<i32, Logical>) {
1594 if self.view_size == size && self.working_area == working_area {
1595 return;
1596 }
1597
1598 self.view_size = size;
1599 self.working_area = working_area;
1600
1601 for col in &mut self.columns {
1602 col.set_view_size(self.view_size, self.working_area);
1603 }
1604 }
1605
1606 fn toplevel_bounds(&self) -> Size<i32, Logical> {
1607 Size::from((
1608 max(self.working_area.size.w - self.options.gaps * 2, 1),
1609 max(self.working_area.size.h - self.options.gaps * 2, 1),
1610 ))
1611 }
1612
1613 pub fn configure_new_window(&self, window: &Window) {
1614 let width = ColumnWidth::default().resolve(&self.options, self.working_area.size.w);
1615 let height = self.working_area.size.h - self.options.gaps * 2;
1616 let size = Size::from((max(width, 1), max(height, 1)));
1617
1618 let bounds = self.toplevel_bounds();
1619
1620 window.toplevel().with_pending_state(|state| {
1621 state.size = Some(size);
1622 state.bounds = Some(bounds);
1623 });
1624 }
1625
1626 fn compute_new_view_offset_for_column(&self, current_x: i32, idx: usize) -> i32 {
1627 if self.columns[idx].is_fullscreen {
1628 return 0;
1629 }
1630
1631 let new_col_x = self.column_x(idx);
1632
1633 let final_x = if let Some(anim) = &self.view_offset_anim {
1634 current_x - self.view_offset + anim.to().round() as i32
1635 } else {
1636 current_x
1637 };
1638
1639 let new_offset = compute_new_view_offset(
1640 final_x + self.working_area.loc.x,
1641 self.working_area.size.w,
1642 new_col_x,
1643 self.columns[idx].width(),
1644 self.options.gaps,
1645 );
1646
1647 // Non-fullscreen windows are always offset at least by the working area position.
1648 new_offset - self.working_area.loc.x
1649 }
1650
1651 fn animate_view_offset_to_column(&mut self, current_x: i32, idx: usize) {
1652 let new_view_offset = self.compute_new_view_offset_for_column(current_x, idx);
1653
1654 let new_col_x = self.column_x(idx);
1655 let from_view_offset = current_x - new_col_x;
1656 self.view_offset = from_view_offset;
1657
1658 // If we're already animating towards that, don't restart it.
1659 if let Some(anim) = &self.view_offset_anim {
1660 if anim.value().round() as i32 == self.view_offset
1661 && anim.to().round() as i32 == new_view_offset
1662 {
1663 return;
1664 }
1665 }
1666
1667 // If our view offset is already this, we don't need to do anything.
1668 if self.view_offset == new_view_offset {
1669 self.view_offset_anim = None;
1670 return;
1671 }
1672
1673 self.view_offset_anim = Some(Animation::new(
1674 self.view_offset as f64,
1675 new_view_offset as f64,
1676 Duration::from_millis(250),
1677 ));
1678 }
1679
1680 fn activate_column(&mut self, idx: usize) {
1681 if self.active_column_idx == idx {
1682 return;
1683 }
1684
1685 let current_x = self.view_pos();
1686 self.animate_view_offset_to_column(current_x, idx);
1687
1688 self.active_column_idx = idx;
1689
1690 // A different column was activated; reset the flag.
1691 self.activate_prev_column_on_removal = false;
1692 }
1693
1694 fn has_windows(&self) -> bool {
1695 self.windows().next().is_some()
1696 }
1697
1698 fn has_window(&self, window: &W) -> bool {
1699 self.windows().any(|win| win == window)
1700 }
1701
1702 fn find_wl_surface(&self, wl_surface: &WlSurface) -> Option<&W> {
1703 self.windows().find(|win| win.is_wl_surface(wl_surface))
1704 }
1705
1706 /// Computes the X position of the windows in the given column, in logical coordinates.
1707 fn column_x(&self, column_idx: usize) -> i32 {
1708 let mut x = 0;
1709
1710 for column in self.columns.iter().take(column_idx) {
1711 x += column.width() + self.options.gaps;
1712 }
1713
1714 x
1715 }
1716
1717 fn add_window(&mut self, window: W, activate: bool) {
1718 self.enter_output_for_window(&window);
1719
1720 let was_empty = self.columns.is_empty();
1721
1722 let idx = if self.columns.is_empty() {
1723 0
1724 } else {
1725 self.active_column_idx + 1
1726 };
1727
1728 let column = Column::new(
1729 window,
1730 self.view_size,
1731 self.working_area,
1732 self.options.clone(),
1733 );
1734 self.columns.insert(idx, column);
1735
1736 if activate {
1737 // If this is the first window on an empty workspace, skip the animation from whatever
1738 // view_offset was left over.
1739 if was_empty {
1740 // Try to make the code produce a left-aligned offset, even in presence of left
1741 // exclusive zones.
1742 self.view_offset = self.compute_new_view_offset_for_column(self.column_x(0), 0);
1743 self.view_offset_anim = None;
1744 }
1745
1746 self.activate_column(idx);
1747 self.activate_prev_column_on_removal = true;
1748 }
1749 }
1750
1751 fn remove_window(&mut self, window: &W) {
1752 if let Some(output) = &self.output {
1753 window.output_leave(output);
1754 }
1755
1756 let column_idx = self
1757 .columns
1758 .iter()
1759 .position(|col| col.contains(window))
1760 .unwrap();
1761 let column = &mut self.columns[column_idx];
1762
1763 let window_idx = column.windows.iter().position(|win| win == window).unwrap();
1764 column.windows.remove(window_idx);
1765 if column.windows.is_empty() {
1766 if column_idx + 1 == self.active_column_idx {
1767 // The previous column, that we were going to activate upon removal of the active
1768 // column, has just been itself removed.
1769 self.activate_prev_column_on_removal = false;
1770 }
1771
1772 // FIXME: activate_column below computes current view position to compute the new view
1773 // position, which can include the column we're removing here. This leads to unwanted
1774 // view jumps.
1775 self.columns.remove(column_idx);
1776 if self.columns.is_empty() {
1777 return;
1778 }
1779
1780 if self.active_column_idx > column_idx
1781 || (self.active_column_idx == column_idx && self.activate_prev_column_on_removal)
1782 {
1783 // A column to the left was removed; preserve the current position.
1784 // FIXME: preserve activate_prev_column_on_removal.
1785 // Or, the active column was removed, and we needed to activate the previous column.
1786 self.activate_column(self.active_column_idx.saturating_sub(1));
1787 } else {
1788 self.activate_column(min(self.active_column_idx, self.columns.len() - 1));
1789 }
1790
1791 return;
1792 }
1793
1794 column.active_window_idx = min(column.active_window_idx, column.windows.len() - 1);
1795 column.update_window_sizes();
1796 }
1797
1798 fn update_window(&mut self, window: &W) {
1799 let (idx, column) = self
1800 .columns
1801 .iter_mut()
1802 .enumerate()
1803 .find(|(_, col)| col.contains(window))
1804 .unwrap();
1805 column.update_window_sizes();
1806
1807 if idx == self.active_column_idx {
1808 // We might need to move the view to ensure the resized window is still visible.
1809 let current_x = self.view_pos();
1810 self.animate_view_offset_to_column(current_x, idx);
1811 }
1812 }
1813
1814 fn activate_window(&mut self, window: &W) {
1815 let column_idx = self
1816 .columns
1817 .iter()
1818 .position(|col| col.contains(window))
1819 .unwrap();
1820 let column = &mut self.columns[column_idx];
1821
1822 column.activate_window(window);
1823 self.activate_column(column_idx);
1824 }
1825
1826 #[cfg(test)]
1827 fn verify_invariants(&self) {
1828 assert!(self.view_size.w > 0);
1829 assert!(self.view_size.h > 0);
1830
1831 if !self.columns.is_empty() {
1832 assert!(self.active_column_idx < self.columns.len());
1833
1834 for column in &self.columns {
1835 column.verify_invariants();
1836 }
1837 }
1838 }
1839
1840 fn focus_left(&mut self) {
1841 self.activate_column(self.active_column_idx.saturating_sub(1));
1842 }
1843
1844 fn focus_right(&mut self) {
1845 if self.columns.is_empty() {
1846 return;
1847 }
1848
1849 self.activate_column(min(self.active_column_idx + 1, self.columns.len() - 1));
1850 }
1851
1852 fn focus_down(&mut self) {
1853 if self.columns.is_empty() {
1854 return;
1855 }
1856
1857 self.columns[self.active_column_idx].focus_down();
1858 }
1859
1860 fn focus_up(&mut self) {
1861 if self.columns.is_empty() {
1862 return;
1863 }
1864
1865 self.columns[self.active_column_idx].focus_up();
1866 }
1867
1868 fn move_left(&mut self) {
1869 let new_idx = self.active_column_idx.saturating_sub(1);
1870 if self.active_column_idx == new_idx {
1871 return;
1872 }
1873
1874 let current_x = self.view_pos();
1875
1876 self.columns.swap(self.active_column_idx, new_idx);
1877
1878 self.view_offset =
1879 self.compute_new_view_offset_for_column(current_x, self.active_column_idx);
1880
1881 self.activate_column(new_idx);
1882 }
1883
1884 fn move_right(&mut self) {
1885 if self.columns.is_empty() {
1886 return;
1887 }
1888
1889 let new_idx = min(self.active_column_idx + 1, self.columns.len() - 1);
1890 if self.active_column_idx == new_idx {
1891 return;
1892 }
1893
1894 let current_x = self.view_pos();
1895
1896 self.columns.swap(self.active_column_idx, new_idx);
1897
1898 self.view_offset =
1899 self.compute_new_view_offset_for_column(current_x, self.active_column_idx);
1900
1901 self.activate_column(new_idx);
1902 }
1903
1904 fn move_down(&mut self) {
1905 if self.columns.is_empty() {
1906 return;
1907 }
1908
1909 self.columns[self.active_column_idx].move_down();
1910 }
1911
1912 fn move_up(&mut self) {
1913 if self.columns.is_empty() {
1914 return;
1915 }
1916
1917 self.columns[self.active_column_idx].move_up();
1918 }
1919
1920 fn consume_into_column(&mut self) {
1921 if self.columns.len() < 2 {
1922 return;
1923 }
1924
1925 if self.active_column_idx == self.columns.len() - 1 {
1926 return;
1927 }
1928
1929 let source_column_idx = self.active_column_idx + 1;
1930
1931 let source_column = &mut self.columns[source_column_idx];
1932 let window = source_column.windows[0].clone();
1933 self.remove_window(&window);
1934
1935 let target_column = &mut self.columns[self.active_column_idx];
1936 target_column.add_window(window);
1937 }
1938
1939 fn expel_from_column(&mut self) {
1940 if self.columns.is_empty() {
1941 return;
1942 }
1943
1944 let source_column = &mut self.columns[self.active_column_idx];
1945 if source_column.windows.len() == 1 {
1946 return;
1947 }
1948
1949 let window = source_column.windows[source_column.active_window_idx].clone();
1950 self.remove_window(&window);
1951
1952 self.add_window(window, true);
1953 }
1954
1955 fn view_pos(&self) -> i32 {
1956 self.column_x(self.active_column_idx) + self.view_offset
1957 }
1958
1959 fn window_under(&self, pos: Point<f64, Logical>) -> Option<(&W, Point<i32, Logical>)> {
1960 if self.columns.is_empty() {
1961 return None;
1962 }
1963
1964 let view_pos = self.view_pos();
1965
1966 // Prefer the active window since it's drawn on top.
1967 let col = &self.columns[self.active_column_idx];
1968 let active_win = &col.windows[col.active_window_idx];
1969 let geom = active_win.geometry();
1970 let buf_pos = Point::from((
1971 self.column_x(self.active_column_idx) - view_pos,
1972 col.window_y(col.active_window_idx),
1973 )) - geom.loc;
1974 if active_win.is_in_input_region(&(pos - buf_pos.to_f64())) {
1975 return Some((active_win, buf_pos));
1976 }
1977
1978 let mut x = -view_pos;
1979 for col in &self.columns {
1980 for (win, y) in zip(&col.windows, col.window_ys()) {
1981 if win == active_win {
1982 // Already handled it above.
1983 continue;
1984 }
1985
1986 let geom = win.geometry();
1987 let buf_pos = Point::from((x, y)) - geom.loc;
1988 if win.is_in_input_region(&(pos - buf_pos.to_f64())) {
1989 return Some((win, buf_pos));
1990 }
1991 }
1992
1993 x += col.width() + self.options.gaps;
1994 }
1995
1996 None
1997 }
1998
1999 fn toggle_width(&mut self) {
2000 if self.columns.is_empty() {
2001 return;
2002 }
2003
2004 self.columns[self.active_column_idx].toggle_width();
2005 }
2006
2007 fn toggle_full_width(&mut self) {
2008 if self.columns.is_empty() {
2009 return;
2010 }
2011
2012 self.columns[self.active_column_idx].toggle_full_width();
2013 }
2014
2015 fn set_column_width(&mut self, change: SizeChange) {
2016 if self.columns.is_empty() {
2017 return;
2018 }
2019
2020 self.columns[self.active_column_idx].set_column_width(change);
2021 }
2022
2023 pub fn set_fullscreen(&mut self, window: &W, is_fullscreen: bool) {
2024 let (mut col_idx, win_idx) = self
2025 .columns
2026 .iter()
2027 .enumerate()
2028 .find_map(|(col_idx, col)| {
2029 col.windows
2030 .iter()
2031 .position(|w| w == window)
2032 .map(|win_idx| (col_idx, win_idx))
2033 })
2034 .unwrap();
2035
2036 let mut col = &mut self.columns[col_idx];
2037
2038 if is_fullscreen && col.windows.len() > 1 {
2039 // This wasn't the only window in its column; extract it into a separate column.
2040 let target_window_was_focused =
2041 self.active_column_idx == col_idx && col.active_window_idx == win_idx;
2042 let window = col.windows.remove(win_idx);
2043 col.active_window_idx = min(col.active_window_idx, col.windows.len() - 1);
2044 col.update_window_sizes();
2045
2046 col_idx += 1;
2047 self.columns.insert(
2048 col_idx,
2049 Column::new(
2050 window,
2051 self.view_size,
2052 self.working_area,
2053 self.options.clone(),
2054 ),
2055 );
2056 if self.active_column_idx >= col_idx || target_window_was_focused {
2057 self.active_column_idx += 1;
2058 }
2059 col = &mut self.columns[col_idx];
2060 }
2061
2062 col.set_fullscreen(is_fullscreen);
2063 }
2064
2065 pub fn toggle_fullscreen(&mut self, window: &W) {
2066 let col = self
2067 .columns
2068 .iter_mut()
2069 .find(|col| col.windows.contains(window))
2070 .unwrap();
2071 let value = !col.is_fullscreen;
2072 self.set_fullscreen(window, value);
2073 }
2074}
2075
2076impl Workspace<Window> {
2077 fn refresh(&self) {
2078 let bounds = self.toplevel_bounds();
2079
2080 for (col_idx, col) in self.columns.iter().enumerate() {
2081 for (win_idx, win) in col.windows.iter().enumerate() {
2082 let active = self.active_column_idx == col_idx && col.active_window_idx == win_idx;
2083 win.set_activated(active);
2084
2085 win.toplevel().with_pending_state(|state| {
2086 state.bounds = Some(bounds);
2087 });
2088
2089 win.toplevel().send_pending_configure();
2090 win.refresh();
2091 }
2092 }
2093 }
2094
2095 pub fn render_elements(
2096 &self,
2097 renderer: &mut GlesRenderer,
2098 ) -> Vec<WorkspaceRenderElement<GlesRenderer>> {
2099 if self.columns.is_empty() {
2100 return vec![];
2101 }
2102
2103 // FIXME: workspaces should probably cache their last used scale so they can be correctly
2104 // rendered even with no outputs connected.
2105 let output_scale = self
2106 .output
2107 .as_ref()
2108 .map(|o| Scale::from(o.current_scale().fractional_scale()))
2109 .unwrap_or(Scale::from(1.));
2110
2111 let mut rv = vec![];
2112 let view_pos = self.view_pos();
2113
2114 // Draw the active window on top.
2115 let col = &self.columns[self.active_column_idx];
2116 let active_win = &col.windows[col.active_window_idx];
2117 let win_pos = Point::from((
2118 self.column_x(self.active_column_idx) - view_pos,
2119 col.window_y(col.active_window_idx),
2120 ));
2121
2122 // Draw the window itself.
2123 let geom = active_win.geometry();
2124 let buf_pos = win_pos - geom.loc;
2125 rv.extend(active_win.render_elements(
2126 renderer,
2127 buf_pos.to_physical_precise_round(output_scale),
2128 output_scale,
2129 1.,
2130 ));
2131
2132 // Draw the focus ring.
2133 rv.extend(
2134 self.focus_ring
2135 .render(win_pos, output_scale)
2136 .map(Into::into),
2137 );
2138
2139 let mut x = -view_pos;
2140 for col in &self.columns {
2141 for (win, y) in zip(&col.windows, col.window_ys()) {
2142 if win == active_win {
2143 // Already handled it above.
2144 continue;
2145 }
2146
2147 let geom = win.geometry();
2148 let buf_pos = Point::from((x, y)) - geom.loc;
2149 rv.extend(win.render_elements(
2150 renderer,
2151 buf_pos.to_physical_precise_round(output_scale),
2152 output_scale,
2153 1.,
2154 ));
2155 }
2156
2157 x += col.width() + self.options.gaps;
2158 }
2159
2160 rv
2161 }
2162}
2163
2164impl<W: LayoutElement> Column<W> {
2165 fn new(
2166 window: W,
2167 view_size: Size<i32, Logical>,
2168 working_area: Rectangle<i32, Logical>,
2169 options: Rc<Options>,
2170 ) -> Self {
2171 let mut rv = Self {
2172 windows: vec![],
2173 active_window_idx: 0,
2174 width: ColumnWidth::default(),
2175 is_fullscreen: false,
2176 view_size,
2177 working_area,
2178 options,
2179 };
2180
2181 rv.add_window(window);
2182
2183 rv
2184 }
2185
2186 fn set_view_size(&mut self, size: Size<i32, Logical>, working_area: Rectangle<i32, Logical>) {
2187 if self.view_size == size && self.working_area == working_area {
2188 return;
2189 }
2190
2191 self.view_size = size;
2192 self.working_area = working_area;
2193
2194 self.update_window_sizes();
2195 }
2196
2197 fn update_config(&mut self, options: Rc<Options>) {
2198 let mut update_sizes = false;
2199
2200 // If preset widths changed, make our width non-preset.
2201 if self.options.preset_widths != options.preset_widths {
2202 if let ColumnWidth::Preset(idx) = self.width {
2203 self.width = self.options.preset_widths[idx];
2204 }
2205 }
2206
2207 if self.options.gaps != options.gaps {
2208 update_sizes = true;
2209 }
2210
2211 self.options = options;
2212
2213 if update_sizes {
2214 self.update_window_sizes();
2215 }
2216 }
2217
2218 fn window_count(&self) -> usize {
2219 self.windows.len()
2220 }
2221
2222 fn set_width(&mut self, width: ColumnWidth) {
2223 self.width = width;
2224 self.update_window_sizes();
2225 }
2226
2227 fn contains(&self, window: &W) -> bool {
2228 self.windows.iter().any(|win| win == window)
2229 }
2230
2231 fn activate_window(&mut self, window: &W) {
2232 let idx = self.windows.iter().position(|win| win == window).unwrap();
2233 self.active_window_idx = idx;
2234 }
2235
2236 fn add_window(&mut self, window: W) {
2237 self.is_fullscreen = false;
2238 self.windows.push(window);
2239 self.update_window_sizes();
2240 }
2241
2242 fn update_window_sizes(&mut self) {
2243 if self.is_fullscreen {
2244 self.windows[0].request_fullscreen(self.view_size);
2245 return;
2246 }
2247
2248 let min_width = self
2249 .windows
2250 .iter()
2251 .filter_map(|win| {
2252 let w = win.min_size().w;
2253 if w == 0 {
2254 None
2255 } else {
2256 Some(w)
2257 }
2258 })
2259 .max()
2260 .unwrap_or(1);
2261 let max_width = self
2262 .windows
2263 .iter()
2264 .filter_map(|win| {
2265 let w = win.max_size().w;
2266 if w == 0 {
2267 None
2268 } else {
2269 Some(w)
2270 }
2271 })
2272 .min()
2273 .unwrap_or(i32::MAX);
2274 let max_width = max(max_width, min_width);
2275
2276 let width = self.width.resolve(&self.options, self.working_area.size.w);
2277 let height = (self.working_area.size.h - self.options.gaps) / self.window_count() as i32
2278 - self.options.gaps;
2279 let size = Size::from((max(min(width, max_width), min_width), max(height, 1)));
2280
2281 for win in &self.windows {
2282 win.request_size(size);
2283 }
2284 }
2285
2286 fn width(&self) -> i32 {
2287 self.windows
2288 .iter()
2289 .map(|win| win.geometry().size.w)
2290 .max()
2291 .unwrap()
2292 }
2293
2294 fn focus_up(&mut self) {
2295 self.active_window_idx = self.active_window_idx.saturating_sub(1);
2296 }
2297
2298 fn focus_down(&mut self) {
2299 self.active_window_idx = min(self.active_window_idx + 1, self.windows.len() - 1);
2300 }
2301
2302 fn move_up(&mut self) {
2303 let new_idx = self.active_window_idx.saturating_sub(1);
2304 if self.active_window_idx == new_idx {
2305 return;
2306 }
2307
2308 self.windows.swap(self.active_window_idx, new_idx);
2309 self.active_window_idx = new_idx;
2310 }
2311
2312 fn move_down(&mut self) {
2313 let new_idx = min(self.active_window_idx + 1, self.windows.len() - 1);
2314 if self.active_window_idx == new_idx {
2315 return;
2316 }
2317
2318 self.windows.swap(self.active_window_idx, new_idx);
2319 self.active_window_idx = new_idx;
2320 }
2321
2322 #[cfg(test)]
2323 fn verify_invariants(&self) {
2324 assert!(!self.windows.is_empty(), "columns can't be empty");
2325 assert!(self.active_window_idx < self.windows.len());
2326
2327 if self.is_fullscreen {
2328 assert_eq!(self.windows.len(), 1);
2329 }
2330 }
2331
2332 fn toggle_width(&mut self) {
2333 let idx = match self.width {
2334 ColumnWidth::Preset(idx) => (idx + 1) % self.options.preset_widths.len(),
2335 _ => {
2336 let current = self.width();
2337 self.options
2338 .preset_widths
2339 .iter()
2340 .position(|prop| {
2341 prop.resolve(&self.options, self.working_area.size.w) > current
2342 })
2343 .unwrap_or(0)
2344 }
2345 };
2346 let width = ColumnWidth::Preset(idx);
2347 self.set_width(width);
2348 }
2349
2350 fn toggle_full_width(&mut self) {
2351 let width = match self.width {
2352 ColumnWidth::Proportion(x) if x == 1. => {
2353 // FIXME: would be good to restore to previous width here.
2354 ColumnWidth::default()
2355 }
2356 _ => ColumnWidth::Proportion(1.),
2357 };
2358 self.set_width(width);
2359 }
2360
2361 fn set_column_width(&mut self, change: SizeChange) {
2362 let current_px = self.width.resolve(&self.options, self.working_area.size.w);
2363
2364 let current = match self.width {
2365 ColumnWidth::Preset(idx) => self.options.preset_widths[idx],
2366 current => current,
2367 };
2368
2369 // FIXME: fix overflows then remove limits.
2370 const MAX_PX: i32 = 100000;
2371 const MAX_F: f64 = 10000.;
2372
2373 let width = match (current, change) {
2374 (_, SizeChange::SetFixed(fixed)) => ColumnWidth::Fixed(fixed.clamp(1, MAX_PX)),
2375 (_, SizeChange::SetProportion(proportion)) => {
2376 ColumnWidth::Proportion((proportion / 100.).clamp(0., MAX_F))
2377 }
2378 (_, SizeChange::AdjustFixed(delta)) => {
2379 let width = current_px.saturating_add(delta).clamp(1, MAX_PX);
2380 ColumnWidth::Fixed(width)
2381 }
2382 (ColumnWidth::Proportion(current), SizeChange::AdjustProportion(delta)) => {
2383 let proportion = (current + delta / 100.).clamp(0., MAX_F);
2384 ColumnWidth::Proportion(proportion)
2385 }
2386 (ColumnWidth::Fixed(_), SizeChange::AdjustProportion(delta)) => {
2387 let current = (current_px + self.options.gaps) as f64
2388 / (self.working_area.size.w - self.options.gaps) as f64;
2389 let proportion = (current + delta / 100.).clamp(0., MAX_F);
2390 ColumnWidth::Proportion(proportion)
2391 }
2392 (ColumnWidth::Preset(_), _) => unreachable!(),
2393 };
2394
2395 self.set_width(width);
2396 }
2397
2398 fn set_fullscreen(&mut self, is_fullscreen: bool) {
2399 assert_eq!(self.windows.len(), 1);
2400 self.is_fullscreen = is_fullscreen;
2401 self.update_window_sizes();
2402 }
2403
2404 fn window_y(&self, window_idx: usize) -> i32 {
2405 self.window_ys().nth(window_idx).unwrap()
2406 }
2407
2408 fn window_ys(&self) -> impl Iterator<Item = i32> + '_ {
2409 let mut y = 0;
2410
2411 if !self.is_fullscreen {
2412 y = self.working_area.loc.y + self.options.gaps;
2413 }
2414
2415 self.windows.iter().map(move |win| {
2416 let pos = y;
2417 y += win.geometry().size.h + self.options.gaps;
2418 pos
2419 })
2420 }
2421}
2422
2423pub fn output_size(output: &Output) -> Size<i32, Logical> {
2424 let output_scale = output.current_scale().integer_scale();
2425 let output_transform = output.current_transform();
2426 let output_mode = output.current_mode().unwrap();
2427
2428 output_transform
2429 .transform_size(output_mode.size)
2430 .to_logical(output_scale)
2431}
2432
2433fn compute_new_view_offset(
2434 cur_x: i32,
2435 view_width: i32,
2436 new_col_x: i32,
2437 new_col_width: i32,
2438 gaps: i32,
2439) -> i32 {
2440 // If the column is wider than the view, always left-align it.
2441 if view_width <= new_col_width {
2442 return 0;
2443 }
2444
2445 // Compute the padding in case it needs to be smaller due to large window width.
2446 let padding = ((view_width - new_col_width) / 2).clamp(0, gaps);
2447
2448 // Compute the desired new X with padding.
2449 let new_x = new_col_x - padding;
2450 let new_right_x = new_col_x + new_col_width + padding;
2451
2452 // If the column is already fully visible, leave the view as is.
2453 if cur_x <= new_x && new_right_x <= cur_x + view_width {
2454 return -(new_col_x - cur_x);
2455 }
2456
2457 // Otherwise, prefer the aligment that results in less motion from the current position.
2458 let dist_to_left = cur_x.abs_diff(new_x);
2459 let dist_to_right = (cur_x + view_width).abs_diff(new_right_x);
2460 if dist_to_left <= dist_to_right {
2461 -padding
2462 } else {
2463 -(view_width - padding - new_col_width)
2464 }
2465}
2466
2467#[cfg(test)]
2468mod tests {
2469 use std::cell::Cell;
2470 use std::rc::Rc;
2471
2472 use proptest::prelude::*;
2473 use proptest_derive::Arbitrary;
2474 use smithay::output::{Mode, PhysicalProperties, Subpixel};
2475 use smithay::utils::IsAlive;
2476
2477 use super::*;
2478
2479 impl<W: LayoutElement> Default for Layout<W> {
2480 fn default() -> Self {
2481 Self {
2482 monitor_set: MonitorSet::NoOutputs { workspaces: vec![] },
2483 options: Rc::new(Options::default()),
2484 }
2485 }
2486 }
2487
2488 #[derive(Debug)]
2489 struct TestWindowInner {
2490 id: usize,
2491 bbox: Cell<Rectangle<i32, Logical>>,
2492 initial_bbox: Rectangle<i32, Logical>,
2493 requested_size: Cell<Option<Size<i32, Logical>>>,
2494 }
2495
2496 #[derive(Debug, Clone)]
2497 struct TestWindow(Rc<TestWindowInner>);
2498
2499 impl TestWindow {
2500 fn new(id: usize, bbox: Rectangle<i32, Logical>) -> Self {
2501 Self(Rc::new(TestWindowInner {
2502 id,
2503 bbox: Cell::new(bbox),
2504 initial_bbox: bbox,
2505 requested_size: Cell::new(None),
2506 }))
2507 }
2508
2509 fn communicate(&self) -> bool {
2510 if let Some(size) = self.0.requested_size.take() {
2511 assert!(size.w >= 0);
2512 assert!(size.h >= 0);
2513
2514 let mut new_bbox = self.0.initial_bbox;
2515 if size.w != 0 {
2516 new_bbox.size.w = size.w;
2517 }
2518 if size.h != 0 {
2519 new_bbox.size.h = size.h;
2520 }
2521
2522 if self.0.bbox.get() != new_bbox {
2523 self.0.bbox.set(new_bbox);
2524 return true;
2525 }
2526 }
2527
2528 false
2529 }
2530 }
2531
2532 impl PartialEq for TestWindow {
2533 fn eq(&self, other: &Self) -> bool {
2534 self.0.id == other.0.id
2535 }
2536 }
2537
2538 impl IsAlive for TestWindow {
2539 fn alive(&self) -> bool {
2540 true
2541 }
2542 }
2543
2544 impl SpaceElement for TestWindow {
2545 fn bbox(&self) -> Rectangle<i32, Logical> {
2546 self.0.bbox.get()
2547 }
2548
2549 fn is_in_input_region(&self, _point: &Point<f64, Logical>) -> bool {
2550 false
2551 }
2552
2553 fn set_activate(&self, _activated: bool) {}
2554 fn output_enter(&self, _output: &Output, _overlap: Rectangle<i32, Logical>) {}
2555 fn output_leave(&self, _output: &Output) {}
2556 }
2557
2558 impl LayoutElement for TestWindow {
2559 fn request_size(&self, size: Size<i32, Logical>) {
2560 self.0.requested_size.set(Some(size));
2561 }
2562
2563 fn request_fullscreen(&self, _size: Size<i32, Logical>) {}
2564
2565 fn min_size(&self) -> Size<i32, Logical> {
2566 Size::from((0, 0))
2567 }
2568
2569 fn max_size(&self) -> Size<i32, Logical> {
2570 Size::from((0, 0))
2571 }
2572
2573 fn is_wl_surface(&self, _wl_surface: &WlSurface) -> bool {
2574 false
2575 }
2576 }
2577
2578 fn arbitrary_bbox() -> impl Strategy<Value = Rectangle<i32, Logical>> {
2579 any::<(i16, i16, u16, u16)>().prop_map(|(x, y, w, h)| {
2580 let loc: Point<i32, _> = Point::from((x.into(), y.into()));
2581 let size: Size<i32, _> = Size::from((w.into(), h.into()));
2582 Rectangle::from_loc_and_size(loc, size)
2583 })
2584 }
2585
2586 fn arbitrary_size_change() -> impl Strategy<Value = SizeChange> {
2587 prop_oneof![
2588 (0..).prop_map(SizeChange::SetFixed),
2589 (0f64..).prop_map(SizeChange::SetProportion),
2590 any::<i32>().prop_map(SizeChange::AdjustFixed),
2591 any::<f64>().prop_map(SizeChange::AdjustProportion),
2592 ]
2593 }
2594
2595 #[derive(Debug, Clone, Copy, Arbitrary)]
2596 enum Op {
2597 AddOutput(#[proptest(strategy = "1..=5usize")] usize),
2598 RemoveOutput(#[proptest(strategy = "1..=5usize")] usize),
2599 FocusOutput(#[proptest(strategy = "1..=5usize")] usize),
2600 AddWindow {
2601 #[proptest(strategy = "1..=5usize")]
2602 id: usize,
2603 #[proptest(strategy = "arbitrary_bbox()")]
2604 bbox: Rectangle<i32, Logical>,
2605 activate: bool,
2606 },
2607 CloseWindow(#[proptest(strategy = "1..=5usize")] usize),
2608 FullscreenWindow(#[proptest(strategy = "1..=5usize")] usize),
2609 FocusColumnLeft,
2610 FocusColumnRight,
2611 FocusWindowDown,
2612 FocusWindowUp,
2613 MoveColumnLeft,
2614 MoveColumnRight,
2615 MoveWindowDown,
2616 MoveWindowUp,
2617 ConsumeWindowIntoColumn,
2618 ExpelWindowFromColumn,
2619 FocusWorkspaceDown,
2620 FocusWorkspaceUp,
2621 FocusWorkspace(#[proptest(strategy = "1..=5u8")] u8),
2622 MoveWindowToWorkspaceDown,
2623 MoveWindowToWorkspaceUp,
2624 MoveWindowToWorkspace(#[proptest(strategy = "1..=5u8")] u8),
2625 MoveWindowToOutput(#[proptest(strategy = "1..=5u8")] u8),
2626 SwitchPresetColumnWidth,
2627 MaximizeColumn,
2628 SetColumnWidth(#[proptest(strategy = "arbitrary_size_change()")] SizeChange),
2629 Communicate(#[proptest(strategy = "1..=5usize")] usize),
2630 }
2631
2632 impl Op {
2633 fn apply(self, layout: &mut Layout<TestWindow>) {
2634 match self {
2635 Op::AddOutput(id) => {
2636 let name = format!("output{id}");
2637 if layout.outputs().any(|o| o.name() == name) {
2638 return;
2639 }
2640
2641 let output = Output::new(
2642 name,
2643 PhysicalProperties {
2644 size: Size::from((1280, 720)),
2645 subpixel: Subpixel::Unknown,
2646 make: String::new(),
2647 model: String::new(),
2648 },
2649 );
2650 output.change_current_state(
2651 Some(Mode {
2652 size: Size::from((1280, 720)),
2653 refresh: 60,
2654 }),
2655 None,
2656 None,
2657 None,
2658 );
2659 layout.add_output(output.clone());
2660 }
2661 Op::RemoveOutput(id) => {
2662 let name = format!("output{id}");
2663 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
2664 return;
2665 };
2666
2667 layout.remove_output(&output);
2668 }
2669 Op::FocusOutput(id) => {
2670 let name = format!("output{id}");
2671 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
2672 return;
2673 };
2674
2675 layout.focus_output(&output);
2676 }
2677 Op::AddWindow { id, bbox, activate } => {
2678 let win = TestWindow::new(id, bbox);
2679 layout.add_window(win, activate);
2680 }
2681 Op::CloseWindow(id) => {
2682 let dummy = TestWindow::new(id, Rectangle::default());
2683 layout.remove_window(&dummy);
2684 }
2685 Op::FullscreenWindow(id) => {
2686 let dummy = TestWindow::new(id, Rectangle::default());
2687 layout.toggle_fullscreen(&dummy);
2688 }
2689 Op::FocusColumnLeft => layout.focus_left(),
2690 Op::FocusColumnRight => layout.focus_right(),
2691 Op::FocusWindowDown => layout.focus_down(),
2692 Op::FocusWindowUp => layout.focus_up(),
2693 Op::MoveColumnLeft => layout.move_left(),
2694 Op::MoveColumnRight => layout.move_right(),
2695 Op::MoveWindowDown => layout.move_down(),
2696 Op::MoveWindowUp => layout.move_up(),
2697 Op::ConsumeWindowIntoColumn => layout.consume_into_column(),
2698 Op::ExpelWindowFromColumn => layout.expel_from_column(),
2699 Op::FocusWorkspaceDown => layout.switch_workspace_down(),
2700 Op::FocusWorkspaceUp => layout.switch_workspace_up(),
2701 Op::FocusWorkspace(idx) => layout.switch_workspace(idx),
2702 Op::MoveWindowToWorkspaceDown => layout.move_to_workspace_down(),
2703 Op::MoveWindowToWorkspaceUp => layout.move_to_workspace_up(),
2704 Op::MoveWindowToWorkspace(idx) => layout.move_to_workspace(idx),
2705 Op::MoveWindowToOutput(id) => {
2706 let name = format!("output{id}");
2707 let Some(output) = layout.outputs().find(|o| o.name() == name).cloned() else {
2708 return;
2709 };
2710
2711 layout.move_to_output(&output);
2712 }
2713 Op::SwitchPresetColumnWidth => layout.toggle_width(),
2714 Op::MaximizeColumn => layout.toggle_full_width(),
2715 Op::SetColumnWidth(change) => layout.set_column_width(change),
2716 Op::Communicate(id) => {
2717 let mut window = None;
2718 match &mut layout.monitor_set {
2719 MonitorSet::Normal { monitors, .. } => {
2720 'outer: for mon in monitors {
2721 for ws in &mut mon.workspaces {
2722 for win in ws.windows() {
2723 if win.0.id == id {
2724 if win.communicate() {
2725 window = Some(win.clone());
2726 }
2727 break 'outer;
2728 }
2729 }
2730 }
2731 }
2732 }
2733 MonitorSet::NoOutputs { workspaces, .. } => {
2734 'outer: for ws in workspaces {
2735 for win in ws.windows() {
2736 if win.0.id == id {
2737 if win.communicate() {
2738 window = Some(win.clone());
2739 }
2740 break 'outer;
2741 }
2742 }
2743 }
2744 }
2745 }
2746
2747 if let Some(win) = window {
2748 layout.update_window(&win);
2749 }
2750 }
2751 }
2752 }
2753 }
2754
2755 #[track_caller]
2756 fn check_ops(ops: &[Op]) {
2757 let mut layout = Layout::default();
2758 for op in ops {
2759 op.apply(&mut layout);
2760 layout.verify_invariants();
2761 }
2762 }
2763
2764 #[test]
2765 fn operations_dont_panic() {
2766 let every_op = [
2767 Op::AddOutput(0),
2768 Op::AddOutput(1),
2769 Op::AddOutput(2),
2770 Op::RemoveOutput(0),
2771 Op::RemoveOutput(1),
2772 Op::RemoveOutput(2),
2773 Op::FocusOutput(0),
2774 Op::FocusOutput(1),
2775 Op::FocusOutput(2),
2776 Op::AddWindow {
2777 id: 0,
2778 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2779 activate: true,
2780 },
2781 Op::AddWindow {
2782 id: 1,
2783 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2784 activate: true,
2785 },
2786 Op::AddWindow {
2787 id: 2,
2788 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2789 activate: true,
2790 },
2791 Op::CloseWindow(0),
2792 Op::CloseWindow(1),
2793 Op::CloseWindow(2),
2794 Op::FocusColumnLeft,
2795 Op::FocusColumnRight,
2796 Op::MoveColumnLeft,
2797 Op::MoveColumnRight,
2798 Op::ConsumeWindowIntoColumn,
2799 Op::ExpelWindowFromColumn,
2800 Op::FocusWorkspaceDown,
2801 Op::FocusWorkspaceUp,
2802 Op::FocusWorkspace(1),
2803 Op::FocusWorkspace(2),
2804 Op::FocusWorkspace(3),
2805 Op::MoveWindowToWorkspaceDown,
2806 Op::MoveWindowToWorkspaceUp,
2807 Op::MoveWindowToWorkspace(1),
2808 Op::MoveWindowToWorkspace(2),
2809 Op::MoveWindowToWorkspace(3),
2810 ];
2811
2812 for third in every_op {
2813 for second in every_op {
2814 for first in every_op {
2815 // eprintln!("{first:?}, {second:?}, {third:?}");
2816
2817 let mut layout = Layout::default();
2818 first.apply(&mut layout);
2819 layout.verify_invariants();
2820 second.apply(&mut layout);
2821 layout.verify_invariants();
2822 third.apply(&mut layout);
2823 layout.verify_invariants();
2824 }
2825 }
2826 }
2827 }
2828
2829 #[test]
2830 fn operations_from_starting_state_dont_panic() {
2831 if std::env::var_os("RUN_SLOW_TESTS").is_none() {
2832 eprintln!("ignoring slow test");
2833 return;
2834 }
2835
2836 // Running every op from an empty state doesn't get us to all the interesting states. So,
2837 // also run it from a manually-created starting state with more things going on to exercise
2838 // more code paths.
2839 let setup_ops = [
2840 Op::AddOutput(1),
2841 Op::AddWindow {
2842 id: 1,
2843 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2844 activate: true,
2845 },
2846 Op::MoveWindowToWorkspaceDown,
2847 Op::AddWindow {
2848 id: 2,
2849 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2850 activate: true,
2851 },
2852 Op::AddWindow {
2853 id: 3,
2854 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2855 activate: true,
2856 },
2857 Op::FocusColumnLeft,
2858 Op::ConsumeWindowIntoColumn,
2859 Op::AddWindow {
2860 id: 4,
2861 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2862 activate: true,
2863 },
2864 Op::AddOutput(2),
2865 Op::AddWindow {
2866 id: 5,
2867 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2868 activate: true,
2869 },
2870 Op::MoveWindowToOutput(2),
2871 Op::FocusOutput(1),
2872 Op::Communicate(1),
2873 Op::Communicate(2),
2874 Op::Communicate(3),
2875 Op::Communicate(4),
2876 Op::Communicate(5),
2877 ];
2878
2879 let every_op = [
2880 Op::AddOutput(0),
2881 Op::AddOutput(1),
2882 Op::AddOutput(2),
2883 Op::RemoveOutput(0),
2884 Op::RemoveOutput(1),
2885 Op::RemoveOutput(2),
2886 Op::FocusOutput(0),
2887 Op::FocusOutput(1),
2888 Op::FocusOutput(2),
2889 Op::AddWindow {
2890 id: 0,
2891 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2892 activate: true,
2893 },
2894 Op::AddWindow {
2895 id: 1,
2896 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2897 activate: true,
2898 },
2899 Op::AddWindow {
2900 id: 2,
2901 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2902 activate: true,
2903 },
2904 Op::CloseWindow(0),
2905 Op::CloseWindow(1),
2906 Op::CloseWindow(2),
2907 Op::FocusColumnLeft,
2908 Op::FocusColumnRight,
2909 Op::MoveColumnLeft,
2910 Op::MoveColumnRight,
2911 Op::ConsumeWindowIntoColumn,
2912 Op::ExpelWindowFromColumn,
2913 Op::FocusWorkspaceDown,
2914 Op::FocusWorkspaceUp,
2915 Op::FocusWorkspace(1),
2916 Op::FocusWorkspace(2),
2917 Op::FocusWorkspace(3),
2918 Op::MoveWindowToWorkspaceDown,
2919 Op::MoveWindowToWorkspaceUp,
2920 Op::MoveWindowToWorkspace(1),
2921 Op::MoveWindowToWorkspace(2),
2922 Op::MoveWindowToWorkspace(3),
2923 ];
2924
2925 for third in every_op {
2926 for second in every_op {
2927 for first in every_op {
2928 // eprintln!("{first:?}, {second:?}, {third:?}");
2929
2930 let mut layout = Layout::default();
2931 for op in setup_ops {
2932 op.apply(&mut layout);
2933 }
2934
2935 first.apply(&mut layout);
2936 layout.verify_invariants();
2937 second.apply(&mut layout);
2938 layout.verify_invariants();
2939 third.apply(&mut layout);
2940 layout.verify_invariants();
2941 }
2942 }
2943 }
2944 }
2945
2946 #[test]
2947 fn primary_active_workspace_idx_not_updated_on_output_add() {
2948 let ops = [
2949 Op::AddOutput(1),
2950 Op::AddOutput(2),
2951 Op::FocusOutput(1),
2952 Op::AddWindow {
2953 id: 0,
2954 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2955 activate: true,
2956 },
2957 Op::FocusOutput(2),
2958 Op::AddWindow {
2959 id: 1,
2960 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2961 activate: true,
2962 },
2963 Op::RemoveOutput(2),
2964 Op::FocusWorkspace(3),
2965 Op::AddOutput(2),
2966 ];
2967
2968 check_ops(&ops);
2969 }
2970
2971 #[test]
2972 fn window_closed_on_previous_workspace() {
2973 let ops = [
2974 Op::AddOutput(1),
2975 Op::AddWindow {
2976 id: 0,
2977 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2978 activate: true,
2979 },
2980 Op::FocusWorkspaceDown,
2981 Op::CloseWindow(0),
2982 ];
2983
2984 check_ops(&ops);
2985 }
2986
2987 proptest! {
2988 #![proptest_config(ProptestConfig {
2989 cases: if std::env::var_os("RUN_SLOW_TESTS").is_none() {
2990 eprintln!("ignoring slow test");
2991 0
2992 } else {
2993 ProptestConfig::default().cases
2994 },
2995 ..ProptestConfig::default()
2996 })]
2997
2998 #[test]
2999 fn random_operations_dont_panic(ops: Vec<Op>) {
3000 // eprintln!("{ops:?}");
3001 check_ops(&ops);
3002 }
3003 }
3004}