forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB66583cdIvan Molodetskikh1 year ago2489 commits

scrolling.rs5569 lines, 197.4 KiBHistoryRawDownload
1use std::cmp::{max, min};
2use std::iter::{self, zip};
3use std::rc::Rc;
4use std::time::Duration;
5
6use niri_config::utils::MergeWith as _;
7use niri_config::{CenterFocusedColumn, PresetSize, Struts};
8use niri_ipc::{ColumnDisplay, SizeChange, WindowLayout};
9use ordered_float::NotNan;
10use smithay::backend::renderer::gles::GlesRenderer;
11use smithay::utils::{Logical, Point, Rectangle, Scale, Serial, Size};
12
13use super::closing_window::{ClosingWindow, ClosingWindowRenderElement};
14use super::monitor::InsertPosition;
15use super::tab_indicator::{TabIndicator, TabIndicatorRenderElement, TabInfo};
16use super::tile::{Tile, TileRenderElement, TileRenderSnapshot};
17use super::workspace::{InteractiveResize, ResolvedSize};
18use super::{ConfigureIntent, HitType, InteractiveResizeData, LayoutElement, Options, RemovedTile};
19use crate::animation::{Animation, Clock};
20use crate::input::swipe_tracker::SwipeTracker;
21use crate::layout::SizingMode;
22use crate::niri_render_elements;
23use crate::render_helpers::renderer::NiriRenderer;
24use crate::render_helpers::RenderTarget;
25use crate::utils::transaction::{Transaction, TransactionBlocker};
26use crate::utils::ResizeEdge;
27use crate::window::ResolvedWindowRules;
28
29/// Amount of touchpad movement to scroll the view for the width of one working area.
30const VIEW_GESTURE_WORKING_AREA_MOVEMENT: f64 = 1200.;
31
32/// A scrollable-tiling space for windows.
33#[derive(Debug)]
34pub struct ScrollingSpace<W: LayoutElement> {
35 /// Columns of windows on this space.
36 columns: Vec<Column<W>>,
37
38 /// Extra per-column data.
39 data: Vec<ColumnData>,
40
41 /// Index of the currently active column, if any.
42 active_column_idx: usize,
43
44 /// Ongoing interactive resize.
45 interactive_resize: Option<InteractiveResize<W>>,
46
47 /// Offset of the view computed from the active column.
48 ///
49 /// Any gaps, including left padding from work area left exclusive zone, is handled
50 /// with this view offset (rather than added as a constant elsewhere in the code). This allows
51 /// for natural handling of fullscreen windows, which must ignore work area padding.
52 view_offset: ViewOffset,
53
54 /// Whether to activate the previous, rather than the next, column upon column removal.
55 ///
56 /// When a new column is created and removed with no focus changes in-between, it is more
57 /// natural to activate the previously-focused column. This variable tracks that.
58 ///
59 /// Since we only create-and-activate columns immediately to the right of the active column (in
60 /// contrast to tabs in Firefox, for example), we can track this as a bool, rather than an
61 /// index of the previous column to activate.
62 ///
63 /// The value is the view offset that the previous column had before, to restore it.
64 activate_prev_column_on_removal: Option<f64>,
65
66 /// View offset to restore after unfullscreening or unmaximizing.
67 view_offset_to_restore: Option<f64>,
68
69 /// Windows in the closing animation.
70 closing_windows: Vec<ClosingWindow>,
71
72 /// View size for this space.
73 view_size: Size<f64, Logical>,
74
75 /// Working area for this space.
76 ///
77 /// Takes into account layer-shell exclusive zones and niri struts.
78 working_area: Rectangle<f64, Logical>,
79
80 /// Working area for this space excluding struts.
81 ///
82 /// Used for popup unconstraining. Popups can go over struts, but they shouldn't go over
83 /// the layer-shell top layer (which renders on top of popups).
84 parent_area: Rectangle<f64, Logical>,
85
86 /// Scale of the output the space is on (and rounds its sizes to).
87 scale: f64,
88
89 /// Clock for driving animations.
90 clock: Clock,
91
92 /// Configurable properties of the layout.
93 options: Rc<Options>,
94}
95
96niri_render_elements! {
97 ScrollingSpaceRenderElement<R> => {
98 Tile = TileRenderElement<R>,
99 ClosingWindow = ClosingWindowRenderElement,
100 TabIndicator = TabIndicatorRenderElement,
101 }
102}
103
104/// Extra per-column data.
105#[derive(Debug, Clone, Copy, PartialEq)]
106struct ColumnData {
107 /// Cached actual column width.
108 width: f64,
109}
110
111#[derive(Debug)]
112pub(super) enum ViewOffset {
113 /// The view offset is static.
114 Static(f64),
115 /// The view offset is animating.
116 Animation(Animation),
117 /// The view offset is controlled by the ongoing gesture.
118 Gesture(ViewGesture),
119}
120
121#[derive(Debug)]
122pub(super) struct ViewGesture {
123 current_view_offset: f64,
124 /// Animation for the extra offset to the current position.
125 ///
126 /// For example, when we need to activate a specific window during a DnD scroll.
127 animation: Option<Animation>,
128 tracker: SwipeTracker,
129 delta_from_tracker: f64,
130 // The view offset we'll use if needed for activate_prev_column_on_removal.
131 stationary_view_offset: f64,
132 /// Whether the gesture is controlled by the touchpad.
133 is_touchpad: bool,
134
135 // If this gesture is for drag-and-drop scrolling, this is the last event's unadjusted
136 // timestamp.
137 dnd_last_event_time: Option<Duration>,
138 // Time when the drag-and-drop scroll delta became non-zero, used for debouncing.
139 //
140 // If `None` then the scroll delta is currently zero.
141 dnd_nonzero_start_time: Option<Duration>,
142}
143
144#[derive(Debug)]
145pub struct Column<W: LayoutElement> {
146 /// Tiles in this column.
147 ///
148 /// Must be non-empty.
149 tiles: Vec<Tile<W>>,
150
151 /// Extra per-tile data.
152 ///
153 /// Must have the same number of elements as `tiles`.
154 data: Vec<TileData>,
155
156 /// Index of the currently active tile.
157 active_tile_idx: usize,
158
159 /// Desired width of this column.
160 ///
161 /// If the column is full-width or full-screened, this is the width that should be restored
162 /// upon unfullscreening and untoggling full-width.
163 width: ColumnWidth,
164
165 /// Currently selected preset width index.
166 preset_width_idx: Option<usize>,
167
168 /// Whether this column is full-width.
169 is_full_width: bool,
170
171 /// Whether this column is going to be fullscreen.
172 ///
173 /// This is the compositor-side fullscreen state, so it changes immediately upon
174 /// set_fullscreen(). The actual tiles will take some time to respond to the fullscreen request
175 /// and become fullscreen.
176 ///
177 /// Similarly, unsetting fullscreen will change this value to false immediately, and tiles will
178 /// take some time to catch up and actually unfullscreen.
179 is_pending_fullscreen: bool,
180
181 /// Whether this column is going to be maximized.
182 ///
183 /// Can be `true` together with `is_pending_fullscreen`, which means that the column is
184 /// effectively pending fullscreen, but unfullscreening should go back to maximized state,
185 /// rather than normal.
186 is_pending_maximized: bool,
187
188 /// How this column displays and arranges windows.
189 display_mode: ColumnDisplay,
190
191 /// Tab indicator for the tabbed display mode.
192 tab_indicator: TabIndicator,
193
194 /// Animation of the render offset during window swapping.
195 move_animation: Option<MoveAnimation>,
196
197 /// Latest known view size for this column's workspace.
198 view_size: Size<f64, Logical>,
199
200 /// Latest known working area for this column's workspace.
201 working_area: Rectangle<f64, Logical>,
202
203 /// Working area for this column's workspace excluding struts.
204 ///
205 /// Used for maximize-to-edges.
206 parent_area: Rectangle<f64, Logical>,
207
208 /// Scale of the output the column is on (and rounds its sizes to).
209 scale: f64,
210
211 /// Clock for driving animations.
212 clock: Clock,
213
214 /// Configurable properties of the layout.
215 options: Rc<Options>,
216}
217
218/// Extra per-tile data.
219#[derive(Debug, Clone, Copy, PartialEq)]
220struct TileData {
221 /// Requested height of the window.
222 ///
223 /// This is window height, not tile height, so it excludes tile decorations.
224 height: WindowHeight,
225
226 /// Cached actual size of the tile.
227 size: Size<f64, Logical>,
228
229 /// Cached whether the tile is being interactively resized by its left edge.
230 interactively_resizing_by_left_edge: bool,
231}
232
233/// Width of a column.
234#[derive(Debug, Clone, Copy, PartialEq)]
235pub enum ColumnWidth {
236 /// Proportion of the current view width.
237 Proportion(f64),
238 /// Fixed width in logical pixels.
239 Fixed(f64),
240}
241
242/// Height of a window in a column.
243///
244/// Every window but one in a column must be `Auto`-sized so that the total height can add up to
245/// the workspace height. Resizing a window converts all other windows to `Auto`, weighted to
246/// preserve their visual heights at the moment of the conversion.
247///
248/// In contrast to column widths, proportional height changes are converted to, and stored as,
249/// fixed height right away. With column widths you frequently want e.g. two columns side-by-side
250/// with 50% width each, and you want them to remain this way when moving to a differently sized
251/// monitor. Windows in a column, however, already auto-size to fill the available height, giving
252/// you this behavior. The main reason to set a different window height, then, is when you want
253/// something in the window to fit exactly, e.g. to fit 30 lines in a terminal, which corresponds
254/// to the `Fixed` variant.
255#[derive(Debug, Clone, Copy, PartialEq)]
256pub enum WindowHeight {
257 /// Automatically computed *tile* height, distributed across the column according to weights.
258 ///
259 /// This controls the tile height rather than the window height because it's easier in the auto
260 /// height distribution algorithm.
261 Auto { weight: f64 },
262 /// Fixed *window* height in logical pixels.
263 Fixed(f64),
264 /// One of the preset heights (tile or window).
265 Preset(usize),
266}
267
268/// Horizontal direction for an operation.
269///
270/// As operations often have a symmetrical counterpart, e.g. focus-right/focus-left, methods
271/// on `Scrolling` can sometimes be factored using the direction of the operation as a parameter.
272#[derive(Debug, Clone, Copy, PartialEq)]
273pub enum ScrollDirection {
274 Left,
275 Right,
276}
277
278#[derive(Debug)]
279struct MoveAnimation {
280 anim: Animation,
281 from: f64,
282}
283
284impl<W: LayoutElement> ScrollingSpace<W> {
285 pub fn new(
286 view_size: Size<f64, Logical>,
287 parent_area: Rectangle<f64, Logical>,
288 scale: f64,
289 clock: Clock,
290 options: Rc<Options>,
291 ) -> Self {
292 let working_area = compute_working_area(parent_area, scale, options.layout.struts);
293
294 Self {
295 columns: Vec::new(),
296 data: Vec::new(),
297 active_column_idx: 0,
298 interactive_resize: None,
299 view_offset: ViewOffset::Static(0.),
300 activate_prev_column_on_removal: None,
301 view_offset_to_restore: None,
302 closing_windows: Vec::new(),
303 view_size,
304 working_area,
305 parent_area,
306 scale,
307 clock,
308 options,
309 }
310 }
311
312 pub fn update_config(
313 &mut self,
314 view_size: Size<f64, Logical>,
315 parent_area: Rectangle<f64, Logical>,
316 scale: f64,
317 options: Rc<Options>,
318 ) {
319 let working_area = compute_working_area(parent_area, scale, options.layout.struts);
320
321 for (column, data) in zip(&mut self.columns, &mut self.data) {
322 column.update_config(view_size, working_area, parent_area, scale, options.clone());
323 data.update(column);
324 }
325
326 self.view_size = view_size;
327 self.working_area = working_area;
328 self.parent_area = parent_area;
329 self.scale = scale;
330 self.options = options;
331
332 // Apply always-center and such right away.
333 if !self.columns.is_empty() && !self.view_offset.is_gesture() {
334 self.animate_view_offset_to_column(None, self.active_column_idx, None);
335 }
336 }
337
338 pub fn update_shaders(&mut self) {
339 for tile in self.tiles_mut() {
340 tile.update_shaders();
341 }
342 }
343
344 pub fn advance_animations(&mut self) {
345 if let ViewOffset::Animation(anim) = &self.view_offset {
346 if anim.is_done() {
347 self.view_offset = ViewOffset::Static(anim.to());
348 }
349 }
350
351 if let ViewOffset::Gesture(gesture) = &mut self.view_offset {
352 // Make sure the last event time doesn't go too much out of date (for
353 // workspaces not under cursor), causing sudden jumps.
354 //
355 // This happens after any dnd_scroll_gesture_scroll() calls (in
356 // Layout::advance_animations()), so it doesn't mess up the time delta there.
357 if let Some(last_time) = &mut gesture.dnd_last_event_time {
358 let now = self.clock.now_unadjusted();
359 if *last_time != now {
360 *last_time = now;
361
362 // If last_time was already == now, then dnd_scroll_gesture_scroll() must've
363 // updated the gesture already. Therefore, when this code runs, the pointer
364 // must be outside the DnD scrolling zone.
365 gesture.dnd_nonzero_start_time = None;
366 }
367 }
368
369 if let Some(anim) = &mut gesture.animation {
370 if anim.is_done() {
371 gesture.animation = None;
372 }
373 }
374 }
375
376 for col in &mut self.columns {
377 col.advance_animations();
378 }
379
380 self.closing_windows.retain_mut(|closing| {
381 closing.advance_animations();
382 closing.are_animations_ongoing()
383 });
384 }
385
386 pub fn are_animations_ongoing(&self) -> bool {
387 self.view_offset.is_animation_ongoing()
388 || self.columns.iter().any(Column::are_animations_ongoing)
389 || !self.closing_windows.is_empty()
390 }
391
392 pub fn are_transitions_ongoing(&self) -> bool {
393 !self.view_offset.is_static()
394 || self.columns.iter().any(Column::are_transitions_ongoing)
395 || !self.closing_windows.is_empty()
396 }
397
398 pub fn update_render_elements(&mut self, is_active: bool) {
399 let view_pos = Point::from((self.view_pos(), 0.));
400 let view_size = self.view_size;
401 let active_idx = self.active_column_idx;
402 for (col_idx, (col, col_x)) in self.columns_mut().enumerate() {
403 let is_active = is_active && col_idx == active_idx;
404 let col_off = Point::from((col_x, 0.));
405 let col_pos = view_pos - col_off - col.render_offset();
406 let view_rect = Rectangle::new(col_pos, view_size);
407 col.update_render_elements(is_active, view_rect);
408 }
409 }
410
411 pub fn tiles(&self) -> impl Iterator<Item = &Tile<W>> + '_ {
412 self.columns.iter().flat_map(|col| col.tiles.iter())
413 }
414
415 pub fn tiles_mut(&mut self) -> impl Iterator<Item = &mut Tile<W>> + '_ {
416 self.columns.iter_mut().flat_map(|col| col.tiles.iter_mut())
417 }
418
419 pub fn is_empty(&self) -> bool {
420 self.columns.is_empty()
421 }
422
423 pub fn active_window(&self) -> Option<&W> {
424 if self.columns.is_empty() {
425 return None;
426 }
427
428 let col = &self.columns[self.active_column_idx];
429 Some(col.tiles[col.active_tile_idx].window())
430 }
431
432 pub fn active_window_mut(&mut self) -> Option<&mut W> {
433 if self.columns.is_empty() {
434 return None;
435 }
436
437 let col = &mut self.columns[self.active_column_idx];
438 Some(col.tiles[col.active_tile_idx].window_mut())
439 }
440
441 pub fn active_tile_mut(&mut self) -> Option<&mut Tile<W>> {
442 if self.columns.is_empty() {
443 return None;
444 }
445
446 let col = &mut self.columns[self.active_column_idx];
447 Some(&mut col.tiles[col.active_tile_idx])
448 }
449
450 pub fn is_active_pending_fullscreen(&self) -> bool {
451 if self.columns.is_empty() {
452 return false;
453 }
454
455 let col = &self.columns[self.active_column_idx];
456 col.pending_sizing_mode().is_fullscreen()
457 }
458
459 pub fn new_window_toplevel_bounds(&self, rules: &ResolvedWindowRules) -> Size<i32, Logical> {
460 let border_config = self.options.layout.border.merged_with(&rules.border);
461
462 let display_mode = rules
463 .default_column_display
464 .unwrap_or(self.options.layout.default_column_display);
465 let will_tab = display_mode == ColumnDisplay::Tabbed;
466 let extra_size = if will_tab {
467 TabIndicator::new(self.options.layout.tab_indicator).extra_size(1, self.scale)
468 } else {
469 Size::from((0., 0.))
470 };
471
472 compute_toplevel_bounds(
473 border_config,
474 self.working_area.size,
475 extra_size,
476 self.options.layout.gaps,
477 )
478 }
479
480 pub fn new_window_size(
481 &self,
482 width: Option<PresetSize>,
483 height: Option<PresetSize>,
484 rules: &ResolvedWindowRules,
485 ) -> Size<i32, Logical> {
486 let border = self.options.layout.border.merged_with(&rules.border);
487
488 let display_mode = rules
489 .default_column_display
490 .unwrap_or(self.options.layout.default_column_display);
491 let will_tab = display_mode == ColumnDisplay::Tabbed;
492 let extra = if will_tab {
493 TabIndicator::new(self.options.layout.tab_indicator).extra_size(1, self.scale)
494 } else {
495 Size::from((0., 0.))
496 };
497
498 let working_size = self.working_area.size;
499
500 let width = if let Some(size) = width {
501 let size = match resolve_preset_size(size, &self.options, working_size.w, extra.w) {
502 ResolvedSize::Tile(mut size) => {
503 if !border.off {
504 size -= border.width * 2.;
505 }
506 size
507 }
508 ResolvedSize::Window(size) => size,
509 };
510
511 max(1, size.floor() as i32)
512 } else {
513 0
514 };
515
516 let mut full_height = self.working_area.size.h - self.options.layout.gaps * 2.;
517 if !border.off {
518 full_height -= border.width * 2.;
519 }
520
521 let height = if let Some(height) = height {
522 let height = match resolve_preset_size(height, &self.options, working_size.h, extra.h) {
523 ResolvedSize::Tile(mut size) => {
524 if !border.off {
525 size -= border.width * 2.;
526 }
527 size
528 }
529 ResolvedSize::Window(size) => size,
530 };
531 f64::min(height, full_height)
532 } else {
533 full_height
534 };
535
536 Size::from((width, max(height.floor() as i32, 1)))
537 }
538
539 pub fn is_centering_focused_column(&self) -> bool {
540 self.options.layout.center_focused_column == CenterFocusedColumn::Always
541 || (self.options.layout.always_center_single_column && self.columns.len() <= 1)
542 }
543
544 fn compute_new_view_offset_fit(
545 &self,
546 target_x: Option<f64>,
547 col_x: f64,
548 width: f64,
549 mode: SizingMode,
550 ) -> f64 {
551 if mode.is_fullscreen() {
552 return 0.;
553 }
554
555 let (area, padding) = if mode.is_maximized() {
556 (self.parent_area, 0.)
557 } else {
558 (self.working_area, self.options.layout.gaps)
559 };
560
561 let target_x = target_x.unwrap_or_else(|| self.target_view_pos());
562
563 let new_offset =
564 compute_new_view_offset(target_x + area.loc.x, area.size.w, col_x, width, padding);
565
566 // Non-fullscreen windows are always offset at least by the working area position.
567 new_offset - area.loc.x
568 }
569
570 fn compute_new_view_offset_centered(
571 &self,
572 target_x: Option<f64>,
573 col_x: f64,
574 width: f64,
575 mode: SizingMode,
576 ) -> f64 {
577 if mode.is_fullscreen() {
578 return self.compute_new_view_offset_fit(target_x, col_x, width, mode);
579 }
580
581 let area = if mode.is_maximized() {
582 self.parent_area
583 } else {
584 self.working_area
585 };
586
587 // Columns wider than the view are left-aligned (the fit code can deal with that).
588 if area.size.w <= width {
589 return self.compute_new_view_offset_fit(target_x, col_x, width, mode);
590 }
591
592 -(area.size.w - width) / 2. - area.loc.x
593 }
594
595 fn compute_new_view_offset_for_column_fit(&self, target_x: Option<f64>, idx: usize) -> f64 {
596 let col = &self.columns[idx];
597 self.compute_new_view_offset_fit(
598 target_x,
599 self.column_x(idx),
600 col.width(),
601 col.sizing_mode(),
602 )
603 }
604
605 fn compute_new_view_offset_for_column_centered(
606 &self,
607 target_x: Option<f64>,
608 idx: usize,
609 ) -> f64 {
610 let col = &self.columns[idx];
611 self.compute_new_view_offset_centered(
612 target_x,
613 self.column_x(idx),
614 col.width(),
615 col.sizing_mode(),
616 )
617 }
618
619 fn compute_new_view_offset_for_column(
620 &self,
621 target_x: Option<f64>,
622 idx: usize,
623 prev_idx: Option<usize>,
624 ) -> f64 {
625 if self.is_centering_focused_column() {
626 return self.compute_new_view_offset_for_column_centered(target_x, idx);
627 }
628
629 match self.options.layout.center_focused_column {
630 CenterFocusedColumn::Always => {
631 self.compute_new_view_offset_for_column_centered(target_x, idx)
632 }
633 CenterFocusedColumn::OnOverflow => {
634 let Some(prev_idx) = prev_idx else {
635 return self.compute_new_view_offset_for_column_fit(target_x, idx);
636 };
637
638 // Activating the same column.
639 if prev_idx == idx {
640 return self.compute_new_view_offset_for_column_fit(target_x, idx);
641 }
642
643 // Always take the left or right neighbor of the target as the source.
644 let source_idx = if prev_idx > idx {
645 min(idx + 1, self.columns.len() - 1)
646 } else {
647 idx.saturating_sub(1)
648 };
649
650 let source_col_x = self.column_x(source_idx);
651 let source_col_width = self.columns[source_idx].width();
652
653 let target_col_x = self.column_x(idx);
654 let target_col_width = self.columns[idx].width();
655
656 // NOTE: This logic won't work entirely correctly with small fixed-size maximized
657 // windows (they have a different area and padding).
658 let total_width = if source_col_x < target_col_x {
659 // Source is left from target.
660 target_col_x - source_col_x + target_col_width
661 } else {
662 // Source is right from target.
663 source_col_x - target_col_x + source_col_width
664 } + self.options.layout.gaps * 2.;
665
666 // If it fits together, do a normal animation, otherwise center the new column.
667 if total_width <= self.working_area.size.w {
668 self.compute_new_view_offset_for_column_fit(target_x, idx)
669 } else {
670 self.compute_new_view_offset_for_column_centered(target_x, idx)
671 }
672 }
673 CenterFocusedColumn::Never => {
674 self.compute_new_view_offset_for_column_fit(target_x, idx)
675 }
676 }
677 }
678
679 fn animate_view_offset(&mut self, idx: usize, new_view_offset: f64) {
680 self.animate_view_offset_with_config(
681 idx,
682 new_view_offset,
683 self.options.animations.horizontal_view_movement.0,
684 );
685 }
686
687 fn animate_view_offset_with_config(
688 &mut self,
689 idx: usize,
690 new_view_offset: f64,
691 config: niri_config::Animation,
692 ) {
693 let new_col_x = self.column_x(idx);
694 let old_col_x = self.column_x(self.active_column_idx);
695 let offset_delta = old_col_x - new_col_x;
696 self.view_offset.offset(offset_delta);
697
698 let pixel = 1. / self.scale;
699
700 // If our view offset is already this or animating towards this, we don't need to do
701 // anything.
702 let to_diff = new_view_offset - self.view_offset.target();
703 if to_diff.abs() < pixel {
704 // Correct for any inaccuracy.
705 self.view_offset.offset(to_diff);
706 return;
707 }
708
709 match &mut self.view_offset {
710 ViewOffset::Gesture(gesture) if gesture.dnd_last_event_time.is_some() => {
711 gesture.stationary_view_offset = new_view_offset;
712
713 let current_pos = gesture.current_view_offset - gesture.delta_from_tracker;
714 gesture.delta_from_tracker = new_view_offset - current_pos;
715 let offset_delta = new_view_offset - gesture.current_view_offset;
716 gesture.current_view_offset = new_view_offset;
717
718 gesture.animate_from(-offset_delta, self.clock.clone(), config);
719 }
720 _ => {
721 // FIXME: also compute and use current velocity.
722 self.view_offset = ViewOffset::Animation(Animation::new(
723 self.clock.clone(),
724 self.view_offset.current(),
725 new_view_offset,
726 0.,
727 config,
728 ));
729 }
730 }
731 }
732
733 fn animate_view_offset_to_column_centered(
734 &mut self,
735 target_x: Option<f64>,
736 idx: usize,
737 config: niri_config::Animation,
738 ) {
739 let new_view_offset = self.compute_new_view_offset_for_column_centered(target_x, idx);
740 self.animate_view_offset_with_config(idx, new_view_offset, config);
741 }
742
743 fn animate_view_offset_to_column_with_config(
744 &mut self,
745 target_x: Option<f64>,
746 idx: usize,
747 prev_idx: Option<usize>,
748 config: niri_config::Animation,
749 ) {
750 let new_view_offset = self.compute_new_view_offset_for_column(target_x, idx, prev_idx);
751 self.animate_view_offset_with_config(idx, new_view_offset, config);
752 }
753
754 fn animate_view_offset_to_column(
755 &mut self,
756 target_x: Option<f64>,
757 idx: usize,
758 prev_idx: Option<usize>,
759 ) {
760 self.animate_view_offset_to_column_with_config(
761 target_x,
762 idx,
763 prev_idx,
764 self.options.animations.horizontal_view_movement.0,
765 )
766 }
767
768 fn activate_column(&mut self, idx: usize) {
769 self.activate_column_with_anim_config(
770 idx,
771 self.options.animations.horizontal_view_movement.0,
772 );
773 }
774
775 fn activate_column_with_anim_config(&mut self, idx: usize, config: niri_config::Animation) {
776 if self.active_column_idx == idx
777 // During a DnD scroll, animate even when activating the same window, for DnD hold.
778 && (self.columns.is_empty() || !self.view_offset.is_dnd_scroll())
779 {
780 return;
781 }
782
783 self.animate_view_offset_to_column_with_config(
784 None,
785 idx,
786 Some(self.active_column_idx),
787 config,
788 );
789
790 if self.active_column_idx != idx {
791 self.active_column_idx = idx;
792
793 // A different column was activated; reset the flag.
794 self.activate_prev_column_on_removal = None;
795 self.view_offset_to_restore = None;
796 self.interactive_resize = None;
797 }
798 }
799
800 pub(super) fn insert_position(&self, pos: Point<f64, Logical>) -> InsertPosition {
801 if self.columns.is_empty() {
802 return InsertPosition::NewColumn(0);
803 }
804
805 let x = pos.x + self.view_pos();
806
807 // Aim for the center of the gap.
808 let x = x + self.options.layout.gaps / 2.;
809 let y = pos.y + self.options.layout.gaps / 2.;
810
811 // Insert position is before the first column.
812 if x < 0. {
813 return InsertPosition::NewColumn(0);
814 }
815
816 // Find the closest gap between columns.
817 let (closest_col_idx, col_x) = self
818 .column_xs(self.data.iter().copied())
819 .enumerate()
820 .min_by_key(|(_, col_x)| NotNan::new((col_x - x).abs()).unwrap())
821 .unwrap();
822
823 // Find the column containing the position.
824 let (col_idx, _) = self
825 .column_xs(self.data.iter().copied())
826 .enumerate()
827 .take_while(|(_, col_x)| *col_x <= x)
828 .last()
829 .unwrap_or((0, 0.));
830
831 // Insert position is past the last column.
832 if col_idx == self.columns.len() {
833 return InsertPosition::NewColumn(closest_col_idx);
834 }
835
836 // Find the closest gap between tiles.
837 let col = &self.columns[col_idx];
838
839 let (closest_tile_idx, tile_y) = if col.display_mode == ColumnDisplay::Tabbed {
840 // In tabbed mode, there's only one tile visible, and we want to check its top and
841 // bottom.
842 let top = col.tile_offsets().nth(col.active_tile_idx).unwrap().y;
843 let bottom = top + col.data[col.active_tile_idx].size.h;
844 if (top - y).abs() <= (bottom - y).abs() {
845 (col.active_tile_idx, top)
846 } else {
847 (col.active_tile_idx + 1, bottom)
848 }
849 } else {
850 col.tile_offsets()
851 .map(|tile_off| tile_off.y)
852 .enumerate()
853 .min_by_key(|(_, tile_y)| NotNan::new((tile_y - y).abs()).unwrap())
854 .unwrap()
855 };
856
857 // Return the closest among the vertical and the horizontal gap.
858 let vert_dist = (col_x - x).abs();
859 let hor_dist = (tile_y - y).abs();
860 if vert_dist <= hor_dist {
861 InsertPosition::NewColumn(closest_col_idx)
862 } else {
863 InsertPosition::InColumn(col_idx, closest_tile_idx)
864 }
865 }
866
867 pub fn add_tile(
868 &mut self,
869 col_idx: Option<usize>,
870 tile: Tile<W>,
871 activate: bool,
872 width: ColumnWidth,
873 is_full_width: bool,
874 anim_config: Option<niri_config::Animation>,
875 ) {
876 let column = Column::new_with_tile(
877 tile,
878 self.view_size,
879 self.working_area,
880 self.parent_area,
881 self.scale,
882 width,
883 is_full_width,
884 );
885
886 self.add_column(col_idx, column, activate, anim_config);
887 }
888
889 pub fn add_tile_to_column(
890 &mut self,
891 col_idx: usize,
892 tile_idx: Option<usize>,
893 tile: Tile<W>,
894 activate: bool,
895 ) {
896 let prev_next_x = self.column_x(col_idx + 1);
897
898 let target_column = &mut self.columns[col_idx];
899 let tile_idx = tile_idx.unwrap_or(target_column.tiles.len());
900 let mut prev_active_tile_idx = target_column.active_tile_idx;
901
902 target_column.add_tile_at(tile_idx, tile);
903 self.data[col_idx].update(target_column);
904
905 if tile_idx <= prev_active_tile_idx {
906 target_column.active_tile_idx += 1;
907 prev_active_tile_idx += 1;
908 }
909
910 if activate {
911 target_column.activate_idx(tile_idx);
912 if self.active_column_idx != col_idx {
913 self.activate_column(col_idx);
914 }
915 }
916
917 let target_column = &mut self.columns[col_idx];
918 if target_column.display_mode == ColumnDisplay::Tabbed {
919 if target_column.active_tile_idx == tile_idx {
920 // Fade out the previously active tile.
921 let tile = &mut target_column.tiles[prev_active_tile_idx];
922 tile.animate_alpha(1., 0., self.options.animations.window_movement.0);
923 } else {
924 // Fade out when adding into a tabbed column into the background.
925 let tile = &mut target_column.tiles[tile_idx];
926 tile.animate_alpha(1., 0., self.options.animations.window_movement.0);
927 }
928 }
929
930 // Adding a wider window into a column increases its width now (even if the window will
931 // shrink later). Move the columns to account for this.
932 let offset = self.column_x(col_idx + 1) - prev_next_x;
933 if self.active_column_idx <= col_idx {
934 for col in &mut self.columns[col_idx + 1..] {
935 col.animate_move_from(-offset);
936 }
937 } else {
938 for col in &mut self.columns[..=col_idx] {
939 col.animate_move_from(offset);
940 }
941 }
942 }
943
944 pub fn add_tile_right_of(
945 &mut self,
946 right_of: &W::Id,
947 tile: Tile<W>,
948 activate: bool,
949 width: ColumnWidth,
950 is_full_width: bool,
951 ) {
952 let right_of_idx = self
953 .columns
954 .iter()
955 .position(|col| col.contains(right_of))
956 .unwrap();
957 let col_idx = right_of_idx + 1;
958
959 self.add_tile(Some(col_idx), tile, activate, width, is_full_width, None);
960 }
961
962 pub fn add_column(
963 &mut self,
964 idx: Option<usize>,
965 mut column: Column<W>,
966 activate: bool,
967 anim_config: Option<niri_config::Animation>,
968 ) {
969 let was_empty = self.columns.is_empty();
970
971 let idx = idx.unwrap_or_else(|| {
972 if was_empty {
973 0
974 } else {
975 self.active_column_idx + 1
976 }
977 });
978
979 column.update_config(
980 self.view_size,
981 self.working_area,
982 self.parent_area,
983 self.scale,
984 self.options.clone(),
985 );
986 self.data.insert(idx, ColumnData::new(&column));
987 self.columns.insert(idx, column);
988
989 if activate {
990 // If this is the first window on an empty workspace, remove the effect of whatever
991 // view_offset was left over and skip the animation.
992 if was_empty {
993 self.view_offset = ViewOffset::Static(0.);
994 self.view_offset =
995 ViewOffset::Static(self.compute_new_view_offset_for_column(None, idx, None));
996 }
997
998 let prev_offset = (!was_empty && idx == self.active_column_idx + 1)
999 .then(|| self.view_offset.stationary());
1000
1001 let anim_config =
1002 anim_config.unwrap_or(self.options.animations.horizontal_view_movement.0);
1003 self.activate_column_with_anim_config(idx, anim_config);
1004 self.activate_prev_column_on_removal = prev_offset;
1005 } else if !was_empty && idx <= self.active_column_idx {
1006 self.active_column_idx += 1;
1007 }
1008
1009 // Animate movement of other columns.
1010 let offset = self.column_x(idx + 1) - self.column_x(idx);
1011 let config = anim_config.unwrap_or(self.options.animations.window_movement.0);
1012 if self.active_column_idx <= idx {
1013 for col in &mut self.columns[idx + 1..] {
1014 col.animate_move_from_with_config(-offset, config);
1015 }
1016 } else {
1017 for col in &mut self.columns[..idx] {
1018 col.animate_move_from_with_config(offset, config);
1019 }
1020 }
1021 }
1022
1023 pub fn remove_active_tile(&mut self, transaction: Transaction) -> Option<RemovedTile<W>> {
1024 if self.columns.is_empty() {
1025 return None;
1026 }
1027
1028 let column = &self.columns[self.active_column_idx];
1029 Some(self.remove_tile_by_idx(
1030 self.active_column_idx,
1031 column.active_tile_idx,
1032 transaction,
1033 None,
1034 ))
1035 }
1036
1037 pub fn remove_tile(&mut self, window: &W::Id, transaction: Transaction) -> RemovedTile<W> {
1038 let column_idx = self
1039 .columns
1040 .iter()
1041 .position(|col| col.contains(window))
1042 .unwrap();
1043 let column = &self.columns[column_idx];
1044
1045 let tile_idx = column.position(window).unwrap();
1046 self.remove_tile_by_idx(column_idx, tile_idx, transaction, None)
1047 }
1048
1049 pub fn remove_tile_by_idx(
1050 &mut self,
1051 column_idx: usize,
1052 tile_idx: usize,
1053 transaction: Transaction,
1054 anim_config: Option<niri_config::Animation>,
1055 ) -> RemovedTile<W> {
1056 // If this is the only tile in the column, remove the whole column.
1057 if self.columns[column_idx].tiles.len() == 1 {
1058 let mut column = self.remove_column_by_idx(column_idx, anim_config);
1059 return RemovedTile {
1060 tile: column.tiles.remove(tile_idx),
1061 width: column.width,
1062 is_full_width: column.is_full_width,
1063 is_floating: false,
1064 };
1065 }
1066
1067 let column = &mut self.columns[column_idx];
1068 let prev_width = self.data[column_idx].width;
1069
1070 let movement_config = anim_config.unwrap_or(self.options.animations.window_movement.0);
1071
1072 // Animate movement of other tiles.
1073 // FIXME: tiles can move by X too, in a centered or resizing layout with one window smaller
1074 // than the others.
1075 let offset_y = column.tile_offset(tile_idx + 1).y - column.tile_offset(tile_idx).y;
1076 for tile in &mut column.tiles[tile_idx + 1..] {
1077 tile.animate_move_y_from(offset_y);
1078 }
1079
1080 if column.display_mode == ColumnDisplay::Tabbed && tile_idx != column.active_tile_idx {
1081 // Fade in when removing background tab from a tabbed column.
1082 let tile = &mut column.tiles[tile_idx];
1083 tile.animate_alpha(0., 1., movement_config);
1084 }
1085
1086 let was_normal = column.sizing_mode().is_normal();
1087
1088 let tile = column.tiles.remove(tile_idx);
1089 column.data.remove(tile_idx);
1090
1091 // If an active column became non-fullscreen after removing the tile, clear the stored
1092 // unfullscreen offset.
1093 if column_idx == self.active_column_idx && !was_normal && column.sizing_mode().is_normal() {
1094 self.view_offset_to_restore = None;
1095 }
1096
1097 // If one window is left, reset its weight to 1.
1098 if column.data.len() == 1 {
1099 if let WindowHeight::Auto { weight } = &mut column.data[0].height {
1100 *weight = 1.;
1101 }
1102 }
1103
1104 // Stop interactive resize.
1105 if let Some(resize) = &self.interactive_resize {
1106 if tile.window().id() == &resize.window {
1107 self.interactive_resize = None;
1108 }
1109 }
1110
1111 let tile = RemovedTile {
1112 tile,
1113 width: column.width,
1114 is_full_width: column.is_full_width,
1115 is_floating: false,
1116 };
1117
1118 #[allow(clippy::comparison_chain)] // What do you even want here?
1119 if tile_idx < column.active_tile_idx {
1120 // A tile above was removed; preserve the current position.
1121 column.active_tile_idx -= 1;
1122 } else if tile_idx == column.active_tile_idx {
1123 // The active tile was removed, so the active tile index shifted to the next tile.
1124 if tile_idx == column.tiles.len() {
1125 // The bottom tile was removed and it was active, update active idx to remain valid.
1126 column.activate_idx(tile_idx - 1);
1127 } else {
1128 // Ensure the newly active tile animates to opaque.
1129 column.tiles[tile_idx].ensure_alpha_animates_to_1();
1130 }
1131 }
1132
1133 column.update_tile_sizes_with_transaction(true, transaction);
1134 self.data[column_idx].update(column);
1135 let offset = prev_width - column.width();
1136
1137 // Animate movement of the other columns.
1138 if self.active_column_idx <= column_idx {
1139 for col in &mut self.columns[column_idx + 1..] {
1140 col.animate_move_from_with_config(offset, movement_config);
1141 }
1142 } else {
1143 for col in &mut self.columns[..=column_idx] {
1144 col.animate_move_from_with_config(-offset, movement_config);
1145 }
1146 }
1147
1148 tile
1149 }
1150
1151 pub fn remove_active_column(&mut self) -> Option<Column<W>> {
1152 if self.columns.is_empty() {
1153 return None;
1154 }
1155
1156 Some(self.remove_column_by_idx(self.active_column_idx, None))
1157 }
1158
1159 pub fn remove_column_by_idx(
1160 &mut self,
1161 column_idx: usize,
1162 anim_config: Option<niri_config::Animation>,
1163 ) -> Column<W> {
1164 // Animate movement of the other columns.
1165 let movement_config = anim_config.unwrap_or(self.options.animations.window_movement.0);
1166 let offset = self.column_x(column_idx + 1) - self.column_x(column_idx);
1167 if self.active_column_idx <= column_idx {
1168 for col in &mut self.columns[column_idx + 1..] {
1169 col.animate_move_from_with_config(offset, movement_config);
1170 }
1171 } else {
1172 for col in &mut self.columns[..column_idx] {
1173 col.animate_move_from_with_config(-offset, movement_config);
1174 }
1175 }
1176
1177 let column = self.columns.remove(column_idx);
1178 self.data.remove(column_idx);
1179
1180 // Stop interactive resize.
1181 if let Some(resize) = &self.interactive_resize {
1182 if column
1183 .tiles
1184 .iter()
1185 .any(|tile| tile.window().id() == &resize.window)
1186 {
1187 self.interactive_resize = None;
1188 }
1189 }
1190
1191 if column_idx + 1 == self.active_column_idx {
1192 // The previous column, that we were going to activate upon removal of the active
1193 // column, has just been itself removed.
1194 self.activate_prev_column_on_removal = None;
1195 }
1196
1197 if column_idx == self.active_column_idx {
1198 self.view_offset_to_restore = None;
1199 }
1200
1201 if self.columns.is_empty() {
1202 return column;
1203 }
1204
1205 let view_config = anim_config.unwrap_or(self.options.animations.horizontal_view_movement.0);
1206
1207 if column_idx < self.active_column_idx {
1208 // A column to the left was removed; preserve the current position.
1209 // FIXME: preserve activate_prev_column_on_removal.
1210 self.active_column_idx -= 1;
1211 self.activate_prev_column_on_removal = None;
1212 } else if column_idx == self.active_column_idx
1213 && self.activate_prev_column_on_removal.is_some()
1214 {
1215 // The active column was removed, and we needed to activate the previous column.
1216 if 0 < column_idx {
1217 let prev_offset = self.activate_prev_column_on_removal.unwrap();
1218
1219 self.activate_column_with_anim_config(self.active_column_idx - 1, view_config);
1220
1221 // Restore the view offset but make sure to scroll the view in case the
1222 // previous window had resized.
1223 self.animate_view_offset_with_config(
1224 self.active_column_idx,
1225 prev_offset,
1226 view_config,
1227 );
1228 self.animate_view_offset_to_column_with_config(
1229 None,
1230 self.active_column_idx,
1231 None,
1232 view_config,
1233 );
1234 }
1235 } else {
1236 self.activate_column_with_anim_config(
1237 min(self.active_column_idx, self.columns.len() - 1),
1238 view_config,
1239 );
1240 }
1241
1242 column
1243 }
1244
1245 pub fn update_window(&mut self, window: &W::Id, serial: Option<Serial>) {
1246 let (col_idx, column) = self
1247 .columns
1248 .iter_mut()
1249 .enumerate()
1250 .find(|(_, col)| col.contains(window))
1251 .unwrap();
1252 let was_normal = column.sizing_mode().is_normal();
1253 let prev_origin = column.tiles_origin();
1254
1255 let (tile_idx, tile) = column
1256 .tiles
1257 .iter_mut()
1258 .enumerate()
1259 .find(|(_, tile)| tile.window().id() == window)
1260 .unwrap();
1261
1262 let resize = tile.window_mut().interactive_resize_data();
1263
1264 // Do this before calling update_window() so it can get up-to-date info.
1265 if let Some(serial) = serial {
1266 tile.window_mut().on_commit(serial);
1267 }
1268
1269 let prev_width = self.data[col_idx].width;
1270
1271 column.update_window(window);
1272 self.data[col_idx].update(column);
1273 column.update_tile_sizes(false);
1274
1275 let offset = prev_width - self.data[col_idx].width;
1276
1277 // Move other columns in tandem with resizing.
1278 let ongoing_resize_anim = column.tiles[tile_idx].resize_animation().is_some();
1279 if offset != 0. {
1280 if self.active_column_idx <= col_idx {
1281 for col in &mut self.columns[col_idx + 1..] {
1282 // If there's a resize animation on the tile (that may have just started in
1283 // column.update_window()), then the apparent size change is smooth with no
1284 // sudden jumps. This corresponds to adding an X animation to adjacent columns.
1285 //
1286 // There could also be no resize animation with nonzero offset. This could
1287 // happen for example:
1288 // - if the window resized on its own, which we don't animate
1289 // - if the window resized by less than 10 px (the resize threshold)
1290 //
1291 // The latter case could also cancel an ongoing resize animation.
1292 //
1293 // Now, stationary columns shouldn't react to this offset change in any way,
1294 // i.e. their apparent X position should jump together with the resize.
1295 // However, adjacent columns that are already animating an X movement should
1296 // offset their animations to avoid the jump.
1297 //
1298 // Notably, this is necessary to fix the animation jump when resizing width back
1299 // and forth in quick succession (in a way that cancels the resize animation).
1300 if ongoing_resize_anim {
1301 col.animate_move_from_with_config(
1302 offset,
1303 self.options.animations.window_resize.anim,
1304 );
1305 } else {
1306 col.offset_move_anim_current(offset);
1307 }
1308 }
1309 } else {
1310 for col in &mut self.columns[..=col_idx] {
1311 if ongoing_resize_anim {
1312 col.animate_move_from_with_config(
1313 -offset,
1314 self.options.animations.window_resize.anim,
1315 );
1316 } else {
1317 col.offset_move_anim_current(-offset);
1318 }
1319 }
1320 }
1321 }
1322
1323 // When a column goes between fullscreen and non-fullscreen, the tiles origin can change.
1324 // The change comes from things like ignoring struts and hiding the tab indicator in
1325 // fullscreen, so both in X and Y directions.
1326 let column = &mut self.columns[col_idx];
1327 let new_origin = column.tiles_origin();
1328 let origin_delta = prev_origin - new_origin;
1329 if origin_delta != Point::new(0., 0.) {
1330 for (tile, _pos) in column.tiles_mut() {
1331 tile.animate_move_from(origin_delta);
1332 }
1333 }
1334
1335 if col_idx == self.active_column_idx {
1336 // If offset == 0, then don't mess with the view or the gesture. Some clients (Firefox,
1337 // Chromium, Electron) currently don't commit after the ack of a configure that drops
1338 // the Resizing state, which can trigger this code path for a while.
1339 let resize = if offset != 0. { resize } else { None };
1340 if let Some(resize) = resize {
1341 // Don't bother with the gesture.
1342 self.view_offset.cancel_gesture();
1343
1344 // If this is an interactive resize commit of an active window, then we need to
1345 // either preserve the view offset or adjust it accordingly.
1346 let centered = self.is_centering_focused_column();
1347
1348 let width = self.data[col_idx].width;
1349 let offset = if centered {
1350 // FIXME: when view_offset becomes fractional, this can be made additive too.
1351 let new_offset =
1352 -(self.working_area.size.w - width) / 2. - self.working_area.loc.x;
1353 new_offset - self.view_offset.target()
1354 } else if resize.edges.contains(ResizeEdge::LEFT) {
1355 -offset
1356 } else {
1357 0.
1358 };
1359
1360 self.view_offset.offset(offset);
1361 }
1362
1363 // When the active column goes fullscreen, store the view offset to restore later.
1364 let is_normal = self.columns[col_idx].sizing_mode().is_normal();
1365 if was_normal && !is_normal {
1366 self.view_offset_to_restore = Some(self.view_offset.stationary());
1367 }
1368
1369 // Upon unfullscreening, restore the view offset.
1370 //
1371 // In tabbed display mode, there can be multiple tiles in a fullscreen column. They
1372 // will unfullscreen one by one, and the column width will shrink only when the
1373 // last tile unfullscreens. This is when we want to restore the view offset,
1374 // otherwise it will immediately reset back by the animate_view_offset below.
1375 let unfullscreen_offset = if !was_normal && is_normal {
1376 // Take the value unconditionally, even if the view is currently frozen by
1377 // a view gesture. It shouldn't linger around because it's only valid for this
1378 // particular unfullscreen.
1379 self.view_offset_to_restore.take()
1380 } else {
1381 None
1382 };
1383
1384 // We might need to move the view to ensure the resized window is still visible. But
1385 // only do it when the view isn't frozen by an interactive resize or a view gesture.
1386 if self.interactive_resize.is_none() && !self.view_offset.is_gesture() {
1387 // Restore the view offset upon unfullscreening if needed.
1388 if let Some(prev_offset) = unfullscreen_offset {
1389 self.animate_view_offset(col_idx, prev_offset);
1390 }
1391
1392 // Synchronize the horizontal view movement with the resize so that it looks nice.
1393 // This is especially important for always-centered view.
1394 let config = if ongoing_resize_anim {
1395 self.options.animations.window_resize.anim
1396 } else {
1397 self.options.animations.horizontal_view_movement.0
1398 };
1399
1400 // FIXME: we will want to skip the animation in some cases here to make continuously
1401 // resizing windows not look janky.
1402 self.animate_view_offset_to_column_with_config(None, col_idx, None, config);
1403 }
1404 }
1405 }
1406
1407 pub fn scroll_amount_to_activate(&self, window: &W::Id) -> f64 {
1408 let column_idx = self
1409 .columns
1410 .iter()
1411 .position(|col| col.contains(window))
1412 .unwrap();
1413
1414 if self.active_column_idx == column_idx {
1415 return 0.;
1416 }
1417
1418 // Consider the end of an ongoing animation because that's what compute to fit does too.
1419 let target_x = self.target_view_pos();
1420 let new_view_offset = self.compute_new_view_offset_for_column(
1421 Some(target_x),
1422 column_idx,
1423 Some(self.active_column_idx),
1424 );
1425
1426 let new_col_x = self.column_x(column_idx);
1427 let from_view_offset = target_x - new_col_x;
1428
1429 (from_view_offset - new_view_offset).abs() / self.working_area.size.w
1430 }
1431
1432 pub fn activate_window(&mut self, window: &W::Id) -> bool {
1433 let column_idx = self.columns.iter().position(|col| col.contains(window));
1434 let Some(column_idx) = column_idx else {
1435 return false;
1436 };
1437 let column = &mut self.columns[column_idx];
1438
1439 column.activate_window(window);
1440 self.activate_column(column_idx);
1441
1442 true
1443 }
1444
1445 pub fn start_close_animation_for_window(
1446 &mut self,
1447 renderer: &mut GlesRenderer,
1448 window: &W::Id,
1449 blocker: TransactionBlocker,
1450 ) {
1451 let (tile, mut tile_pos) = self
1452 .tiles_with_render_positions_mut(false)
1453 .find(|(tile, _)| tile.window().id() == window)
1454 .unwrap();
1455
1456 let Some(snapshot) = tile.take_unmap_snapshot() else {
1457 return;
1458 };
1459
1460 let tile_size = tile.tile_size();
1461
1462 let (col_idx, tile_idx) = self
1463 .columns
1464 .iter()
1465 .enumerate()
1466 .find_map(|(col_idx, col)| {
1467 col.tiles
1468 .iter()
1469 .position(|tile| tile.window().id() == window)
1470 .map(move |tile_idx| (col_idx, tile_idx))
1471 })
1472 .unwrap();
1473
1474 let col = &self.columns[col_idx];
1475 let removing_last = col.tiles.len() == 1;
1476
1477 // Skip closing animation for invisible tiles in a tabbed column.
1478 if col.display_mode == ColumnDisplay::Tabbed && tile_idx != col.active_tile_idx {
1479 return;
1480 }
1481
1482 tile_pos.x += self.view_pos();
1483
1484 if col_idx < self.active_column_idx {
1485 let offset = if removing_last {
1486 self.column_x(col_idx + 1) - self.column_x(col_idx)
1487 } else {
1488 self.data[col_idx].width
1489 - col
1490 .data
1491 .iter()
1492 .enumerate()
1493 .filter_map(|(idx, data)| {
1494 (idx != tile_idx).then_some(NotNan::new(data.size.w).unwrap())
1495 })
1496 .max()
1497 .map(NotNan::into_inner)
1498 .unwrap()
1499 };
1500 tile_pos.x -= offset;
1501 }
1502
1503 self.start_close_animation_for_tile(renderer, snapshot, tile_size, tile_pos, blocker);
1504 }
1505
1506 fn start_close_animation_for_tile(
1507 &mut self,
1508 renderer: &mut GlesRenderer,
1509 snapshot: TileRenderSnapshot,
1510 tile_size: Size<f64, Logical>,
1511 tile_pos: Point<f64, Logical>,
1512 blocker: TransactionBlocker,
1513 ) {
1514 let anim = Animation::new(
1515 self.clock.clone(),
1516 0.,
1517 1.,
1518 0.,
1519 self.options.animations.window_close.anim,
1520 );
1521
1522 let blocker = if self.options.disable_transactions {
1523 TransactionBlocker::completed()
1524 } else {
1525 blocker
1526 };
1527
1528 let scale = Scale::from(self.scale);
1529 let res = ClosingWindow::new(
1530 renderer, snapshot, scale, tile_size, tile_pos, blocker, anim,
1531 );
1532 match res {
1533 Ok(closing) => {
1534 self.closing_windows.push(closing);
1535 }
1536 Err(err) => {
1537 warn!("error creating a closing window animation: {err:?}");
1538 }
1539 }
1540 }
1541
1542 pub fn start_open_animation(&mut self, id: &W::Id) -> bool {
1543 self.columns
1544 .iter_mut()
1545 .any(|col| col.start_open_animation(id))
1546 }
1547
1548 pub fn focus_left(&mut self) -> bool {
1549 if self.active_column_idx == 0 {
1550 return false;
1551 }
1552 self.activate_column(self.active_column_idx - 1);
1553 true
1554 }
1555
1556 pub fn focus_right(&mut self) -> bool {
1557 if self.active_column_idx + 1 >= self.columns.len() {
1558 return false;
1559 }
1560
1561 self.activate_column(self.active_column_idx + 1);
1562 true
1563 }
1564
1565 pub fn focus_column_first(&mut self) {
1566 self.activate_column(0);
1567 }
1568
1569 pub fn focus_column_last(&mut self) {
1570 if self.columns.is_empty() {
1571 return;
1572 }
1573
1574 self.activate_column(self.columns.len() - 1);
1575 }
1576
1577 pub fn focus_column(&mut self, index: usize) {
1578 if self.columns.is_empty() {
1579 return;
1580 }
1581
1582 self.activate_column(index.saturating_sub(1).min(self.columns.len() - 1));
1583 }
1584
1585 pub fn focus_window_in_column(&mut self, index: u8) {
1586 if self.columns.is_empty() {
1587 return;
1588 }
1589
1590 self.columns[self.active_column_idx].focus_index(index);
1591 }
1592
1593 pub fn focus_down(&mut self) -> bool {
1594 if self.columns.is_empty() {
1595 return false;
1596 }
1597
1598 self.columns[self.active_column_idx].focus_down()
1599 }
1600
1601 pub fn focus_up(&mut self) -> bool {
1602 if self.columns.is_empty() {
1603 return false;
1604 }
1605
1606 self.columns[self.active_column_idx].focus_up()
1607 }
1608
1609 pub fn focus_down_or_left(&mut self) {
1610 if self.columns.is_empty() {
1611 return;
1612 }
1613
1614 let column = &mut self.columns[self.active_column_idx];
1615 if !column.focus_down() {
1616 self.focus_left();
1617 }
1618 }
1619
1620 pub fn focus_down_or_right(&mut self) {
1621 if self.columns.is_empty() {
1622 return;
1623 }
1624
1625 let column = &mut self.columns[self.active_column_idx];
1626 if !column.focus_down() {
1627 self.focus_right();
1628 }
1629 }
1630
1631 pub fn focus_up_or_left(&mut self) {
1632 if self.columns.is_empty() {
1633 return;
1634 }
1635
1636 let column = &mut self.columns[self.active_column_idx];
1637 if !column.focus_up() {
1638 self.focus_left();
1639 }
1640 }
1641
1642 pub fn focus_up_or_right(&mut self) {
1643 if self.columns.is_empty() {
1644 return;
1645 }
1646
1647 let column = &mut self.columns[self.active_column_idx];
1648 if !column.focus_up() {
1649 self.focus_right();
1650 }
1651 }
1652
1653 pub fn focus_top(&mut self) {
1654 if self.columns.is_empty() {
1655 return;
1656 }
1657
1658 self.columns[self.active_column_idx].focus_top()
1659 }
1660
1661 pub fn focus_bottom(&mut self) {
1662 if self.columns.is_empty() {
1663 return;
1664 }
1665
1666 self.columns[self.active_column_idx].focus_bottom()
1667 }
1668
1669 pub fn move_column_to_index(&mut self, index: usize) {
1670 if self.columns.is_empty() {
1671 return;
1672 }
1673
1674 self.move_column_to(index.saturating_sub(1).min(self.columns.len() - 1));
1675 }
1676
1677 fn move_column_to(&mut self, new_idx: usize) {
1678 if self.active_column_idx == new_idx {
1679 return;
1680 }
1681
1682 let current_col_x = self.column_x(self.active_column_idx);
1683 let next_col_x = self.column_x(self.active_column_idx + 1);
1684
1685 let mut column = self.columns.remove(self.active_column_idx);
1686 let data = self.data.remove(self.active_column_idx);
1687 cancel_resize_for_column(&mut self.interactive_resize, &mut column);
1688 self.columns.insert(new_idx, column);
1689 self.data.insert(new_idx, data);
1690
1691 // Preserve the camera position when moving to the left.
1692 let view_offset_delta = -self.column_x(self.active_column_idx) + current_col_x;
1693 self.view_offset.offset(view_offset_delta);
1694
1695 // The column we just moved is offset by the difference between its new and old position.
1696 let new_col_x = self.column_x(new_idx);
1697 self.columns[new_idx].animate_move_from(current_col_x - new_col_x);
1698
1699 // All columns in between moved by the width of the column that we just moved.
1700 let others_x_offset = next_col_x - current_col_x;
1701 if self.active_column_idx < new_idx {
1702 for col in &mut self.columns[self.active_column_idx..new_idx] {
1703 col.animate_move_from(others_x_offset);
1704 }
1705 } else {
1706 for col in &mut self.columns[new_idx + 1..=self.active_column_idx] {
1707 col.animate_move_from(-others_x_offset);
1708 }
1709 }
1710
1711 self.activate_column_with_anim_config(new_idx, self.options.animations.window_movement.0);
1712 }
1713
1714 pub fn move_left(&mut self) -> bool {
1715 if self.active_column_idx == 0 {
1716 return false;
1717 }
1718
1719 self.move_column_to(self.active_column_idx - 1);
1720 true
1721 }
1722
1723 pub fn move_right(&mut self) -> bool {
1724 let new_idx = self.active_column_idx + 1;
1725 if new_idx >= self.columns.len() {
1726 return false;
1727 }
1728
1729 self.move_column_to(new_idx);
1730 true
1731 }
1732
1733 pub fn move_column_to_first(&mut self) {
1734 self.move_column_to(0);
1735 }
1736
1737 pub fn move_column_to_last(&mut self) {
1738 if self.columns.is_empty() {
1739 return;
1740 }
1741
1742 let new_idx = self.columns.len() - 1;
1743 self.move_column_to(new_idx);
1744 }
1745
1746 pub fn move_down(&mut self) -> bool {
1747 if self.columns.is_empty() {
1748 return false;
1749 }
1750
1751 self.columns[self.active_column_idx].move_down()
1752 }
1753
1754 pub fn move_up(&mut self) -> bool {
1755 if self.columns.is_empty() {
1756 return false;
1757 }
1758
1759 self.columns[self.active_column_idx].move_up()
1760 }
1761
1762 pub fn consume_or_expel_window_left(&mut self, window: Option<&W::Id>) {
1763 if self.columns.is_empty() {
1764 return;
1765 }
1766
1767 let (source_col_idx, source_tile_idx) = if let Some(window) = window {
1768 self.columns
1769 .iter_mut()
1770 .enumerate()
1771 .find_map(|(col_idx, col)| {
1772 col.tiles
1773 .iter()
1774 .position(|tile| tile.window().id() == window)
1775 .map(|tile_idx| (col_idx, tile_idx))
1776 })
1777 .unwrap()
1778 } else {
1779 let source_col_idx = self.active_column_idx;
1780 let source_tile_idx = self.columns[self.active_column_idx].active_tile_idx;
1781 (source_col_idx, source_tile_idx)
1782 };
1783
1784 let source_column = &self.columns[source_col_idx];
1785 let prev_off = source_column.tile_offset(source_tile_idx);
1786
1787 let source_tile_was_active = self.active_column_idx == source_col_idx
1788 && source_column.active_tile_idx == source_tile_idx;
1789
1790 if source_column.tiles.len() == 1 {
1791 if source_col_idx == 0 {
1792 return;
1793 }
1794
1795 // Move into adjacent column.
1796 let target_column_idx = source_col_idx - 1;
1797
1798 let offset = if self.active_column_idx <= source_col_idx {
1799 // Tiles to the right animate from the following column.
1800 self.column_x(source_col_idx) - self.column_x(target_column_idx)
1801 } else {
1802 // Tiles to the left animate to preserve their right edge position.
1803 f64::max(
1804 0.,
1805 self.data[target_column_idx].width - self.data[source_col_idx].width,
1806 )
1807 };
1808 let mut offset = Point::from((offset, 0.));
1809
1810 if source_tile_was_active {
1811 // Make sure the previous (target) column is activated so the animation looks right.
1812 //
1813 // However, if it was already going to be activated, leave the offset as is. This
1814 // improves the workflow that has become common with tabbed columns: open a new
1815 // window, then immediately consume it left as a new tab.
1816 self.activate_prev_column_on_removal
1817 .get_or_insert(self.view_offset.stationary() + offset.x);
1818 }
1819
1820 offset.x += self.columns[source_col_idx].render_offset().x;
1821 let RemovedTile { tile, .. } = self.remove_tile_by_idx(
1822 source_col_idx,
1823 0,
1824 Transaction::new(),
1825 Some(self.options.animations.window_movement.0),
1826 );
1827 self.add_tile_to_column(target_column_idx, None, tile, source_tile_was_active);
1828
1829 let target_column = &mut self.columns[target_column_idx];
1830 offset.x -= target_column.render_offset().x;
1831 offset += prev_off - target_column.tile_offset(target_column.tiles.len() - 1);
1832
1833 let new_tile = target_column.tiles.last_mut().unwrap();
1834 new_tile.animate_move_from(offset);
1835 } else {
1836 // Move out of column.
1837 let mut offset = Point::from((source_column.render_offset().x, 0.));
1838
1839 let removed =
1840 self.remove_tile_by_idx(source_col_idx, source_tile_idx, Transaction::new(), None);
1841
1842 // We're inserting into the source column position.
1843 let target_column_idx = source_col_idx;
1844
1845 self.add_tile(
1846 Some(target_column_idx),
1847 removed.tile,
1848 source_tile_was_active,
1849 removed.width,
1850 removed.is_full_width,
1851 Some(self.options.animations.window_movement.0),
1852 );
1853
1854 if source_tile_was_active {
1855 // We added to the left, don't activate even further left on removal.
1856 self.activate_prev_column_on_removal = None;
1857 }
1858
1859 if target_column_idx < self.active_column_idx {
1860 // Tiles to the left animate from the following column.
1861 offset.x += self.column_x(target_column_idx + 1) - self.column_x(target_column_idx);
1862 }
1863
1864 let new_col = &mut self.columns[target_column_idx];
1865 offset += prev_off - new_col.tile_offset(0);
1866 new_col.tiles[0].animate_move_from(offset);
1867 }
1868 }
1869
1870 pub fn consume_or_expel_window_right(&mut self, window: Option<&W::Id>) {
1871 if self.columns.is_empty() {
1872 return;
1873 }
1874
1875 let (source_col_idx, source_tile_idx) = if let Some(window) = window {
1876 self.columns
1877 .iter_mut()
1878 .enumerate()
1879 .find_map(|(col_idx, col)| {
1880 col.tiles
1881 .iter()
1882 .position(|tile| tile.window().id() == window)
1883 .map(|tile_idx| (col_idx, tile_idx))
1884 })
1885 .unwrap()
1886 } else {
1887 let source_col_idx = self.active_column_idx;
1888 let source_tile_idx = self.columns[self.active_column_idx].active_tile_idx;
1889 (source_col_idx, source_tile_idx)
1890 };
1891
1892 let cur_x = self.column_x(source_col_idx);
1893
1894 let source_column = &self.columns[source_col_idx];
1895 let mut offset = Point::from((source_column.render_offset().x, 0.));
1896 let prev_off = source_column.tile_offset(source_tile_idx);
1897
1898 let source_tile_was_active = self.active_column_idx == source_col_idx
1899 && source_column.active_tile_idx == source_tile_idx;
1900
1901 if source_column.tiles.len() == 1 {
1902 if source_col_idx + 1 == self.columns.len() {
1903 return;
1904 }
1905
1906 // Move into adjacent column.
1907 let target_column_idx = source_col_idx;
1908
1909 offset.x += cur_x - self.column_x(source_col_idx + 1);
1910 offset.x -= self.columns[source_col_idx + 1].render_offset().x;
1911
1912 if source_tile_was_active {
1913 // Make sure the target column gets activated.
1914 self.activate_prev_column_on_removal = None;
1915 }
1916
1917 let RemovedTile { tile, .. } = self.remove_tile_by_idx(
1918 source_col_idx,
1919 0,
1920 Transaction::new(),
1921 Some(self.options.animations.window_movement.0),
1922 );
1923 self.add_tile_to_column(target_column_idx, None, tile, source_tile_was_active);
1924
1925 let target_column = &mut self.columns[target_column_idx];
1926 offset += prev_off - target_column.tile_offset(target_column.tiles.len() - 1);
1927
1928 let new_tile = target_column.tiles.last_mut().unwrap();
1929 new_tile.animate_move_from(offset);
1930 } else {
1931 // Move out of column.
1932 let prev_width = self.data[source_col_idx].width;
1933
1934 let removed =
1935 self.remove_tile_by_idx(source_col_idx, source_tile_idx, Transaction::new(), None);
1936
1937 let target_column_idx = source_col_idx + 1;
1938
1939 self.add_tile(
1940 Some(target_column_idx),
1941 removed.tile,
1942 source_tile_was_active,
1943 removed.width,
1944 removed.is_full_width,
1945 Some(self.options.animations.window_movement.0),
1946 );
1947
1948 offset.x += if self.active_column_idx <= target_column_idx {
1949 // Tiles to the right animate to the following column.
1950 cur_x - self.column_x(target_column_idx)
1951 } else {
1952 // Tiles to the left animate for a change in width.
1953 -f64::max(0., prev_width - self.data[target_column_idx].width)
1954 };
1955
1956 let new_col = &mut self.columns[target_column_idx];
1957 offset += prev_off - new_col.tile_offset(0);
1958 new_col.tiles[0].animate_move_from(offset);
1959 }
1960 }
1961
1962 pub fn consume_into_column(&mut self) {
1963 if self.columns.len() < 2 {
1964 return;
1965 }
1966
1967 if self.active_column_idx == self.columns.len() - 1 {
1968 return;
1969 }
1970
1971 let target_column_idx = self.active_column_idx;
1972 let source_column_idx = self.active_column_idx + 1;
1973
1974 let offset = self.column_x(source_column_idx)
1975 + self.columns[source_column_idx].render_offset().x
1976 - self.column_x(target_column_idx);
1977 let mut offset = Point::from((offset, 0.));
1978 let prev_off = self.columns[source_column_idx].tile_offset(0);
1979
1980 let removed = self.remove_tile_by_idx(source_column_idx, 0, Transaction::new(), None);
1981 self.add_tile_to_column(target_column_idx, None, removed.tile, false);
1982
1983 let target_column = &mut self.columns[target_column_idx];
1984 offset += prev_off - target_column.tile_offset(target_column.tiles.len() - 1);
1985 offset.x -= target_column.render_offset().x;
1986
1987 let new_tile = target_column.tiles.last_mut().unwrap();
1988 new_tile.animate_move_from(offset);
1989 }
1990
1991 pub fn expel_from_column(&mut self) {
1992 if self.columns.is_empty() {
1993 return;
1994 }
1995
1996 let source_col_idx = self.active_column_idx;
1997 let target_col_idx = self.active_column_idx + 1;
1998 let cur_x = self.column_x(source_col_idx);
1999
2000 let source_column = &self.columns[self.active_column_idx];
2001 if source_column.tiles.len() == 1 {
2002 return;
2003 }
2004
2005 let source_tile_idx = source_column.tiles.len() - 1;
2006
2007 let mut offset = Point::from((source_column.render_offset().x, 0.));
2008 let prev_off = source_column.tile_offset(source_tile_idx);
2009
2010 let removed =
2011 self.remove_tile_by_idx(source_col_idx, source_tile_idx, Transaction::new(), None);
2012
2013 self.add_tile(
2014 Some(target_col_idx),
2015 removed.tile,
2016 false,
2017 removed.width,
2018 removed.is_full_width,
2019 Some(self.options.animations.window_movement.0),
2020 );
2021
2022 offset.x += cur_x - self.column_x(target_col_idx);
2023
2024 let new_col = &mut self.columns[target_col_idx];
2025 offset += prev_off - new_col.tile_offset(0);
2026 new_col.tiles[0].animate_move_from(offset);
2027 }
2028
2029 pub fn swap_window_in_direction(&mut self, direction: ScrollDirection) {
2030 if self.columns.is_empty() {
2031 return;
2032 }
2033
2034 // if this is the first (resp. last column), then this operation is equivalent
2035 // to an `consume_or_expel_window_left` (resp. `consume_or_expel_window_right`)
2036 match direction {
2037 ScrollDirection::Left => {
2038 if self.active_column_idx == 0 {
2039 return;
2040 }
2041 }
2042 ScrollDirection::Right => {
2043 if self.active_column_idx == self.columns.len() - 1 {
2044 return;
2045 }
2046 }
2047 }
2048
2049 let source_column_idx = self.active_column_idx;
2050 let target_column_idx = self.active_column_idx.wrapping_add_signed(match direction {
2051 ScrollDirection::Left => -1,
2052 ScrollDirection::Right => 1,
2053 });
2054
2055 // if both source and target columns contain a single tile, then the operation is equivalent
2056 // to a simple column move
2057 if self.columns[source_column_idx].tiles.len() == 1
2058 && self.columns[target_column_idx].tiles.len() == 1
2059 {
2060 return self.move_column_to(target_column_idx);
2061 }
2062
2063 let source_tile_idx = self.columns[source_column_idx].active_tile_idx;
2064 let target_tile_idx = self.columns[target_column_idx].active_tile_idx;
2065 let source_column_drained = self.columns[source_column_idx].tiles.len() == 1;
2066
2067 // capture the original positions of the tiles
2068 let (mut source_pt, mut target_pt) = (
2069 self.columns[source_column_idx].render_offset()
2070 + self.columns[source_column_idx].tile_offset(source_tile_idx),
2071 self.columns[target_column_idx].render_offset()
2072 + self.columns[target_column_idx].tile_offset(target_tile_idx),
2073 );
2074 source_pt.x += self.column_x(source_column_idx);
2075 target_pt.x += self.column_x(target_column_idx);
2076
2077 let transaction = Transaction::new();
2078
2079 // If the source column contains a single tile, this will also remove the column.
2080 // When this happens `source_column_drained` will be set and the column will need to be
2081 // recreated with `add_tile`
2082 let source_removed = self.remove_tile_by_idx(
2083 source_column_idx,
2084 source_tile_idx,
2085 transaction.clone(),
2086 None,
2087 );
2088
2089 {
2090 // special case when the source column disappears after removing its last tile
2091 let adjusted_target_column_idx =
2092 if direction == ScrollDirection::Right && source_column_drained {
2093 target_column_idx - 1
2094 } else {
2095 target_column_idx
2096 };
2097
2098 self.add_tile_to_column(
2099 adjusted_target_column_idx,
2100 Some(target_tile_idx),
2101 source_removed.tile,
2102 false,
2103 );
2104
2105 let RemovedTile {
2106 tile: target_tile, ..
2107 } = self.remove_tile_by_idx(
2108 adjusted_target_column_idx,
2109 target_tile_idx + 1,
2110 transaction.clone(),
2111 None,
2112 );
2113
2114 if source_column_drained {
2115 // recreate the drained column with only the target tile
2116 self.add_tile(
2117 Some(source_column_idx),
2118 target_tile,
2119 true,
2120 source_removed.width,
2121 source_removed.is_full_width,
2122 None,
2123 )
2124 } else {
2125 // simply add the removed target tile to the source column
2126 self.add_tile_to_column(
2127 source_column_idx,
2128 Some(source_tile_idx),
2129 target_tile,
2130 false,
2131 );
2132 }
2133 }
2134
2135 // update the active tile in the modified columns
2136 self.columns[source_column_idx].active_tile_idx = source_tile_idx;
2137 self.columns[target_column_idx].active_tile_idx = target_tile_idx;
2138
2139 // Animations
2140 self.columns[target_column_idx].tiles[target_tile_idx]
2141 .animate_move_from(source_pt - target_pt);
2142 self.columns[target_column_idx].tiles[target_tile_idx].ensure_alpha_animates_to_1();
2143
2144 // FIXME: this stop_move_animations() causes the target tile animation to "reset" when
2145 // swapping. It's here as a workaround to stop the unwanted animation of moving the source
2146 // tile down when adding the target tile above it. This code needs to be written in some
2147 // other way not to trigger that animation, or to cancel it properly, so that swap doesn't
2148 // cancel all ongoing target tile animations.
2149 self.columns[source_column_idx].tiles[source_tile_idx].stop_move_animations();
2150 self.columns[source_column_idx].tiles[source_tile_idx]
2151 .animate_move_from(target_pt - source_pt);
2152 self.columns[source_column_idx].tiles[source_tile_idx].ensure_alpha_animates_to_1();
2153
2154 self.activate_column(target_column_idx);
2155 }
2156
2157 pub fn toggle_column_tabbed_display(&mut self) {
2158 if self.columns.is_empty() {
2159 return;
2160 }
2161
2162 let col = &mut self.columns[self.active_column_idx];
2163 let display = match col.display_mode {
2164 ColumnDisplay::Normal => ColumnDisplay::Tabbed,
2165 ColumnDisplay::Tabbed => ColumnDisplay::Normal,
2166 };
2167
2168 self.set_column_display(display);
2169 }
2170
2171 pub fn set_column_display(&mut self, display: ColumnDisplay) {
2172 if self.columns.is_empty() {
2173 return;
2174 }
2175
2176 let col = &mut self.columns[self.active_column_idx];
2177 if col.display_mode == display {
2178 return;
2179 }
2180
2181 cancel_resize_for_column(&mut self.interactive_resize, col);
2182 col.set_column_display(display);
2183
2184 // With place_within_column, the tab indicator changes the column size immediately.
2185 self.data[self.active_column_idx].update(col);
2186 col.update_tile_sizes(true);
2187
2188 // Disable fullscreen if needed.
2189 if col.display_mode != ColumnDisplay::Tabbed && col.tiles.len() > 1 {
2190 let window = col.tiles[col.active_tile_idx].window().id().clone();
2191 self.set_fullscreen(&window, false);
2192 self.set_maximized(&window, false);
2193 }
2194 }
2195
2196 pub fn center_column(&mut self) {
2197 if self.columns.is_empty() {
2198 return;
2199 }
2200
2201 self.animate_view_offset_to_column_centered(
2202 None,
2203 self.active_column_idx,
2204 self.options.animations.horizontal_view_movement.0,
2205 );
2206
2207 let col = &mut self.columns[self.active_column_idx];
2208 cancel_resize_for_column(&mut self.interactive_resize, col);
2209 }
2210
2211 pub fn center_window(&mut self, window: Option<&W::Id>) {
2212 if self.columns.is_empty() {
2213 return;
2214 }
2215
2216 let col_idx = if let Some(window) = window {
2217 self.columns
2218 .iter()
2219 .position(|col| col.contains(window))
2220 .unwrap()
2221 } else {
2222 self.active_column_idx
2223 };
2224
2225 // We can reasonably center only the active column.
2226 if col_idx != self.active_column_idx {
2227 return;
2228 }
2229
2230 self.center_column();
2231 }
2232
2233 pub fn center_visible_columns(&mut self) {
2234 if self.columns.is_empty() {
2235 return;
2236 }
2237
2238 if self.is_centering_focused_column() {
2239 return;
2240 }
2241
2242 // Consider the end of an ongoing animation because that's what compute to fit does too.
2243 let view_x = self.target_view_pos();
2244 let working_x = self.working_area.loc.x;
2245 let working_w = self.working_area.size.w;
2246
2247 // Count all columns that are fully visible inside the working area.
2248 let mut width_taken = 0.;
2249 let mut leftmost_col_x = None;
2250 let mut active_col_x = None;
2251
2252 let gap = self.options.layout.gaps;
2253 let col_xs = self.column_xs(self.data.iter().copied());
2254 for (idx, col_x) in col_xs.take(self.columns.len()).enumerate() {
2255 if col_x < view_x + working_x + gap {
2256 // Column goes off-screen to the left.
2257 continue;
2258 }
2259
2260 leftmost_col_x.get_or_insert(col_x);
2261
2262 let width = self.data[idx].width;
2263 if view_x + working_x + working_w < col_x + width + gap {
2264 // Column goes off-screen to the right. We can stop here.
2265 break;
2266 }
2267
2268 if idx == self.active_column_idx {
2269 active_col_x = Some(col_x);
2270 }
2271
2272 width_taken += width + gap;
2273 }
2274
2275 if active_col_x.is_none() {
2276 // The active column wasn't fully on screen, so we can't meaningfully do anything.
2277 return;
2278 }
2279
2280 let col = &mut self.columns[self.active_column_idx];
2281 cancel_resize_for_column(&mut self.interactive_resize, col);
2282
2283 let free_space = working_w - width_taken + gap;
2284 let new_view_x = leftmost_col_x.unwrap() - free_space / 2. - working_x;
2285
2286 self.animate_view_offset(self.active_column_idx, new_view_x - active_col_x.unwrap());
2287 // Just in case.
2288 self.animate_view_offset_to_column(None, self.active_column_idx, None);
2289 }
2290
2291 pub fn view_pos(&self) -> f64 {
2292 self.column_x(self.active_column_idx) + self.view_offset.current()
2293 }
2294
2295 pub fn target_view_pos(&self) -> f64 {
2296 self.column_x(self.active_column_idx) + self.view_offset.target()
2297 }
2298
2299 // HACK: pass a self.data iterator in manually as a workaround for the lack of method partial
2300 // borrowing. Note that this method's return value does not borrow the entire &Self!
2301 fn column_xs(&self, data: impl Iterator<Item = ColumnData>) -> impl Iterator<Item = f64> {
2302 let gaps = self.options.layout.gaps;
2303 let mut x = 0.;
2304
2305 // Chain with a dummy value to be able to get one past all columns' X.
2306 let dummy = ColumnData { width: 0. };
2307 let data = data.chain(iter::once(dummy));
2308
2309 data.map(move |data| {
2310 let rv = x;
2311 x += data.width + gaps;
2312 rv
2313 })
2314 }
2315
2316 fn column_x(&self, column_idx: usize) -> f64 {
2317 self.column_xs(self.data.iter().copied())
2318 .nth(column_idx)
2319 .unwrap()
2320 }
2321
2322 fn column_xs_in_render_order(
2323 &self,
2324 data: impl Iterator<Item = ColumnData>,
2325 ) -> impl Iterator<Item = f64> {
2326 let active_idx = self.active_column_idx;
2327 let active_pos = self.column_x(active_idx);
2328 let offsets = self
2329 .column_xs(data)
2330 .enumerate()
2331 .filter_map(move |(idx, pos)| (idx != active_idx).then_some(pos));
2332 iter::once(active_pos).chain(offsets)
2333 }
2334
2335 pub fn columns(&self) -> impl Iterator<Item = &Column<W>> {
2336 self.columns.iter()
2337 }
2338
2339 fn columns_mut(&mut self) -> impl Iterator<Item = (&mut Column<W>, f64)> + '_ {
2340 let offsets = self.column_xs(self.data.iter().copied());
2341 zip(&mut self.columns, offsets)
2342 }
2343
2344 fn columns_in_render_order(&self) -> impl Iterator<Item = (&Column<W>, f64)> + '_ {
2345 let offsets = self.column_xs_in_render_order(self.data.iter().copied());
2346
2347 let (first, active, rest) = if self.columns.is_empty() {
2348 (&[][..], &[][..], &[][..])
2349 } else {
2350 let (first, rest) = self.columns.split_at(self.active_column_idx);
2351 let (active, rest) = rest.split_at(1);
2352 (first, active, rest)
2353 };
2354
2355 let columns = active.iter().chain(first).chain(rest);
2356 zip(columns, offsets)
2357 }
2358
2359 fn columns_in_render_order_mut(&mut self) -> impl Iterator<Item = (&mut Column<W>, f64)> + '_ {
2360 let offsets = self.column_xs_in_render_order(self.data.iter().copied());
2361
2362 let (first, active, rest) = if self.columns.is_empty() {
2363 (&mut [][..], &mut [][..], &mut [][..])
2364 } else {
2365 let (first, rest) = self.columns.split_at_mut(self.active_column_idx);
2366 let (active, rest) = rest.split_at_mut(1);
2367 (first, active, rest)
2368 };
2369
2370 let columns = active.iter_mut().chain(first).chain(rest);
2371 zip(columns, offsets)
2372 }
2373
2374 pub fn tiles_with_render_positions(
2375 &self,
2376 ) -> impl Iterator<Item = (&Tile<W>, Point<f64, Logical>, bool)> {
2377 let scale = self.scale;
2378 let view_off = Point::from((-self.view_pos(), 0.));
2379 self.columns_in_render_order()
2380 .flat_map(move |(col, col_x)| {
2381 let col_off = Point::from((col_x, 0.));
2382 let col_render_off = col.render_offset();
2383 col.tiles_in_render_order()
2384 .map(move |(tile, tile_off, visible)| {
2385 let pos =
2386 view_off + col_off + col_render_off + tile_off + tile.render_offset();
2387 // Round to physical pixels.
2388 let pos = pos.to_physical_precise_round(scale).to_logical(scale);
2389 (tile, pos, visible)
2390 })
2391 })
2392 }
2393
2394 pub fn tiles_with_render_positions_mut(
2395 &mut self,
2396 round: bool,
2397 ) -> impl Iterator<Item = (&mut Tile<W>, Point<f64, Logical>)> {
2398 let scale = self.scale;
2399 let view_off = Point::from((-self.view_pos(), 0.));
2400 self.columns_in_render_order_mut()
2401 .flat_map(move |(col, col_x)| {
2402 let col_off = Point::from((col_x, 0.));
2403 let col_render_off = col.render_offset();
2404 col.tiles_in_render_order_mut()
2405 .map(move |(tile, tile_off)| {
2406 let mut pos =
2407 view_off + col_off + col_render_off + tile_off + tile.render_offset();
2408 // Round to physical pixels.
2409 if round {
2410 pos = pos.to_physical_precise_round(scale).to_logical(scale);
2411 }
2412 (tile, pos)
2413 })
2414 })
2415 }
2416
2417 pub fn tiles_with_ipc_layouts(&self) -> impl Iterator<Item = (&Tile<W>, WindowLayout)> {
2418 self.columns
2419 .iter()
2420 .enumerate()
2421 .flat_map(move |(col_idx, col)| {
2422 col.tiles().enumerate().map(move |(tile_idx, (tile, _))| {
2423 let layout = WindowLayout {
2424 // Our indices are 1-based, consistent with the actions.
2425 pos_in_scrolling_layout: Some((col_idx + 1, tile_idx + 1)),
2426 ..tile.ipc_layout_template()
2427 };
2428 (tile, layout)
2429 })
2430 })
2431 }
2432
2433 pub(super) fn insert_hint_area(
2434 &self,
2435 position: InsertPosition,
2436 ) -> Option<Rectangle<f64, Logical>> {
2437 let mut hint_area = match position {
2438 InsertPosition::NewColumn(column_index) => {
2439 if column_index == 0 || column_index == self.columns.len() {
2440 let size = Size::from((
2441 300.,
2442 self.working_area.size.h - self.options.layout.gaps * 2.,
2443 ));
2444 let mut loc = Point::from((
2445 self.column_x(column_index),
2446 self.working_area.loc.y + self.options.layout.gaps,
2447 ));
2448 if column_index == 0 && !self.columns.is_empty() {
2449 loc.x -= size.w + self.options.layout.gaps;
2450 }
2451 Rectangle::new(loc, size)
2452 } else if column_index > self.columns.len() {
2453 error!("insert hint column index is out of range");
2454 return None;
2455 } else {
2456 let size = Size::from((
2457 300.,
2458 self.working_area.size.h - self.options.layout.gaps * 2.,
2459 ));
2460 let loc = Point::from((
2461 self.column_x(column_index) - size.w / 2. - self.options.layout.gaps / 2.,
2462 self.working_area.loc.y + self.options.layout.gaps,
2463 ));
2464 Rectangle::new(loc, size)
2465 }
2466 }
2467 InsertPosition::InColumn(column_index, tile_index) => {
2468 if column_index > self.columns.len() {
2469 error!("insert hint column index is out of range");
2470 return None;
2471 }
2472
2473 let col = &self.columns[column_index];
2474 if tile_index > col.tiles.len() {
2475 error!("insert hint tile index is out of range");
2476 return None;
2477 }
2478
2479 let is_tabbed = col.display_mode == ColumnDisplay::Tabbed;
2480
2481 let (height, y) = if is_tabbed {
2482 // In tabbed mode, there's only one tile visible, and we want to draw the hint
2483 // at its top or bottom.
2484 let top = col.tile_offset(col.active_tile_idx).y;
2485 let bottom = top + col.data[col.active_tile_idx].size.h;
2486
2487 if tile_index <= col.active_tile_idx {
2488 (150., top)
2489 } else {
2490 (150., bottom - 150.)
2491 }
2492 } else {
2493 let top = col.tile_offset(tile_index).y;
2494
2495 if tile_index == 0 {
2496 (150., top)
2497 } else if tile_index == col.tiles.len() {
2498 (150., top - self.options.layout.gaps - 150.)
2499 } else {
2500 (300., top - self.options.layout.gaps / 2. - 150.)
2501 }
2502 };
2503
2504 // Adjust for place-within-column tab indicator.
2505 let origin_x = col.tiles_origin().x;
2506 let extra_w = if is_tabbed && col.sizing_mode().is_normal() {
2507 col.tab_indicator.extra_size(col.tiles.len(), col.scale).w
2508 } else {
2509 0.
2510 };
2511
2512 let size = Size::from((self.data[column_index].width - extra_w, height));
2513 let loc = Point::from((self.column_x(column_index) + origin_x, y));
2514 Rectangle::new(loc, size)
2515 }
2516 InsertPosition::Floating => return None,
2517 };
2518
2519 // First window on an empty workspace will cancel out any view offset. Replicate this
2520 // effect here.
2521 if self.columns.is_empty() {
2522 let view_offset = if self.is_centering_focused_column() {
2523 self.compute_new_view_offset_centered(
2524 Some(0.),
2525 0.,
2526 hint_area.size.w,
2527 SizingMode::Normal,
2528 )
2529 } else {
2530 self.compute_new_view_offset_fit(Some(0.), 0., hint_area.size.w, SizingMode::Normal)
2531 };
2532 hint_area.loc.x -= view_offset;
2533 } else {
2534 hint_area.loc.x -= self.view_pos();
2535 }
2536
2537 Some(hint_area)
2538 }
2539
2540 /// Returns the geometry of the active tile relative to and clamped to the view.
2541 ///
2542 /// During animations, assumes the final view position.
2543 pub fn active_tile_visual_rectangle(&self) -> Option<Rectangle<f64, Logical>> {
2544 let col = self.columns.get(self.active_column_idx)?;
2545
2546 let final_view_offset = self.view_offset.target();
2547 let view_off = Point::from((-final_view_offset, 0.));
2548
2549 let (tile, tile_off) = col.tiles().nth(col.active_tile_idx).unwrap();
2550
2551 let tile_pos = view_off + tile_off;
2552 let tile_size = tile.tile_size();
2553 let tile_rect = Rectangle::new(tile_pos, tile_size);
2554
2555 let view = Rectangle::from_size(self.view_size);
2556 view.intersection(tile_rect)
2557 }
2558
2559 pub fn popup_target_rect(&self, id: &W::Id) -> Option<Rectangle<f64, Logical>> {
2560 for col in &self.columns {
2561 for (tile, pos) in col.tiles() {
2562 if tile.window().id() == id {
2563 // In the scrolling layout, we try to position popups horizontally within the
2564 // window geometry (so they remain visible even if the window scrolls flush with
2565 // the left/right edge of the screen), and vertically wihin the whole parent
2566 // working area.
2567 let width = tile.window_size().w;
2568 let height = self.parent_area.size.h;
2569
2570 let mut target = Rectangle::from_size(Size::from((width, height)));
2571 target.loc.y += self.parent_area.loc.y;
2572 target.loc.y -= pos.y;
2573 target.loc.y -= tile.window_loc().y;
2574
2575 return Some(target);
2576 }
2577 }
2578 }
2579 None
2580 }
2581
2582 pub fn toggle_width(&mut self, forwards: bool) {
2583 if self.columns.is_empty() {
2584 return;
2585 }
2586
2587 let col = &mut self.columns[self.active_column_idx];
2588 col.toggle_width(None, forwards);
2589
2590 cancel_resize_for_column(&mut self.interactive_resize, col);
2591 }
2592
2593 pub fn toggle_full_width(&mut self) {
2594 if self.columns.is_empty() {
2595 return;
2596 }
2597
2598 let col = &mut self.columns[self.active_column_idx];
2599 col.toggle_full_width();
2600
2601 cancel_resize_for_column(&mut self.interactive_resize, col);
2602 }
2603
2604 pub fn set_window_width(&mut self, window: Option<&W::Id>, change: SizeChange) {
2605 if self.columns.is_empty() {
2606 return;
2607 }
2608
2609 let (col, tile_idx) = if let Some(window) = window {
2610 self.columns
2611 .iter_mut()
2612 .find_map(|col| {
2613 col.tiles
2614 .iter()
2615 .position(|tile| tile.window().id() == window)
2616 .map(|tile_idx| (col, Some(tile_idx)))
2617 })
2618 .unwrap()
2619 } else {
2620 (&mut self.columns[self.active_column_idx], None)
2621 };
2622
2623 col.set_column_width(change, tile_idx, true);
2624
2625 cancel_resize_for_column(&mut self.interactive_resize, col);
2626 }
2627
2628 pub fn set_window_height(&mut self, window: Option<&W::Id>, change: SizeChange) {
2629 if self.columns.is_empty() {
2630 return;
2631 }
2632
2633 let (col, tile_idx) = if let Some(window) = window {
2634 self.columns
2635 .iter_mut()
2636 .find_map(|col| {
2637 col.tiles
2638 .iter()
2639 .position(|tile| tile.window().id() == window)
2640 .map(|tile_idx| (col, Some(tile_idx)))
2641 })
2642 .unwrap()
2643 } else {
2644 (&mut self.columns[self.active_column_idx], None)
2645 };
2646
2647 col.set_window_height(change, tile_idx, true);
2648
2649 cancel_resize_for_column(&mut self.interactive_resize, col);
2650 }
2651
2652 pub fn reset_window_height(&mut self, window: Option<&W::Id>) {
2653 if self.columns.is_empty() {
2654 return;
2655 }
2656
2657 let (col, tile_idx) = if let Some(window) = window {
2658 self.columns
2659 .iter_mut()
2660 .find_map(|col| {
2661 col.tiles
2662 .iter()
2663 .position(|tile| tile.window().id() == window)
2664 .map(|tile_idx| (col, Some(tile_idx)))
2665 })
2666 .unwrap()
2667 } else {
2668 (&mut self.columns[self.active_column_idx], None)
2669 };
2670
2671 col.reset_window_height(tile_idx);
2672
2673 cancel_resize_for_column(&mut self.interactive_resize, col);
2674 }
2675
2676 pub fn toggle_window_width(&mut self, window: Option<&W::Id>, forwards: bool) {
2677 if self.columns.is_empty() {
2678 return;
2679 }
2680
2681 let (col, tile_idx) = if let Some(window) = window {
2682 self.columns
2683 .iter_mut()
2684 .find_map(|col| {
2685 col.tiles
2686 .iter()
2687 .position(|tile| tile.window().id() == window)
2688 .map(|tile_idx| (col, Some(tile_idx)))
2689 })
2690 .unwrap()
2691 } else {
2692 (&mut self.columns[self.active_column_idx], None)
2693 };
2694
2695 col.toggle_width(tile_idx, forwards);
2696
2697 cancel_resize_for_column(&mut self.interactive_resize, col);
2698 }
2699
2700 pub fn toggle_window_height(&mut self, window: Option<&W::Id>, forwards: bool) {
2701 if self.columns.is_empty() {
2702 return;
2703 }
2704
2705 let (col, tile_idx) = if let Some(window) = window {
2706 self.columns
2707 .iter_mut()
2708 .find_map(|col| {
2709 col.tiles
2710 .iter()
2711 .position(|tile| tile.window().id() == window)
2712 .map(|tile_idx| (col, Some(tile_idx)))
2713 })
2714 .unwrap()
2715 } else {
2716 (&mut self.columns[self.active_column_idx], None)
2717 };
2718
2719 col.toggle_window_height(tile_idx, forwards);
2720
2721 cancel_resize_for_column(&mut self.interactive_resize, col);
2722 }
2723
2724 pub fn expand_column_to_available_width(&mut self) {
2725 if self.columns.is_empty() {
2726 return;
2727 }
2728
2729 let col = &mut self.columns[self.active_column_idx];
2730 if !col.pending_sizing_mode().is_normal() || col.is_full_width {
2731 return;
2732 }
2733
2734 if self.is_centering_focused_column() {
2735 // Always-centered mode is different since the active window position cannot be
2736 // controlled (it's always at the center). I guess you could come up with different
2737 // logic here that computes the width in such a way so as to leave nearby columns fully
2738 // on screen while taking into account that the active column will remain centered
2739 // after resizing. But I'm not sure it's that useful? So let's do the simple thing.
2740 let col = &mut self.columns[self.active_column_idx];
2741 col.toggle_full_width();
2742 cancel_resize_for_column(&mut self.interactive_resize, col);
2743 return;
2744 }
2745
2746 // NOTE: This logic won't work entirely correctly with small fixed-size maximized windows
2747 // (they have a different area and padding).
2748
2749 // Consider the end of an ongoing animation because that's what compute to fit does too.
2750 let view_x = self.target_view_pos();
2751 let working_x = self.working_area.loc.x;
2752 let working_w = self.working_area.size.w;
2753
2754 // Count all columns that are fully visible inside the working area.
2755 let mut width_taken = 0.;
2756 let mut leftmost_col_x = None;
2757 let mut active_col_x = None;
2758 let mut counted_non_active_column = false;
2759
2760 let gap = self.options.layout.gaps;
2761 let col_xs = self.column_xs(self.data.iter().copied());
2762 for (idx, col_x) in col_xs.take(self.columns.len()).enumerate() {
2763 if col_x < view_x + working_x + gap {
2764 // Column goes off-screen to the left.
2765 continue;
2766 }
2767
2768 leftmost_col_x.get_or_insert(col_x);
2769
2770 let width = self.data[idx].width;
2771 if view_x + working_x + working_w < col_x + width + gap {
2772 // Column goes off-screen to the right. We can stop here.
2773 break;
2774 }
2775
2776 if idx == self.active_column_idx {
2777 active_col_x = Some(col_x);
2778 } else {
2779 counted_non_active_column = true;
2780 }
2781
2782 width_taken += width + gap;
2783 }
2784
2785 if active_col_x.is_none() {
2786 // The active column wasn't fully on screen, so we can't meaningfully do anything.
2787 return;
2788 }
2789
2790 let col = &mut self.columns[self.active_column_idx];
2791
2792 let available_width = working_w - gap - width_taken - col.extra_size().w;
2793 if available_width <= 0. {
2794 // Nowhere to expand.
2795 return;
2796 }
2797
2798 cancel_resize_for_column(&mut self.interactive_resize, col);
2799
2800 if !counted_non_active_column {
2801 // Only the active column was fully on-screen (maybe it's the only column), so we're
2802 // about to set its width to 100% of the working area. Let's do it via
2803 // toggle_full_width() as it lets you back out of it more intuitively.
2804 col.toggle_full_width();
2805 return;
2806 }
2807
2808 let active_width = self.data[self.active_column_idx].width;
2809 col.width = ColumnWidth::Fixed(active_width + available_width);
2810 col.preset_width_idx = None;
2811 col.is_full_width = false;
2812 col.update_tile_sizes(true);
2813
2814 // Put the leftmost window into the view.
2815 let new_view_x = leftmost_col_x.unwrap() - gap - working_x;
2816 self.animate_view_offset(self.active_column_idx, new_view_x - active_col_x.unwrap());
2817 // Just in case.
2818 self.animate_view_offset_to_column(None, self.active_column_idx, None);
2819 }
2820
2821 pub fn set_fullscreen(&mut self, window: &W::Id, is_fullscreen: bool) -> bool {
2822 let mut col_idx = self
2823 .columns
2824 .iter()
2825 .position(|col| col.contains(window))
2826 .unwrap();
2827
2828 if is_fullscreen == self.columns[col_idx].is_pending_fullscreen {
2829 return false;
2830 }
2831
2832 let mut col = &mut self.columns[col_idx];
2833 let is_tabbed = col.display_mode == ColumnDisplay::Tabbed;
2834
2835 cancel_resize_for_column(&mut self.interactive_resize, col);
2836
2837 if is_fullscreen && (col.tiles.len() > 1 && !is_tabbed) {
2838 // This wasn't the only window in its column; extract it into a separate column.
2839 self.consume_or_expel_window_right(Some(window));
2840 col_idx += 1;
2841 col = &mut self.columns[col_idx];
2842 }
2843
2844 col.set_fullscreen(is_fullscreen);
2845
2846 // With place_within_column, the tab indicator changes the column size immediately.
2847 self.data[col_idx].update(col);
2848
2849 true
2850 }
2851
2852 pub fn set_maximized(&mut self, window: &W::Id, maximize: bool) -> bool {
2853 let mut col_idx = self
2854 .columns
2855 .iter()
2856 .position(|col| col.contains(window))
2857 .unwrap();
2858
2859 if maximize == self.columns[col_idx].is_pending_maximized {
2860 return false;
2861 }
2862
2863 let mut col = &mut self.columns[col_idx];
2864 let is_tabbed = col.display_mode == ColumnDisplay::Tabbed;
2865
2866 cancel_resize_for_column(&mut self.interactive_resize, col);
2867
2868 if maximize && (col.tiles.len() > 1 && !is_tabbed) {
2869 // This wasn't the only window in its column; extract it into a separate column.
2870 self.consume_or_expel_window_right(Some(window));
2871 col_idx += 1;
2872 col = &mut self.columns[col_idx];
2873 }
2874
2875 col.set_maximized(maximize);
2876
2877 // With place_within_column, the tab indicator changes the column size immediately.
2878 self.data[col_idx].update(col);
2879
2880 true
2881 }
2882
2883 pub fn render_above_top_layer(&self) -> bool {
2884 // Render above the top layer if we're on a fullscreen window and the view is stationary.
2885 if self.columns.is_empty() {
2886 return false;
2887 }
2888
2889 if !self.view_offset.is_static() {
2890 return false;
2891 }
2892
2893 self.columns[self.active_column_idx]
2894 .sizing_mode()
2895 .is_fullscreen()
2896 }
2897
2898 pub fn render_elements<R: NiriRenderer>(
2899 &self,
2900 renderer: &mut R,
2901 target: RenderTarget,
2902 focus_ring: bool,
2903 ) -> Vec<ScrollingSpaceRenderElement<R>> {
2904 let mut rv = vec![];
2905
2906 let scale = Scale::from(self.scale);
2907
2908 // Draw the closing windows on top of the other windows.
2909 let view_rect = Rectangle::new(Point::from((self.view_pos(), 0.)), self.view_size);
2910 for closing in self.closing_windows.iter().rev() {
2911 let elem = closing.render(renderer.as_gles_renderer(), view_rect, scale, target);
2912 rv.push(elem.into());
2913 }
2914
2915 if self.columns.is_empty() {
2916 return rv;
2917 }
2918
2919 let mut first = true;
2920
2921 // This matches self.tiles_in_render_order().
2922 let view_off = Point::from((-self.view_pos(), 0.));
2923 for (col, col_x) in self.columns_in_render_order() {
2924 let col_off = Point::from((col_x, 0.));
2925 let col_render_off = col.render_offset();
2926
2927 // Draw the tab indicator on top.
2928 {
2929 let pos = view_off + col_off + col_render_off;
2930 let pos = pos.to_physical_precise_round(scale).to_logical(scale);
2931 rv.extend(col.tab_indicator.render(renderer, pos).map(Into::into));
2932 }
2933
2934 for (tile, tile_off, visible) in col.tiles_in_render_order() {
2935 let tile_pos =
2936 view_off + col_off + col_render_off + tile_off + tile.render_offset();
2937 // Round to physical pixels.
2938 let tile_pos = tile_pos.to_physical_precise_round(scale).to_logical(scale);
2939
2940 // And now the drawing logic.
2941
2942 // For the active tile (which comes first), draw the focus ring.
2943 let focus_ring = focus_ring && first;
2944 first = false;
2945
2946 // In the scrolling layout, we currently use visible only for hidden tabs in the
2947 // tabbed mode. We want to animate their opacity when going in and out of tabbed
2948 // mode, so we don't want to apply "visible" immediately. However, "visible" is
2949 // also used for input handling, and there we *do* want to apply it immediately.
2950 // So, let's just selectively ignore "visible" here when animating alpha.
2951 let visible = visible || tile.alpha_animation.is_some();
2952 if !visible {
2953 continue;
2954 }
2955
2956 rv.extend(
2957 tile.render(renderer, tile_pos, focus_ring, target)
2958 .map(Into::into),
2959 );
2960 }
2961 }
2962
2963 rv
2964 }
2965
2966 pub fn window_under(&self, pos: Point<f64, Logical>) -> Option<(&W, HitType)> {
2967 // This matches self.tiles_with_render_positions().
2968 let scale = self.scale;
2969 let view_off = Point::from((-self.view_pos(), 0.));
2970 for (col, col_x) in self.columns_in_render_order() {
2971 let col_off = Point::from((col_x, 0.));
2972 let col_render_off = col.render_offset();
2973
2974 // Hit the tab indicator.
2975 if col.display_mode == ColumnDisplay::Tabbed && col.sizing_mode().is_normal() {
2976 let col_pos = view_off + col_off + col_render_off;
2977 let col_pos = col_pos.to_physical_precise_round(scale).to_logical(scale);
2978
2979 if let Some(idx) = col.tab_indicator.hit(
2980 col.tab_indicator_area(),
2981 col.tiles.len(),
2982 scale,
2983 pos - col_pos,
2984 ) {
2985 let hit = HitType::Activate {
2986 is_tab_indicator: true,
2987 };
2988 return Some((col.tiles[idx].window(), hit));
2989 }
2990 }
2991
2992 for (tile, tile_off, visible) in col.tiles_in_render_order() {
2993 if !visible {
2994 continue;
2995 }
2996
2997 let tile_pos =
2998 view_off + col_off + col_render_off + tile_off + tile.render_offset();
2999 // Round to physical pixels.
3000 let tile_pos = tile_pos.to_physical_precise_round(scale).to_logical(scale);
3001
3002 if let Some(rv) = HitType::hit_tile(tile, tile_pos, pos) {
3003 return Some(rv);
3004 }
3005 }
3006 }
3007
3008 None
3009 }
3010
3011 pub fn view_offset_gesture_begin(&mut self, is_touchpad: bool) {
3012 if self.columns.is_empty() {
3013 return;
3014 }
3015
3016 if self.interactive_resize.is_some() {
3017 return;
3018 }
3019
3020 let gesture = ViewGesture {
3021 current_view_offset: self.view_offset.current(),
3022 animation: None,
3023 tracker: SwipeTracker::new(),
3024 delta_from_tracker: self.view_offset.current(),
3025 stationary_view_offset: self.view_offset.stationary(),
3026 is_touchpad,
3027 dnd_last_event_time: None,
3028 dnd_nonzero_start_time: None,
3029 };
3030 self.view_offset = ViewOffset::Gesture(gesture);
3031 }
3032
3033 pub fn dnd_scroll_gesture_begin(&mut self) {
3034 if let ViewOffset::Gesture(ViewGesture {
3035 dnd_last_event_time: Some(_),
3036 ..
3037 }) = &self.view_offset
3038 {
3039 // Already active.
3040 return;
3041 }
3042
3043 let gesture = ViewGesture {
3044 current_view_offset: self.view_offset.current(),
3045 animation: None,
3046 tracker: SwipeTracker::new(),
3047 delta_from_tracker: self.view_offset.current(),
3048 stationary_view_offset: self.view_offset.stationary(),
3049 is_touchpad: false,
3050 dnd_last_event_time: Some(self.clock.now_unadjusted()),
3051 dnd_nonzero_start_time: None,
3052 };
3053 self.view_offset = ViewOffset::Gesture(gesture);
3054
3055 self.interactive_resize = None;
3056 }
3057
3058 pub fn view_offset_gesture_update(
3059 &mut self,
3060 delta_x: f64,
3061 timestamp: Duration,
3062 is_touchpad: bool,
3063 ) -> Option<bool> {
3064 let ViewOffset::Gesture(gesture) = &mut self.view_offset else {
3065 return None;
3066 };
3067
3068 if gesture.is_touchpad != is_touchpad || gesture.dnd_last_event_time.is_some() {
3069 return None;
3070 }
3071
3072 gesture.tracker.push(delta_x, timestamp);
3073
3074 let norm_factor = if gesture.is_touchpad {
3075 self.working_area.size.w / VIEW_GESTURE_WORKING_AREA_MOVEMENT
3076 } else {
3077 1.
3078 };
3079 let pos = gesture.tracker.pos() * norm_factor;
3080 let view_offset = pos + gesture.delta_from_tracker;
3081 gesture.current_view_offset = view_offset;
3082
3083 Some(true)
3084 }
3085
3086 pub fn dnd_scroll_gesture_scroll(&mut self, delta: f64) -> bool {
3087 let ViewOffset::Gesture(gesture) = &mut self.view_offset else {
3088 return false;
3089 };
3090
3091 let Some(last_time) = gesture.dnd_last_event_time else {
3092 // Not a DnD scroll.
3093 return false;
3094 };
3095
3096 let config = &self.options.gestures.dnd_edge_view_scroll;
3097
3098 let now = self.clock.now_unadjusted();
3099 gesture.dnd_last_event_time = Some(now);
3100
3101 if delta == 0. {
3102 // We're outside the scrolling zone.
3103 gesture.dnd_nonzero_start_time = None;
3104 return false;
3105 }
3106
3107 let nonzero_start = *gesture.dnd_nonzero_start_time.get_or_insert(now);
3108
3109 // Delay starting the gesture a bit to avoid unwanted movement when dragging across
3110 // monitors.
3111 let delay = Duration::from_millis(u64::from(config.delay_ms));
3112 if now.saturating_sub(nonzero_start) < delay {
3113 return true;
3114 }
3115
3116 let time_delta = now.saturating_sub(last_time).as_secs_f64();
3117
3118 let delta = delta * time_delta * config.max_speed;
3119
3120 gesture.tracker.push(delta, now);
3121
3122 let view_offset = gesture.tracker.pos() + gesture.delta_from_tracker;
3123
3124 // Clamp it so that it doesn't go too much out of bounds.
3125 let (leftmost, rightmost) = if self.columns.is_empty() {
3126 (0., 0.)
3127 } else {
3128 let gaps = self.options.layout.gaps;
3129
3130 let mut leftmost = -self.working_area.size.w;
3131
3132 let last_col_idx = self.columns.len() - 1;
3133 let last_col_x = self
3134 .columns
3135 .iter()
3136 .take(last_col_idx)
3137 .fold(0., |col_x, col| col_x + col.width() + gaps);
3138 let last_col_width = self.data[last_col_idx].width;
3139 let mut rightmost = last_col_x + last_col_width - self.working_area.loc.x;
3140
3141 let active_col_x = self
3142 .columns
3143 .iter()
3144 .take(self.active_column_idx)
3145 .fold(0., |col_x, col| col_x + col.width() + gaps);
3146 leftmost -= active_col_x;
3147 rightmost -= active_col_x;
3148
3149 (leftmost, rightmost)
3150 };
3151 let min_offset = f64::min(leftmost, rightmost);
3152 let max_offset = f64::max(leftmost, rightmost);
3153 let clamped_offset = view_offset.clamp(min_offset, max_offset);
3154
3155 gesture.delta_from_tracker += clamped_offset - view_offset;
3156 gesture.current_view_offset = clamped_offset;
3157 true
3158 }
3159
3160 pub fn view_offset_gesture_end(&mut self, is_touchpad: Option<bool>) -> bool {
3161 let ViewOffset::Gesture(gesture) = &mut self.view_offset else {
3162 return false;
3163 };
3164
3165 if is_touchpad.is_some_and(|x| gesture.is_touchpad != x) {
3166 return false;
3167 }
3168
3169 // We do not handle cancelling, just like GNOME Shell doesn't. For this gesture, proper
3170 // cancelling would require keeping track of the original active column, and then updating
3171 // it in all the right places (adding columns, removing columns, etc.) -- quite a bit of
3172 // effort and bug potential.
3173
3174 // Take into account any idle time between the last event and now.
3175 let now = self.clock.now_unadjusted();
3176 gesture.tracker.push(0., now);
3177
3178 let norm_factor = if gesture.is_touchpad {
3179 self.working_area.size.w / VIEW_GESTURE_WORKING_AREA_MOVEMENT
3180 } else {
3181 1.
3182 };
3183 let velocity = gesture.tracker.velocity() * norm_factor;
3184 let pos = gesture.tracker.pos() * norm_factor;
3185 let current_view_offset = pos + gesture.delta_from_tracker;
3186
3187 if self.columns.is_empty() {
3188 self.view_offset = ViewOffset::Static(current_view_offset);
3189 return true;
3190 }
3191
3192 // Figure out where the gesture would stop after deceleration.
3193 let end_pos = gesture.tracker.projected_end_pos() * norm_factor;
3194 let target_view_offset = end_pos + gesture.delta_from_tracker;
3195
3196 // Compute the snapping points. These are where the view aligns with column boundaries on
3197 // either side.
3198 struct Snap {
3199 // View position relative to x = 0 (the first column).
3200 view_pos: f64,
3201 // Column to activate for this snapping point.
3202 col_idx: usize,
3203 }
3204
3205 let mut snapping_points = Vec::new();
3206
3207 if self.is_centering_focused_column() {
3208 let mut col_x = 0.;
3209 for (col_idx, col) in self.columns.iter().enumerate() {
3210 let col_w = col.width();
3211 let mode = col.sizing_mode();
3212
3213 let area = if mode.is_maximized() {
3214 self.parent_area
3215 } else {
3216 self.working_area
3217 };
3218
3219 let left_strut = area.loc.x;
3220
3221 let view_pos = if mode.is_fullscreen() {
3222 col_x
3223 } else if area.size.w <= col_w {
3224 col_x - left_strut
3225 } else {
3226 col_x - (area.size.w - col_w) / 2. - left_strut
3227 };
3228 snapping_points.push(Snap { view_pos, col_idx });
3229
3230 col_x += col_w + self.options.layout.gaps;
3231 }
3232 } else {
3233 let center_on_overflow = matches!(
3234 self.options.layout.center_focused_column,
3235 CenterFocusedColumn::OnOverflow
3236 );
3237
3238 let view_width = self.view_size.w;
3239 let gaps = self.options.layout.gaps;
3240
3241 let snap_points =
3242 |col_x, col: &Column<W>, prev_col_w: Option<f64>, next_col_w: Option<f64>| {
3243 let col_w = col.width();
3244 let mode = col.sizing_mode();
3245
3246 let area = if mode.is_maximized() {
3247 self.parent_area
3248 } else {
3249 self.working_area
3250 };
3251
3252 let left_strut = area.loc.x;
3253 let right_strut = self.view_size.w - area.size.w - area.loc.x;
3254
3255 // Normal columns align with the working area, but fullscreen columns align with
3256 // the view size.
3257 if mode.is_fullscreen() {
3258 let left = col_x;
3259 let right = left + col_w;
3260 (left, right)
3261 } else {
3262 // Logic from compute_new_view_offset.
3263 let padding = if mode.is_maximized() {
3264 0.
3265 } else {
3266 ((area.size.w - col_w) / 2.).clamp(0., gaps)
3267 };
3268
3269 let center = if area.size.w <= col_w {
3270 col_x - left_strut
3271 } else {
3272 col_x - (area.size.w - col_w) / 2. - left_strut
3273 };
3274 let is_overflowing = |adj_col_w: Option<f64>| {
3275 center_on_overflow
3276 && adj_col_w
3277 .filter(|adj_col_w| {
3278 // NOTE: This logic won't work entirely correctly with small
3279 // fixed-size maximized windows (they have a different area
3280 // and padding).
3281 center_on_overflow
3282 && adj_col_w + 3.0 * gaps + col_w > area.size.w
3283 })
3284 .is_some()
3285 };
3286
3287 let left = if is_overflowing(next_col_w) {
3288 center
3289 } else {
3290 col_x - padding - left_strut
3291 };
3292 let right = if is_overflowing(prev_col_w) {
3293 center + view_width
3294 } else {
3295 col_x + col_w + padding + right_strut
3296 };
3297 (left, right)
3298 }
3299 };
3300
3301 // Prevent the gesture from snapping further than the first/last column, as this is
3302 // generally undesired.
3303 //
3304 // It's ok if leftmost_snap is > rightmost_snap (this happens if the columns on a
3305 // workspace total up to less than the workspace width).
3306
3307 // The first column's left snap isn't actually guaranteed to be the *leftmost* snap.
3308 // With weird enough left strut and perhaps a maximized small fixed-size window, you
3309 // can make the second window's left snap be further to the left than the first
3310 // window's. The same goes for the rightmost snap.
3311 //
3312 // This isn't actually a big problem because it's very much an obscure edge case. Just
3313 // need to make sure the code doesn't panic when that happens.
3314 let leftmost_snap = snap_points(
3315 0.,
3316 &self.columns[0],
3317 None,
3318 self.columns.get(1).map(|c| c.width()),
3319 )
3320 .0;
3321 let last_col_idx = self.columns.len() - 1;
3322 let last_col_x = self
3323 .columns
3324 .iter()
3325 .take(last_col_idx)
3326 .fold(0., |col_x, col| col_x + col.width() + gaps);
3327 let rightmost_snap = snap_points(
3328 last_col_x,
3329 &self.columns[last_col_idx],
3330 last_col_idx
3331 .checked_sub(1)
3332 .and_then(|idx| self.columns.get(idx).map(|c| c.width())),
3333 None,
3334 )
3335 .1 - view_width;
3336
3337 snapping_points.push(Snap {
3338 view_pos: leftmost_snap,
3339 col_idx: 0,
3340 });
3341 snapping_points.push(Snap {
3342 view_pos: rightmost_snap,
3343 col_idx: last_col_idx,
3344 });
3345
3346 let mut push = |col_idx, left, right| {
3347 if leftmost_snap < left && left < rightmost_snap {
3348 snapping_points.push(Snap {
3349 view_pos: left,
3350 col_idx,
3351 });
3352 }
3353
3354 let right = right - view_width;
3355 if leftmost_snap < right && right < rightmost_snap {
3356 snapping_points.push(Snap {
3357 view_pos: right,
3358 col_idx,
3359 });
3360 }
3361 };
3362
3363 let mut col_x = 0.;
3364 for (col_idx, col) in self.columns.iter().enumerate() {
3365 let (left, right) = snap_points(
3366 col_x,
3367 col,
3368 col_idx
3369 .checked_sub(1)
3370 .and_then(|idx| self.columns.get(idx).map(|c| c.width())),
3371 self.columns.get(col_idx + 1).map(|c| c.width()),
3372 );
3373 push(col_idx, left, right);
3374
3375 col_x += col.width() + gaps;
3376 }
3377 }
3378
3379 // Find the closest snapping point.
3380 snapping_points.sort_by_key(|snap| NotNan::new(snap.view_pos).unwrap());
3381
3382 let active_col_x = self.column_x(self.active_column_idx);
3383 let target_view_pos = active_col_x + target_view_offset;
3384 let target_snap = snapping_points
3385 .iter()
3386 .min_by_key(|snap| NotNan::new((snap.view_pos - target_view_pos).abs()).unwrap())
3387 .unwrap();
3388
3389 let mut new_col_idx = target_snap.col_idx;
3390
3391 if !self.is_centering_focused_column() {
3392 // Focus the furthest window towards the direction of the gesture.
3393 if target_view_offset >= current_view_offset {
3394 for col_idx in (new_col_idx + 1)..self.columns.len() {
3395 let col = &self.columns[col_idx];
3396 let col_x = self.column_x(col_idx);
3397 let col_w = col.width();
3398 let mode = col.sizing_mode();
3399
3400 let area = if mode.is_maximized() {
3401 self.parent_area
3402 } else {
3403 self.working_area
3404 };
3405
3406 let left_strut = area.loc.x;
3407
3408 if mode.is_fullscreen() {
3409 if target_snap.view_pos + self.view_size.w < col_x + col_w {
3410 break;
3411 }
3412 } else {
3413 let padding = if mode.is_maximized() {
3414 0.
3415 } else {
3416 ((area.size.w - col_w) / 2.).clamp(0., self.options.layout.gaps)
3417 };
3418
3419 if target_snap.view_pos + left_strut + area.size.w < col_x + col_w + padding
3420 {
3421 break;
3422 }
3423 }
3424
3425 new_col_idx = col_idx;
3426 }
3427 } else {
3428 for col_idx in (0..new_col_idx).rev() {
3429 let col = &self.columns[col_idx];
3430 let col_x = self.column_x(col_idx);
3431 let col_w = col.width();
3432 let mode = col.sizing_mode();
3433
3434 let area = if mode.is_maximized() {
3435 self.parent_area
3436 } else {
3437 self.working_area
3438 };
3439
3440 let left_strut = area.loc.x;
3441
3442 if mode.is_fullscreen() {
3443 if col_x < target_snap.view_pos {
3444 break;
3445 }
3446 } else {
3447 let padding = if mode.is_maximized() {
3448 0.
3449 } else {
3450 ((area.size.w - col_w) / 2.).clamp(0., self.options.layout.gaps)
3451 };
3452
3453 if col_x - padding < target_snap.view_pos + left_strut {
3454 break;
3455 }
3456 }
3457
3458 new_col_idx = col_idx;
3459 }
3460 }
3461 }
3462
3463 let new_col_x = self.column_x(new_col_idx);
3464 let delta = active_col_x - new_col_x;
3465
3466 if self.active_column_idx != new_col_idx {
3467 self.view_offset_to_restore = None;
3468 }
3469
3470 self.active_column_idx = new_col_idx;
3471
3472 let target_view_offset = target_snap.view_pos - new_col_x;
3473
3474 self.view_offset = ViewOffset::Animation(Animation::new(
3475 self.clock.clone(),
3476 current_view_offset + delta,
3477 target_view_offset,
3478 velocity,
3479 self.options.animations.horizontal_view_movement.0,
3480 ));
3481
3482 // HACK: deal with things like snapping to the right edge of a larger-than-view window.
3483 self.animate_view_offset_to_column(None, new_col_idx, None);
3484
3485 true
3486 }
3487
3488 pub fn dnd_scroll_gesture_end(&mut self) {
3489 let ViewOffset::Gesture(gesture) = &mut self.view_offset else {
3490 return;
3491 };
3492
3493 if gesture.dnd_last_event_time.is_some() && gesture.tracker.pos() == 0. {
3494 // DnD didn't scroll anything, so preserve the current view position (rather than
3495 // snapping the window).
3496 self.view_offset = ViewOffset::Static(gesture.delta_from_tracker);
3497
3498 if !self.columns.is_empty() {
3499 // Just in case, make sure the active window remains on screen.
3500 self.animate_view_offset_to_column(None, self.active_column_idx, None);
3501 }
3502 return;
3503 }
3504
3505 self.view_offset_gesture_end(None);
3506 }
3507
3508 pub fn interactive_resize_begin(&mut self, window: W::Id, edges: ResizeEdge) -> bool {
3509 if self.interactive_resize.is_some() {
3510 return false;
3511 }
3512
3513 let col = self
3514 .columns
3515 .iter_mut()
3516 .find(|col| col.contains(&window))
3517 .unwrap();
3518
3519 if !col.pending_sizing_mode().is_normal() {
3520 return false;
3521 }
3522
3523 let tile = col
3524 .tiles
3525 .iter_mut()
3526 .find(|tile| tile.window().id() == &window)
3527 .unwrap();
3528
3529 let original_window_size = tile.window_size();
3530
3531 let resize = InteractiveResize {
3532 window,
3533 original_window_size,
3534 data: InteractiveResizeData { edges },
3535 };
3536 self.interactive_resize = Some(resize);
3537
3538 self.view_offset.stop_anim_and_gesture();
3539
3540 true
3541 }
3542
3543 pub fn interactive_resize_update(
3544 &mut self,
3545 window: &W::Id,
3546 delta: Point<f64, Logical>,
3547 ) -> bool {
3548 let Some(resize) = &self.interactive_resize else {
3549 return false;
3550 };
3551
3552 if window != &resize.window {
3553 return false;
3554 }
3555
3556 let is_centering = self.is_centering_focused_column();
3557
3558 let col = self
3559 .columns
3560 .iter_mut()
3561 .find(|col| col.contains(window))
3562 .unwrap();
3563
3564 let tile_idx = col
3565 .tiles
3566 .iter()
3567 .position(|tile| tile.window().id() == window)
3568 .unwrap();
3569
3570 if resize.data.edges.intersects(ResizeEdge::LEFT_RIGHT) {
3571 let mut dx = delta.x;
3572 if resize.data.edges.contains(ResizeEdge::LEFT) {
3573 dx = -dx;
3574 };
3575
3576 if is_centering {
3577 dx *= 2.;
3578 }
3579
3580 let window_width = (resize.original_window_size.w + dx).round() as i32;
3581 col.set_column_width(SizeChange::SetFixed(window_width), Some(tile_idx), false);
3582 }
3583
3584 if resize.data.edges.intersects(ResizeEdge::TOP_BOTTOM) {
3585 // Prevent the simplest case of weird resizing (top edge when this is the topmost
3586 // window).
3587 if !(resize.data.edges.contains(ResizeEdge::TOP) && tile_idx == 0) {
3588 let mut dy = delta.y;
3589 if resize.data.edges.contains(ResizeEdge::TOP) {
3590 dy = -dy;
3591 };
3592
3593 // FIXME: some smarter height distribution would be nice here so that vertical
3594 // resizes work as expected in more cases.
3595
3596 let window_height = (resize.original_window_size.h + dy).round() as i32;
3597 col.set_window_height(SizeChange::SetFixed(window_height), Some(tile_idx), false);
3598 }
3599 }
3600
3601 true
3602 }
3603
3604 pub fn interactive_resize_end(&mut self, window: Option<&W::Id>) {
3605 let Some(resize) = &self.interactive_resize else {
3606 return;
3607 };
3608
3609 if let Some(window) = window {
3610 if window != &resize.window {
3611 return;
3612 }
3613
3614 // Animate the active window into view right away.
3615 if self.columns[self.active_column_idx].contains(window) {
3616 self.animate_view_offset_to_column(None, self.active_column_idx, None);
3617 }
3618 }
3619
3620 self.interactive_resize = None;
3621 }
3622
3623 pub fn refresh(&mut self, is_active: bool, is_focused: bool) {
3624 for (col_idx, col) in self.columns.iter_mut().enumerate() {
3625 let mut col_resize_data = None;
3626 if let Some(resize) = &self.interactive_resize {
3627 if col.contains(&resize.window) {
3628 col_resize_data = Some(resize.data);
3629 }
3630 }
3631
3632 let is_tabbed = col.display_mode == ColumnDisplay::Tabbed;
3633 let extra_size = col.extra_size();
3634
3635 // If transactions are disabled, also disable combined throttling, for more intuitive
3636 // behavior. In tabbed display mode, only one window is visible, so individual
3637 // throttling makes more sense.
3638 let individual_throttling = self.options.disable_transactions || is_tabbed;
3639
3640 let intent = if self.options.disable_resize_throttling {
3641 ConfigureIntent::CanSend
3642 } else if individual_throttling {
3643 // In this case, we don't use combined throttling, but rather compute throttling
3644 // individually below.
3645 ConfigureIntent::CanSend
3646 } else {
3647 col.tiles
3648 .iter()
3649 .fold(ConfigureIntent::NotNeeded, |intent, tile| {
3650 match (intent, tile.window().configure_intent()) {
3651 (_, ConfigureIntent::ShouldSend) => ConfigureIntent::ShouldSend,
3652 (ConfigureIntent::NotNeeded, tile_intent) => tile_intent,
3653 (ConfigureIntent::CanSend, ConfigureIntent::Throttled) => {
3654 ConfigureIntent::Throttled
3655 }
3656 (intent, _) => intent,
3657 }
3658 })
3659 };
3660
3661 for (tile_idx, tile) in col.tiles.iter_mut().enumerate() {
3662 let win = tile.window_mut();
3663
3664 let active_in_column = col.active_tile_idx == tile_idx;
3665 win.set_active_in_column(active_in_column);
3666 win.set_floating(false);
3667
3668 let mut active = is_active && self.active_column_idx == col_idx;
3669 if self.options.deactivate_unfocused_windows {
3670 active &= active_in_column && is_focused;
3671 } else {
3672 // In tabbed mode, all tabs have activated state to reduce unnecessary
3673 // animations when switching tabs.
3674 active &= active_in_column || is_tabbed;
3675 }
3676 win.set_activated(active);
3677
3678 win.set_interactive_resize(col_resize_data);
3679
3680 let border_config = self.options.layout.border.merged_with(&win.rules().border);
3681 let bounds = compute_toplevel_bounds(
3682 border_config,
3683 self.working_area.size,
3684 extra_size,
3685 self.options.layout.gaps,
3686 );
3687 win.set_bounds(bounds);
3688
3689 let intent = if individual_throttling {
3690 win.configure_intent()
3691 } else {
3692 intent
3693 };
3694
3695 if matches!(
3696 intent,
3697 ConfigureIntent::CanSend | ConfigureIntent::ShouldSend
3698 ) {
3699 win.send_pending_configure();
3700 }
3701
3702 win.refresh();
3703 }
3704 }
3705 }
3706
3707 #[cfg(test)]
3708 pub fn view_size(&self) -> Size<f64, Logical> {
3709 self.view_size
3710 }
3711
3712 #[cfg(test)]
3713 pub fn parent_area(&self) -> Rectangle<f64, Logical> {
3714 self.parent_area
3715 }
3716
3717 #[cfg(test)]
3718 pub fn clock(&self) -> &Clock {
3719 &self.clock
3720 }
3721
3722 #[cfg(test)]
3723 pub fn options(&self) -> &Rc<Options> {
3724 &self.options
3725 }
3726
3727 #[cfg(test)]
3728 pub fn active_column_idx(&self) -> usize {
3729 self.active_column_idx
3730 }
3731
3732 #[cfg(test)]
3733 pub(super) fn view_offset(&self) -> &ViewOffset {
3734 &self.view_offset
3735 }
3736
3737 #[cfg(test)]
3738 pub fn verify_invariants(&self) {
3739 assert!(self.view_size.w > 0.);
3740 assert!(self.view_size.h > 0.);
3741 assert!(self.scale > 0.);
3742 assert!(self.scale.is_finite());
3743 assert_eq!(self.columns.len(), self.data.len());
3744 assert_eq!(
3745 self.working_area,
3746 compute_working_area(self.parent_area, self.scale, self.options.layout.struts)
3747 );
3748
3749 if !self.columns.is_empty() {
3750 assert!(self.active_column_idx < self.columns.len());
3751
3752 for (column, data) in zip(&self.columns, &self.data) {
3753 assert!(Rc::ptr_eq(&self.options, &column.options));
3754 assert_eq!(self.clock, column.clock);
3755 assert_eq!(self.scale, column.scale);
3756 column.verify_invariants();
3757
3758 let mut data2 = *data;
3759 data2.update(column);
3760 assert_eq!(data, &data2, "column data must be up to date");
3761 }
3762
3763 let col = &self.columns[self.active_column_idx];
3764
3765 if self.view_offset_to_restore.is_some() {
3766 assert!(
3767 !col.sizing_mode().is_normal(),
3768 "when view_offset_to_restore is set, \
3769 the active column must be fullscreen or maximized"
3770 );
3771 }
3772 }
3773
3774 if let Some(resize) = &self.interactive_resize {
3775 assert!(
3776 self.columns
3777 .iter()
3778 .flat_map(|col| &col.tiles)
3779 .any(|tile| tile.window().id() == &resize.window),
3780 "interactive resize window must be present in the layout"
3781 );
3782 }
3783 }
3784}
3785
3786impl ViewOffset {
3787 /// Returns the current view offset.
3788 pub fn current(&self) -> f64 {
3789 match self {
3790 ViewOffset::Static(offset) => *offset,
3791 ViewOffset::Animation(anim) => anim.value(),
3792 ViewOffset::Gesture(gesture) => {
3793 gesture.current_view_offset
3794 + gesture.animation.as_ref().map_or(0., |anim| anim.value())
3795 }
3796 }
3797 }
3798
3799 /// Returns the target view offset suitable for computing the new view offset.
3800 pub fn target(&self) -> f64 {
3801 match self {
3802 ViewOffset::Static(offset) => *offset,
3803 ViewOffset::Animation(anim) => anim.to(),
3804 // This can be used for example if a gesture is interrupted.
3805 ViewOffset::Gesture(gesture) => gesture.current_view_offset,
3806 }
3807 }
3808
3809 /// Returns a view offset value suitable for saving and later restoration.
3810 ///
3811 /// This means that it shouldn't return an in-progress animation or gesture value.
3812 fn stationary(&self) -> f64 {
3813 match self {
3814 ViewOffset::Static(offset) => *offset,
3815 // For animations we can return the final value.
3816 ViewOffset::Animation(anim) => anim.to(),
3817 ViewOffset::Gesture(gesture) => gesture.stationary_view_offset,
3818 }
3819 }
3820
3821 pub fn is_static(&self) -> bool {
3822 matches!(self, Self::Static(_))
3823 }
3824
3825 pub fn is_gesture(&self) -> bool {
3826 matches!(self, Self::Gesture(_))
3827 }
3828
3829 pub fn is_dnd_scroll(&self) -> bool {
3830 matches!(&self, ViewOffset::Gesture(gesture) if gesture.dnd_last_event_time.is_some())
3831 }
3832
3833 pub fn is_animation_ongoing(&self) -> bool {
3834 match self {
3835 ViewOffset::Static(_) => false,
3836 ViewOffset::Animation(_) => true,
3837 ViewOffset::Gesture(gesture) => gesture.animation.is_some(),
3838 }
3839 }
3840
3841 pub fn offset(&mut self, delta: f64) {
3842 match self {
3843 ViewOffset::Static(offset) => *offset += delta,
3844 ViewOffset::Animation(anim) => anim.offset(delta),
3845 ViewOffset::Gesture(gesture) => {
3846 gesture.stationary_view_offset += delta;
3847 gesture.delta_from_tracker += delta;
3848 gesture.current_view_offset += delta;
3849 }
3850 }
3851 }
3852
3853 pub fn cancel_gesture(&mut self) {
3854 if let ViewOffset::Gesture(gesture) = self {
3855 *self = ViewOffset::Static(gesture.current_view_offset);
3856 }
3857 }
3858
3859 pub fn stop_anim_and_gesture(&mut self) {
3860 *self = ViewOffset::Static(self.current());
3861 }
3862}
3863
3864impl ViewGesture {
3865 fn animate_from(&mut self, from: f64, clock: Clock, config: niri_config::Animation) {
3866 let current = self.animation.as_ref().map_or(0., Animation::value);
3867 self.animation = Some(Animation::new(clock, from + current, 0., 0., config));
3868 }
3869}
3870
3871impl ColumnData {
3872 pub fn new<W: LayoutElement>(column: &Column<W>) -> Self {
3873 let mut rv = Self { width: 0. };
3874 rv.update(column);
3875 rv
3876 }
3877
3878 pub fn update<W: LayoutElement>(&mut self, column: &Column<W>) {
3879 self.width = column.width();
3880 }
3881}
3882
3883impl TileData {
3884 pub fn new<W: LayoutElement>(tile: &Tile<W>, height: WindowHeight) -> Self {
3885 let mut rv = Self {
3886 height,
3887 size: Size::default(),
3888 interactively_resizing_by_left_edge: false,
3889 };
3890 rv.update(tile);
3891 rv
3892 }
3893
3894 pub fn update<W: LayoutElement>(&mut self, tile: &Tile<W>) {
3895 self.size = tile.tile_size();
3896 self.interactively_resizing_by_left_edge = tile
3897 .window()
3898 .interactive_resize_data()
3899 .is_some_and(|data| data.edges.contains(ResizeEdge::LEFT));
3900 }
3901}
3902
3903impl From<PresetSize> for ColumnWidth {
3904 fn from(value: PresetSize) -> Self {
3905 match value {
3906 PresetSize::Proportion(p) => Self::Proportion(p.clamp(0., 10000.)),
3907 PresetSize::Fixed(f) => Self::Fixed(f64::from(f.clamp(1, 100000))),
3908 }
3909 }
3910}
3911
3912impl WindowHeight {
3913 const fn auto_1() -> Self {
3914 Self::Auto { weight: 1. }
3915 }
3916}
3917
3918impl<W: LayoutElement> Column<W> {
3919 #[allow(clippy::too_many_arguments)]
3920 fn new_with_tile(
3921 tile: Tile<W>,
3922 view_size: Size<f64, Logical>,
3923 working_area: Rectangle<f64, Logical>,
3924 parent_area: Rectangle<f64, Logical>,
3925 scale: f64,
3926 width: ColumnWidth,
3927 is_full_width: bool,
3928 ) -> Self {
3929 let options = tile.options.clone();
3930
3931 let display_mode = tile
3932 .window()
3933 .rules()
3934 .default_column_display
3935 .unwrap_or(options.layout.default_column_display);
3936
3937 let mut rv = Self {
3938 tiles: vec![],
3939 data: vec![],
3940 active_tile_idx: 0,
3941 width,
3942 preset_width_idx: None,
3943 is_full_width,
3944 is_pending_maximized: false,
3945 is_pending_fullscreen: false,
3946 display_mode,
3947 tab_indicator: TabIndicator::new(options.layout.tab_indicator),
3948 move_animation: None,
3949 view_size,
3950 working_area,
3951 parent_area,
3952 scale,
3953 clock: tile.clock.clone(),
3954 options,
3955 };
3956
3957 let pending_sizing_mode = tile.window().pending_sizing_mode();
3958
3959 rv.add_tile_at(0, tile);
3960
3961 match pending_sizing_mode {
3962 SizingMode::Normal => (),
3963 SizingMode::Maximized => rv.set_maximized(true),
3964 SizingMode::Fullscreen => rv.set_fullscreen(true),
3965 }
3966
3967 // Animate the tab indicator for new columns.
3968 if display_mode == ColumnDisplay::Tabbed
3969 && !rv.options.layout.tab_indicator.hide_when_single_tab
3970 && rv.sizing_mode().is_normal()
3971 {
3972 // Usually new columns are created together with window movement actions. For new
3973 // windows, we handle that in start_open_animation().
3974 rv.tab_indicator
3975 .start_open_animation(rv.clock.clone(), rv.options.animations.window_movement.0);
3976 }
3977
3978 rv
3979 }
3980
3981 fn update_config(
3982 &mut self,
3983 view_size: Size<f64, Logical>,
3984 working_area: Rectangle<f64, Logical>,
3985 parent_area: Rectangle<f64, Logical>,
3986 scale: f64,
3987 options: Rc<Options>,
3988 ) {
3989 let mut update_sizes = false;
3990
3991 if self.view_size != view_size
3992 || self.working_area != working_area
3993 || self.parent_area != parent_area
3994 {
3995 update_sizes = true;
3996 }
3997
3998 // If preset widths changed, clear our stored preset index.
3999 if self.options.layout.preset_column_widths != options.layout.preset_column_widths {
4000 self.preset_width_idx = None;
4001 }
4002
4003 // If preset heights changed, make our heights non-preset.
4004 if self.options.layout.preset_window_heights != options.layout.preset_window_heights {
4005 self.convert_heights_to_auto();
4006 update_sizes = true;
4007 }
4008
4009 if self.options.layout.gaps != options.layout.gaps {
4010 update_sizes = true;
4011 }
4012
4013 if self.options.layout.border.off != options.layout.border.off
4014 || self.options.layout.border.width != options.layout.border.width
4015 {
4016 update_sizes = true;
4017 }
4018
4019 if self.options.layout.tab_indicator != options.layout.tab_indicator {
4020 update_sizes = true;
4021 }
4022
4023 for (tile, data) in zip(&mut self.tiles, &mut self.data) {
4024 tile.update_config(view_size, scale, options.clone());
4025 data.update(tile);
4026 }
4027
4028 self.tab_indicator
4029 .update_config(options.layout.tab_indicator);
4030 self.view_size = view_size;
4031 self.working_area = working_area;
4032 self.parent_area = parent_area;
4033 self.scale = scale;
4034 self.options = options;
4035
4036 if update_sizes {
4037 self.update_tile_sizes(false);
4038 }
4039 }
4040
4041 pub fn advance_animations(&mut self) {
4042 if let Some(move_) = &mut self.move_animation {
4043 if move_.anim.is_done() {
4044 self.move_animation = None;
4045 }
4046 }
4047
4048 for tile in &mut self.tiles {
4049 tile.advance_animations();
4050 }
4051
4052 self.tab_indicator.advance_animations();
4053 }
4054
4055 pub fn are_animations_ongoing(&self) -> bool {
4056 self.move_animation.is_some()
4057 || self.tab_indicator.are_animations_ongoing()
4058 || self.tiles.iter().any(Tile::are_animations_ongoing)
4059 }
4060
4061 pub fn are_transitions_ongoing(&self) -> bool {
4062 self.move_animation.is_some()
4063 || self.tab_indicator.are_animations_ongoing()
4064 || self.tiles.iter().any(Tile::are_transitions_ongoing)
4065 }
4066
4067 pub fn update_render_elements(&mut self, is_active: bool, view_rect: Rectangle<f64, Logical>) {
4068 let active_idx = self.active_tile_idx;
4069 for (tile_idx, (tile, tile_off)) in self.tiles_mut().enumerate() {
4070 let is_active = is_active && tile_idx == active_idx;
4071
4072 let mut tile_view_rect = view_rect;
4073 tile_view_rect.loc -= tile_off + tile.render_offset();
4074 tile.update_render_elements(is_active, tile_view_rect);
4075 }
4076
4077 let config = self.tab_indicator.config();
4078 let offsets = self.tile_offsets_iter(self.data.iter().copied());
4079 let tabs = zip(&self.tiles, offsets)
4080 .enumerate()
4081 .map(|(tile_idx, (tile, tile_off))| {
4082 let is_active = tile_idx == active_idx;
4083 let is_urgent = tile.window().is_urgent();
4084 let tile_pos = tile_off + tile.render_offset();
4085 TabInfo::from_tile(tile, tile_pos, is_active, is_urgent, &config)
4086 });
4087
4088 // Hide the tab indicator in fullscreen. If you have it configured to overlap the window,
4089 // you don't want that to happen in fullscreen. Also, laying things out correctly when the
4090 // tab indicator is within the column and the column goes fullscreen, would require too
4091 // many changes to the code for too little benefit (it's mostly invisible anyway).
4092 let enabled = self.display_mode == ColumnDisplay::Tabbed && self.sizing_mode().is_normal();
4093
4094 self.tab_indicator.update_render_elements(
4095 enabled,
4096 self.tab_indicator_area(),
4097 view_rect,
4098 self.tiles.len(),
4099 tabs,
4100 is_active,
4101 self.scale,
4102 );
4103 }
4104
4105 pub fn is_pending_fullscreen(&self) -> bool {
4106 self.is_pending_fullscreen
4107 }
4108
4109 pub fn is_pending_maximized(&self) -> bool {
4110 self.is_pending_maximized
4111 }
4112
4113 pub fn pending_sizing_mode(&self) -> SizingMode {
4114 if self.is_pending_fullscreen {
4115 SizingMode::Fullscreen
4116 } else if self.is_pending_maximized {
4117 SizingMode::Maximized
4118 } else {
4119 SizingMode::Normal
4120 }
4121 }
4122
4123 pub fn render_offset(&self) -> Point<f64, Logical> {
4124 let mut offset = Point::from((0., 0.));
4125
4126 if let Some(move_) = &self.move_animation {
4127 offset.x += move_.from * move_.anim.value();
4128 }
4129
4130 offset
4131 }
4132
4133 pub fn animate_move_from(&mut self, from_x_offset: f64) {
4134 self.animate_move_from_with_config(
4135 from_x_offset,
4136 self.options.animations.window_movement.0,
4137 );
4138 }
4139
4140 pub fn animate_move_from_with_config(
4141 &mut self,
4142 from_x_offset: f64,
4143 config: niri_config::Animation,
4144 ) {
4145 let current_offset = self
4146 .move_animation
4147 .as_ref()
4148 .map_or(0., |move_| move_.from * move_.anim.value());
4149
4150 let anim = Animation::new(self.clock.clone(), 1., 0., 0., config);
4151 self.move_animation = Some(MoveAnimation {
4152 anim,
4153 from: from_x_offset + current_offset,
4154 });
4155 }
4156
4157 pub fn offset_move_anim_current(&mut self, offset: f64) {
4158 if let Some(move_) = self.move_animation.as_mut() {
4159 // If the anim is almost done, there's little point trying to offset it; we can let
4160 // things jump. If it turns out like a bad idea, we could restart the anim instead.
4161 let value = move_.anim.value();
4162 if value > 0.001 {
4163 move_.from += offset / value;
4164 }
4165 }
4166 }
4167
4168 /// Returns whether this column is currently fullscreen.
4169 ///
4170 /// As in, if it contains one currently-fullscreen tile, or in tabbed mode, if it contains at
4171 /// least one currently-fullscreen tile.
4172 ///
4173 /// This will lag behind is_pending_fullscreen, depending on when the tiles actually respond to
4174 /// the un/fullscreen request. But, it's possible for is_fullscreen() to flip instantly, for
4175 /// example when consuming a fullscreen tile into a non-pending-fullscreen column.
4176 ///
4177 /// This controls things like:
4178 ///
4179 /// - whether the column draws at the top of the screen or at the start of the working area
4180 /// - whether the column draws above the top layer-shell layer
4181 /// - whether the tab indicator is shown
4182 /// - restoring view_offset_before_fullscreen
4183 ///
4184 /// Edge cases to watch out for:
4185 ///
4186 /// - Consuming a fullscreen tile into a non-tabbed column will keep that tile fullscreen until
4187 /// it responds to the unfullscreen request. This tile may be anywhere in the column,
4188 /// including at the active position.
4189 ///
4190 /// - Changing a fullscreen tabbed column into normal mode is an easy way to get randomly
4191 /// delayed unfullscreening tiles in a normal column.
4192 ///
4193 /// - is_fullscreen() can suddenly change when consuming/expelling a fullscreen tile into/from a
4194 /// non-fullscreen column. This can influence the code that saves/restores the unfullscreen
4195 /// view offset.
4196 fn sizing_mode(&self) -> SizingMode {
4197 // Behaviors that we want:
4198 //
4199 // 1. The common case: single tile in a column. Assume no animations. Fullscreening the tile
4200 // should make it jump to the top-left of the screen only when the tile finishes
4201 // fullscreening. Similarly, unfullscreening should keep it at the top-left until the
4202 // tile had unfullscreened.
4203 //
4204 // 2. Unfullscreening a tabbed column with multiple tiles should restore the view offset
4205 // correctly. This means waiting for *all* tiles to unfullscreen, because otherwise the
4206 // restored view offset will immediately get overwritted by the still screen-wide column
4207 // (it uses the largest tile's width).
4208 //
4209 // 3. Changing a fullscreen tabbed column to normal should probably also restore the view
4210 // offset correctly. Same problem as above, but now for normal columns (since display
4211 // mode change applies instantly).
4212 //
4213 // The logic that satisfies these behaviors is to check if *any* tile is fullscreen.
4214 let mut any_fullscreen = false;
4215 let mut any_maximized = false;
4216 for tile in &self.tiles {
4217 match tile.sizing_mode() {
4218 SizingMode::Normal => (),
4219 SizingMode::Maximized => any_maximized = true,
4220 SizingMode::Fullscreen => any_fullscreen = true,
4221 }
4222 }
4223
4224 if any_fullscreen {
4225 SizingMode::Fullscreen
4226 } else if any_maximized {
4227 SizingMode::Maximized
4228 } else {
4229 SizingMode::Normal
4230 }
4231 }
4232
4233 pub fn contains(&self, window: &W::Id) -> bool {
4234 self.tiles
4235 .iter()
4236 .map(Tile::window)
4237 .any(|win| win.id() == window)
4238 }
4239
4240 pub fn position(&self, window: &W::Id) -> Option<usize> {
4241 self.tiles
4242 .iter()
4243 .map(Tile::window)
4244 .position(|win| win.id() == window)
4245 }
4246
4247 fn activate_idx(&mut self, idx: usize) -> bool {
4248 if self.active_tile_idx == idx {
4249 return false;
4250 }
4251
4252 self.active_tile_idx = idx;
4253
4254 self.tiles[idx].ensure_alpha_animates_to_1();
4255
4256 true
4257 }
4258
4259 fn activate_window(&mut self, window: &W::Id) {
4260 let idx = self.position(window).unwrap();
4261 self.activate_idx(idx);
4262 }
4263
4264 fn add_tile_at(&mut self, idx: usize, mut tile: Tile<W>) {
4265 tile.update_config(self.view_size, self.scale, self.options.clone());
4266
4267 // Inserting a tile pushes down all tiles below it, but also in always-centering mode it
4268 // will affect the X position of all tiles in the column.
4269 let mut prev_offsets = Vec::with_capacity(self.tiles.len() + 1);
4270 prev_offsets.extend(self.tile_offsets().take(self.tiles.len()));
4271
4272 if self.display_mode != ColumnDisplay::Tabbed {
4273 self.is_pending_fullscreen = false;
4274 self.is_pending_maximized = false;
4275 }
4276
4277 self.data
4278 .insert(idx, TileData::new(&tile, WindowHeight::auto_1()));
4279 self.tiles.insert(idx, tile);
4280 self.update_tile_sizes(true);
4281
4282 // Animate tiles according to the offset changes.
4283 prev_offsets.insert(idx, Point::default());
4284 for (i, ((tile, offset), prev)) in zip(self.tiles_mut(), prev_offsets).enumerate() {
4285 if i == idx {
4286 continue;
4287 }
4288
4289 tile.animate_move_from(prev - offset);
4290 }
4291 }
4292
4293 fn update_window(&mut self, window: &W::Id) {
4294 let (tile_idx, tile) = self
4295 .tiles
4296 .iter_mut()
4297 .enumerate()
4298 .find(|(_, tile)| tile.window().id() == window)
4299 .unwrap();
4300
4301 let prev_height = self.data[tile_idx].size.h;
4302
4303 tile.update_window();
4304 self.data[tile_idx].update(tile);
4305
4306 let offset = prev_height - self.data[tile_idx].size.h;
4307
4308 let is_tabbed = self.display_mode == ColumnDisplay::Tabbed;
4309
4310 // Move windows below in tandem with resizing.
4311 //
4312 // FIXME: in always-centering mode, window resizing will affect the offsets of all other
4313 // windows in the column, so they should all be animated. How should this interact with
4314 // animated vs. non-animated resizes? For example, an animated +20 resize followed by two
4315 // non-animated -10 resizes.
4316 if !is_tabbed && offset != 0. {
4317 if tile.resize_animation().is_some() {
4318 // If there's a resize animation (that may have just started in
4319 // tile.update_window()), then the apparent size change is smooth with no sudden
4320 // jumps. This corresponds to adding an Y animation to tiles below.
4321 for tile in &mut self.tiles[tile_idx + 1..] {
4322 tile.animate_move_y_from_with_config(
4323 offset,
4324 self.options.animations.window_resize.anim,
4325 );
4326 }
4327 } else {
4328 // There's no resize animation, but the offset is nonzero. This could happen for
4329 // example:
4330 // - if the window resized on its own, which we don't animate
4331 // - if the window resized by less than 10 px (the resize threshold)
4332 //
4333 // The latter case could also cancel an ongoing resize animation.
4334 //
4335 // Now, stationary tiles below shouldn't react to this offset change in any way,
4336 // i.e. their apparent Y position should jump together with the resize. However,
4337 // tiles below that are already animating an Y movement should offset their
4338 // animations to avoid the jump.
4339 //
4340 // Notably, this is necessary to fix the animation jump when resizing height back
4341 // and forth in quick succession (in a way that cancels the resize animation).
4342 for tile in &mut self.tiles[tile_idx + 1..] {
4343 tile.offset_move_y_anim_current(offset);
4344 }
4345 }
4346 }
4347 }
4348
4349 /// Extra size taken up by elements in the column such as the tab indicator.
4350 fn extra_size(&self) -> Size<f64, Logical> {
4351 if self.display_mode == ColumnDisplay::Tabbed {
4352 self.tab_indicator.extra_size(self.tiles.len(), self.scale)
4353 } else {
4354 Size::from((0., 0.))
4355 }
4356 }
4357
4358 fn resolve_preset_width(&self, preset: PresetSize) -> ResolvedSize {
4359 let extra = self.extra_size();
4360 resolve_preset_size(preset, &self.options, self.working_area.size.w, extra.w)
4361 }
4362
4363 fn resolve_preset_height(&self, preset: PresetSize) -> ResolvedSize {
4364 let extra = self.extra_size();
4365 resolve_preset_size(preset, &self.options, self.working_area.size.h, extra.h)
4366 }
4367
4368 fn resolve_column_width(&self, width: ColumnWidth) -> f64 {
4369 let working_size = self.working_area.size;
4370 let gaps = self.options.layout.gaps;
4371 let extra = self.extra_size();
4372
4373 match width {
4374 ColumnWidth::Proportion(proportion) => {
4375 (working_size.w - gaps) * proportion - gaps - extra.w
4376 }
4377 ColumnWidth::Fixed(width) => width,
4378 }
4379 }
4380
4381 fn update_tile_sizes(&mut self, animate: bool) {
4382 self.update_tile_sizes_with_transaction(animate, Transaction::new());
4383 }
4384
4385 fn update_tile_sizes_with_transaction(&mut self, animate: bool, transaction: Transaction) {
4386 let sizing_mode = self.pending_sizing_mode();
4387 if matches!(sizing_mode, SizingMode::Fullscreen | SizingMode::Maximized) {
4388 for (tile_idx, tile) in self.tiles.iter_mut().enumerate() {
4389 // In tabbed mode, only the visible window participates in the transaction.
4390 let is_active = tile_idx == self.active_tile_idx;
4391 let transaction = if self.display_mode == ColumnDisplay::Tabbed && !is_active {
4392 None
4393 } else {
4394 Some(transaction.clone())
4395 };
4396
4397 if matches!(sizing_mode, SizingMode::Fullscreen) {
4398 tile.request_fullscreen(animate, transaction);
4399 } else {
4400 tile.request_maximized(self.parent_area.size, animate, transaction);
4401 }
4402 }
4403 return;
4404 }
4405
4406 let is_tabbed = self.display_mode == ColumnDisplay::Tabbed;
4407
4408 let min_size: Vec<_> = self
4409 .tiles
4410 .iter()
4411 .map(Tile::min_size_nonfullscreen)
4412 .map(|mut size| {
4413 size.w = size.w.max(1.);
4414 size.h = size.h.max(1.);
4415 size
4416 })
4417 .collect();
4418 let max_size: Vec<_> = self
4419 .tiles
4420 .iter()
4421 .map(Tile::max_size_nonfullscreen)
4422 .collect();
4423
4424 // Compute the column width.
4425 let min_width = min_size
4426 .iter()
4427 .map(|size| NotNan::new(size.w).unwrap())
4428 .max()
4429 .map(NotNan::into_inner)
4430 .unwrap();
4431 let max_width = max_size
4432 .iter()
4433 .filter_map(|size| {
4434 let w = size.w;
4435 if w == 0. {
4436 None
4437 } else {
4438 Some(NotNan::new(w).unwrap())
4439 }
4440 })
4441 .min()
4442 .map(NotNan::into_inner)
4443 .unwrap_or(f64::from(i32::MAX));
4444 let max_width = f64::max(max_width, min_width);
4445
4446 let width = if self.is_full_width {
4447 ColumnWidth::Proportion(1.)
4448 } else {
4449 self.width
4450 };
4451
4452 let working_size = self.working_area.size;
4453 let extra_size = self.extra_size();
4454
4455 let width = self.resolve_column_width(width);
4456 let width = f64::max(f64::min(width, max_width), min_width);
4457 let max_tile_height = working_size.h - self.options.layout.gaps * 2. - extra_size.h;
4458
4459 // If there are multiple windows in a column, clamp the non-auto window's height according
4460 // to other windows' min sizes.
4461 let mut max_non_auto_window_height = None;
4462 if self.tiles.len() > 1 && !is_tabbed {
4463 if let Some(non_auto_idx) = self
4464 .data
4465 .iter()
4466 .position(|data| !matches!(data.height, WindowHeight::Auto { .. }))
4467 {
4468 let min_height_taken = min_size
4469 .iter()
4470 .enumerate()
4471 .filter(|(idx, _)| *idx != non_auto_idx)
4472 .map(|(_, min_size)| min_size.h + self.options.layout.gaps)
4473 .sum::<f64>();
4474
4475 let tile = &self.tiles[non_auto_idx];
4476 let height_left = max_tile_height - min_height_taken;
4477 max_non_auto_window_height = Some(f64::max(
4478 1.,
4479 tile.window_height_for_tile_height(height_left).round(),
4480 ));
4481 }
4482 }
4483
4484 // Compute the tile heights. Start by converting window heights to tile heights.
4485 let mut heights = zip(&self.tiles, &self.data)
4486 .map(|(tile, data)| match data.height {
4487 auto @ WindowHeight::Auto { .. } => auto,
4488 WindowHeight::Fixed(height) => {
4489 let mut window_height = height.round().max(1.);
4490 if let Some(max) = max_non_auto_window_height {
4491 window_height = f64::min(window_height, max);
4492 } else {
4493 // In any case, clamp to the working area height.
4494 let max = tile.window_height_for_tile_height(max_tile_height).round();
4495 window_height = f64::min(window_height, max);
4496 }
4497
4498 WindowHeight::Fixed(tile.tile_height_for_window_height(window_height))
4499 }
4500 WindowHeight::Preset(idx) => {
4501 let preset = self.options.layout.preset_window_heights[idx];
4502 let window_height = match self.resolve_preset_height(preset) {
4503 ResolvedSize::Tile(h) => tile.window_height_for_tile_height(h),
4504 ResolvedSize::Window(h) => h,
4505 };
4506
4507 let mut window_height = window_height.round().clamp(1., 100000.);
4508 if let Some(max) = max_non_auto_window_height {
4509 window_height = f64::min(window_height, max);
4510 }
4511
4512 let tile_height = tile.tile_height_for_window_height(window_height);
4513 WindowHeight::Fixed(tile_height)
4514 }
4515 })
4516 .collect::<Vec<_>>();
4517
4518 // In tabbed display mode, fill fixed heights right away.
4519 if is_tabbed {
4520 // All tiles have the same height, equal to the height of the only fixed tile (if any).
4521 let tabbed_height = heights
4522 .iter()
4523 .find_map(|h| {
4524 if let WindowHeight::Fixed(h) = h {
4525 Some(*h)
4526 } else {
4527 None
4528 }
4529 })
4530 .unwrap_or(max_tile_height);
4531
4532 // We also take min height of all tabs into account.
4533 let min_height = min_size
4534 .iter()
4535 .map(|size| NotNan::new(size.h).unwrap())
4536 .max()
4537 .map(NotNan::into_inner)
4538 .unwrap();
4539 // But, if there's a larger-than-workspace tab, we don't want to force all tabs to that
4540 // size.
4541 let min_height = f64::min(max_tile_height, min_height);
4542 let tabbed_height = f64::max(tabbed_height, min_height);
4543
4544 heights.fill(WindowHeight::Fixed(tabbed_height));
4545
4546 // The following logic will apply individual min/max height, etc.
4547 }
4548
4549 let gaps_left = self.options.layout.gaps * (self.tiles.len() + 1) as f64;
4550 let mut height_left = working_size.h - gaps_left;
4551 let mut auto_tiles_left = self.tiles.len();
4552
4553 // Subtract all fixed-height tiles.
4554 for (h, (min_size, max_size)) in zip(&mut heights, zip(&min_size, &max_size)) {
4555 // Check if the tile has an exact height constraint.
4556 if min_size.h == max_size.h {
4557 *h = WindowHeight::Fixed(min_size.h);
4558 }
4559
4560 if let WindowHeight::Fixed(h) = h {
4561 if max_size.h > 0. {
4562 *h = f64::min(*h, max_size.h);
4563 }
4564 *h = f64::max(*h, min_size.h);
4565
4566 height_left -= *h;
4567 auto_tiles_left -= 1;
4568 }
4569 }
4570
4571 let mut total_weight: f64 = heights
4572 .iter()
4573 .filter_map(|h| {
4574 if let WindowHeight::Auto { weight } = *h {
4575 Some(weight)
4576 } else {
4577 None
4578 }
4579 })
4580 .sum();
4581
4582 // Iteratively try to distribute the remaining height, checking against tile min heights.
4583 // Pick an auto height according to the current sizes, then check if it satisfies all
4584 // remaining min heights. If not, allocate fixed height to those tiles and repeat the
4585 // loop. On each iteration the auto height will get smaller.
4586 //
4587 // NOTE: we do not respect max height here. Doing so would complicate things: if the current
4588 // auto height is above some tile's max height, then the auto height can become larger.
4589 // Combining this with the min height loop is where the complexity appears.
4590 //
4591 // However, most max height uses are for fixed-size dialogs, where min height == max_height.
4592 // This case is separately handled above.
4593 'outer: while auto_tiles_left > 0 {
4594 // Wayland requires us to round the requested size for a window to integer logical
4595 // pixels, therefore we compute the remaining auto height dynamically.
4596 let mut height_left_2 = height_left;
4597 let mut total_weight_2 = total_weight;
4598 for ((h, tile), min_size) in zip(zip(&mut heights, &self.tiles), &min_size) {
4599 let weight = match *h {
4600 WindowHeight::Auto { weight } => weight,
4601 WindowHeight::Fixed(_) => continue,
4602 WindowHeight::Preset(_) => unreachable!(),
4603 };
4604 let factor = weight / total_weight_2;
4605
4606 // Compute the current auto height.
4607 let mut auto = height_left_2 * factor;
4608
4609 // Check if the auto height satisfies the min height.
4610 if min_size.h > auto {
4611 auto = min_size.h;
4612 *h = WindowHeight::Fixed(auto);
4613 height_left -= auto;
4614 total_weight -= weight;
4615 auto_tiles_left -= 1;
4616
4617 // If a min height was unsatisfied, then we allocate the tile more than the
4618 // auto height, which means that the remaining auto tiles now have less height
4619 // to work with, and the loop must run again.
4620 //
4621 // If we keep going in this loop and break out later, we may allocate less
4622 // height to the subsequent tiles than would be available next iteration and
4623 // potentially trip their min height check earlier than necessary, leading to
4624 // visible snapping.
4625 continue 'outer;
4626 }
4627
4628 auto = tile.tile_height_for_window_height(
4629 tile.window_height_for_tile_height(auto).round().max(1.),
4630 );
4631
4632 height_left_2 -= auto;
4633 total_weight_2 -= weight;
4634 }
4635
4636 // All min heights were satisfied, fill them in.
4637 for (h, tile) in zip(&mut heights, &self.tiles) {
4638 let weight = match *h {
4639 WindowHeight::Auto { weight } => weight,
4640 WindowHeight::Fixed(_) => continue,
4641 WindowHeight::Preset(_) => unreachable!(),
4642 };
4643 let factor = weight / total_weight;
4644
4645 // Compute the current auto height.
4646 let auto = height_left * factor;
4647 let auto = tile.tile_height_for_window_height(
4648 tile.window_height_for_tile_height(auto).round().max(1.),
4649 );
4650
4651 *h = WindowHeight::Fixed(auto);
4652 height_left -= auto;
4653 total_weight -= weight;
4654 auto_tiles_left -= 1;
4655 }
4656
4657 assert_eq!(auto_tiles_left, 0);
4658 }
4659
4660 for (tile_idx, (tile, h)) in zip(&mut self.tiles, heights).enumerate() {
4661 let WindowHeight::Fixed(height) = h else {
4662 unreachable!()
4663 };
4664
4665 let size = Size::from((width, height));
4666
4667 // In tabbed mode, only the visible window participates in the transaction.
4668 let is_active = tile_idx == self.active_tile_idx;
4669 let transaction = if self.display_mode == ColumnDisplay::Tabbed && !is_active {
4670 None
4671 } else {
4672 Some(transaction.clone())
4673 };
4674
4675 tile.request_tile_size(size, animate, transaction);
4676 }
4677 }
4678
4679 fn width(&self) -> f64 {
4680 let mut tiles_width = self
4681 .data
4682 .iter()
4683 .map(|data| NotNan::new(data.size.w).unwrap())
4684 .max()
4685 .map(NotNan::into_inner)
4686 .unwrap();
4687
4688 if self.display_mode == ColumnDisplay::Tabbed && self.sizing_mode().is_normal() {
4689 let extra_size = self.tab_indicator.extra_size(self.tiles.len(), self.scale);
4690 tiles_width += extra_size.w;
4691 }
4692
4693 tiles_width
4694 }
4695
4696 fn focus_index(&mut self, index: u8) {
4697 let idx = min(usize::from(index.saturating_sub(1)), self.tiles.len() - 1);
4698 self.activate_idx(idx);
4699 }
4700
4701 fn focus_up(&mut self) -> bool {
4702 self.activate_idx(self.active_tile_idx.saturating_sub(1))
4703 }
4704
4705 fn focus_down(&mut self) -> bool {
4706 self.activate_idx(min(self.active_tile_idx + 1, self.tiles.len() - 1))
4707 }
4708
4709 fn focus_top(&mut self) {
4710 self.activate_idx(0);
4711 }
4712
4713 fn focus_bottom(&mut self) {
4714 self.activate_idx(self.tiles.len() - 1);
4715 }
4716
4717 fn move_up(&mut self) -> bool {
4718 let new_idx = self.active_tile_idx.saturating_sub(1);
4719 if self.active_tile_idx == new_idx {
4720 return false;
4721 }
4722
4723 let mut ys = self.tile_offsets().skip(self.active_tile_idx);
4724 let active_y = ys.next().unwrap().y;
4725 let next_y = ys.next().unwrap().y;
4726 drop(ys);
4727
4728 self.tiles.swap(self.active_tile_idx, new_idx);
4729 self.data.swap(self.active_tile_idx, new_idx);
4730 self.active_tile_idx = new_idx;
4731
4732 // Animate the movement.
4733 let new_active_y = self.tile_offset(new_idx).y;
4734 self.tiles[new_idx].animate_move_y_from(active_y - new_active_y);
4735 self.tiles[new_idx + 1].animate_move_y_from(active_y - next_y);
4736
4737 true
4738 }
4739
4740 fn move_down(&mut self) -> bool {
4741 let new_idx = min(self.active_tile_idx + 1, self.tiles.len() - 1);
4742 if self.active_tile_idx == new_idx {
4743 return false;
4744 }
4745
4746 let mut ys = self.tile_offsets().skip(self.active_tile_idx);
4747 let active_y = ys.next().unwrap().y;
4748 let next_y = ys.next().unwrap().y;
4749 drop(ys);
4750
4751 self.tiles.swap(self.active_tile_idx, new_idx);
4752 self.data.swap(self.active_tile_idx, new_idx);
4753 self.active_tile_idx = new_idx;
4754
4755 // Animate the movement.
4756 let new_active_y = self.tile_offset(new_idx).y;
4757 self.tiles[new_idx].animate_move_y_from(active_y - new_active_y);
4758 self.tiles[new_idx - 1].animate_move_y_from(next_y - active_y);
4759
4760 true
4761 }
4762
4763 fn toggle_width(&mut self, tile_idx: Option<usize>, forwards: bool) {
4764 let tile_idx = tile_idx.unwrap_or(self.active_tile_idx);
4765
4766 let preset_idx = if self.is_full_width || self.is_pending_maximized {
4767 None
4768 } else {
4769 self.preset_width_idx
4770 };
4771
4772 let len = self.options.layout.preset_column_widths.len();
4773 let preset_idx = if let Some(idx) = preset_idx {
4774 (idx + if forwards { 1 } else { len - 1 }) % len
4775 } else {
4776 let tile = &self.tiles[tile_idx];
4777 let current_window = tile.window_expected_or_current_size().w;
4778 let current_tile = tile.tile_expected_or_current_size().w;
4779
4780 let mut it = self
4781 .options
4782 .layout
4783 .preset_column_widths
4784 .iter()
4785 .map(|preset| self.resolve_preset_width(*preset));
4786
4787 if forwards {
4788 it.position(|resolved| {
4789 match resolved {
4790 // Some allowance for fractional scaling purposes.
4791 ResolvedSize::Tile(resolved) => current_tile + 1. < resolved,
4792 ResolvedSize::Window(resolved) => current_window + 1. < resolved,
4793 }
4794 })
4795 .unwrap_or(0)
4796 } else {
4797 it.rposition(|resolved| {
4798 match resolved {
4799 // Some allowance for fractional scaling purposes.
4800 ResolvedSize::Tile(resolved) => resolved + 1. < current_tile,
4801 ResolvedSize::Window(resolved) => resolved + 1. < current_window,
4802 }
4803 })
4804 .unwrap_or(len - 1)
4805 }
4806 };
4807
4808 let preset = self.options.layout.preset_column_widths[preset_idx];
4809 self.set_column_width(SizeChange::from(preset), Some(tile_idx), true);
4810
4811 self.preset_width_idx = Some(preset_idx);
4812 }
4813
4814 fn toggle_full_width(&mut self) {
4815 if self.is_pending_maximized {
4816 // Treat it as unmaximize.
4817 self.is_pending_maximized = false;
4818 self.is_full_width = false;
4819 } else {
4820 self.is_full_width = !self.is_full_width;
4821 }
4822
4823 self.update_tile_sizes(true);
4824 }
4825
4826 fn set_column_width(&mut self, change: SizeChange, tile_idx: Option<usize>, animate: bool) {
4827 let current = if self.is_full_width || self.is_pending_maximized {
4828 ColumnWidth::Proportion(1.)
4829 } else {
4830 self.width
4831 };
4832
4833 let current_px = self.resolve_column_width(current);
4834
4835 // FIXME: fix overflows then remove limits.
4836 const MAX_PX: f64 = 100000.;
4837 const MAX_F: f64 = 10000.;
4838
4839 let width = match (current, change) {
4840 (_, SizeChange::SetFixed(fixed)) => {
4841 // As a special case, setting a fixed column width will compute it in such a way
4842 // that the specified (usually active) window gets that width. This is the
4843 // intention behind the ability to set a fixed size.
4844 let tile_idx = tile_idx.unwrap_or(self.active_tile_idx);
4845 let tile = &self.tiles[tile_idx];
4846 ColumnWidth::Fixed(
4847 tile.tile_width_for_window_width(f64::from(fixed))
4848 .clamp(1., MAX_PX),
4849 )
4850 }
4851 (_, SizeChange::SetProportion(proportion)) => {
4852 ColumnWidth::Proportion((proportion / 100.).clamp(0., MAX_F))
4853 }
4854 (_, SizeChange::AdjustFixed(delta)) => {
4855 let width = (current_px + f64::from(delta)).clamp(1., MAX_PX);
4856 ColumnWidth::Fixed(width)
4857 }
4858 (ColumnWidth::Proportion(current), SizeChange::AdjustProportion(delta)) => {
4859 let proportion = (current + delta / 100.).clamp(0., MAX_F);
4860 ColumnWidth::Proportion(proportion)
4861 }
4862 (ColumnWidth::Fixed(_), SizeChange::AdjustProportion(delta)) => {
4863 let full = self.working_area.size.w - self.options.layout.gaps;
4864 let current = if full == 0. {
4865 1.
4866 } else {
4867 (current_px + self.options.layout.gaps + self.extra_size().w) / full
4868 };
4869 let proportion = (current + delta / 100.).clamp(0., MAX_F);
4870 ColumnWidth::Proportion(proportion)
4871 }
4872 };
4873
4874 self.width = width;
4875 self.preset_width_idx = None;
4876 self.is_full_width = false;
4877 self.is_pending_maximized = false;
4878 self.update_tile_sizes(animate);
4879 }
4880
4881 fn set_window_height(&mut self, change: SizeChange, tile_idx: Option<usize>, animate: bool) {
4882 let tile_idx = tile_idx.unwrap_or(self.active_tile_idx);
4883
4884 // Start by converting all heights to automatic, since only one window in the column can be
4885 // non-auto-height. If the current tile is already non-auto, however, we can skip that
4886 // step. Which is not only for optimization, but also preserves automatic weights in case
4887 // one window is resized in such a way that other windows hit their min size, and then
4888 // back.
4889 if matches!(self.data[tile_idx].height, WindowHeight::Auto { .. }) {
4890 self.convert_heights_to_auto();
4891 }
4892
4893 let current = self.data[tile_idx].height;
4894 let tile = &self.tiles[tile_idx];
4895 let current_window_px = match current {
4896 WindowHeight::Auto { .. } | WindowHeight::Preset(_) => tile.window_size().h,
4897 WindowHeight::Fixed(height) => height,
4898 };
4899 let current_tile_px = tile.tile_height_for_window_height(current_window_px);
4900
4901 let working_size = self.working_area.size.h;
4902 let gaps = self.options.layout.gaps;
4903 let extra_size = self.extra_size().h;
4904 let full = working_size - gaps;
4905 let current_prop = if full == 0. {
4906 1.
4907 } else {
4908 (current_tile_px + gaps) / full
4909 };
4910
4911 // FIXME: fix overflows then remove limits.
4912 const MAX_PX: f64 = 100000.;
4913
4914 let mut window_height = match change {
4915 SizeChange::SetFixed(fixed) => f64::from(fixed),
4916 SizeChange::SetProportion(proportion) => {
4917 let tile_height = (working_size - gaps) * (proportion / 100.) - gaps - extra_size;
4918 tile.window_height_for_tile_height(tile_height)
4919 }
4920 SizeChange::AdjustFixed(delta) => current_window_px + f64::from(delta),
4921 SizeChange::AdjustProportion(delta) => {
4922 let proportion = current_prop + delta / 100.;
4923 let tile_height = (working_size - gaps) * proportion - gaps - extra_size;
4924 tile.window_height_for_tile_height(tile_height)
4925 }
4926 };
4927
4928 // Clamp the height according to other windows' min sizes, or simply to working area height.
4929 let min_height_taken = if self.display_mode == ColumnDisplay::Tabbed {
4930 0.
4931 } else {
4932 self.tiles
4933 .iter()
4934 .enumerate()
4935 .filter(|(idx, _)| *idx != tile_idx)
4936 .map(|(_, tile)| f64::max(1., tile.min_size_nonfullscreen().h) + gaps)
4937 .sum::<f64>()
4938 };
4939 let height_left = working_size - extra_size - gaps - min_height_taken - gaps;
4940 let height_left = f64::max(1., tile.window_height_for_tile_height(height_left));
4941 window_height = f64::min(height_left, window_height);
4942
4943 // Clamp it against the window height constraints.
4944 let win = &self.tiles[tile_idx].window();
4945 let min_h = win.min_size().h;
4946 let max_h = win.max_size().h;
4947
4948 if max_h > 0 {
4949 window_height = f64::min(window_height, f64::from(max_h));
4950 }
4951 if min_h > 0 {
4952 window_height = f64::max(window_height, f64::from(min_h));
4953 }
4954
4955 self.data[tile_idx].height = WindowHeight::Fixed(window_height.clamp(1., MAX_PX));
4956 self.is_pending_maximized = false;
4957 self.update_tile_sizes(animate);
4958 }
4959
4960 fn reset_window_height(&mut self, tile_idx: Option<usize>) {
4961 if self.display_mode == ColumnDisplay::Tabbed {
4962 // When tabbed, reset window height should work on any window, not just the fixed-size
4963 // one.
4964 for data in &mut self.data {
4965 data.height = WindowHeight::auto_1();
4966 }
4967 } else {
4968 let tile_idx = tile_idx.unwrap_or(self.active_tile_idx);
4969 self.data[tile_idx].height = WindowHeight::auto_1();
4970 }
4971
4972 self.update_tile_sizes(true);
4973 }
4974
4975 fn toggle_window_height(&mut self, tile_idx: Option<usize>, forwards: bool) {
4976 let tile_idx = tile_idx.unwrap_or(self.active_tile_idx);
4977
4978 // Start by converting all heights to automatic, since only one window in the column can be
4979 // non-auto-height. If the current tile is already non-auto, however, we can skip that
4980 // step. Which is not only for optimization, but also preserves automatic weights in case
4981 // one window is resized in such a way that other windows hit their min size, and then
4982 // back.
4983 if matches!(self.data[tile_idx].height, WindowHeight::Auto { .. }) {
4984 self.convert_heights_to_auto();
4985 }
4986
4987 let len = self.options.layout.preset_window_heights.len();
4988 let preset_idx = match self.data[tile_idx].height {
4989 WindowHeight::Preset(idx) if !self.is_pending_maximized => {
4990 (idx + if forwards { 1 } else { len - 1 }) % len
4991 }
4992 _ => {
4993 let current = self.data[tile_idx].size.h;
4994 let tile = &self.tiles[tile_idx];
4995
4996 let mut it = self
4997 .options
4998 .layout
4999 .preset_window_heights
5000 .iter()
5001 .copied()
5002 .map(|preset| {
5003 let window_height = match self.resolve_preset_height(preset) {
5004 ResolvedSize::Tile(h) => tile.window_height_for_tile_height(h),
5005 ResolvedSize::Window(h) => h,
5006 };
5007 tile.tile_height_for_window_height(window_height.round().clamp(1., 100000.))
5008 });
5009
5010 if forwards {
5011 it.position(|resolved| {
5012 // Some allowance for fractional scaling purposes.
5013 current + 1. < resolved
5014 })
5015 .unwrap_or(0)
5016 } else {
5017 it.rposition(|resolved| {
5018 // Some allowance for fractional scaling purposes.
5019 resolved + 1. < current
5020 })
5021 .unwrap_or(len - 1)
5022 }
5023 }
5024 };
5025 self.data[tile_idx].height = WindowHeight::Preset(preset_idx);
5026 self.is_pending_maximized = false;
5027 self.update_tile_sizes(true);
5028 }
5029
5030 /// Converts all heights in the column to automatic, preserving the apparent heights.
5031 ///
5032 /// All weights are recomputed to preserve the current tile heights while "centering" the
5033 /// weights at the median window height (it gets weight = 1).
5034 ///
5035 /// One case where apparent heights will not be preserved is when the column is taller than the
5036 /// working area.
5037 fn convert_heights_to_auto(&mut self) {
5038 let heights: Vec<_> = self.tiles.iter().map(|tile| tile.tile_size().h).collect();
5039
5040 // Weights are invariant to multiplication: a column with weights 2, 2, 1 is equivalent to
5041 // a column with weights 4, 4, 2. So we find the median window height and use that as 1.
5042 let mut sorted = heights.clone();
5043 sorted.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
5044 let median = sorted[sorted.len() / 2];
5045
5046 for (data, height) in zip(&mut self.data, heights) {
5047 let weight = height / median;
5048 data.height = WindowHeight::Auto { weight };
5049 }
5050 }
5051
5052 fn set_fullscreen(&mut self, is_fullscreen: bool) {
5053 if self.is_pending_fullscreen == is_fullscreen {
5054 return;
5055 }
5056
5057 if is_fullscreen {
5058 assert!(self.tiles.len() == 1 || self.display_mode == ColumnDisplay::Tabbed);
5059 }
5060
5061 self.is_pending_fullscreen = is_fullscreen;
5062 self.update_tile_sizes(true);
5063 }
5064
5065 fn set_maximized(&mut self, maximize: bool) {
5066 if self.is_pending_maximized == maximize {
5067 return;
5068 }
5069
5070 if maximize {
5071 assert!(self.tiles.len() == 1 || self.display_mode == ColumnDisplay::Tabbed);
5072 }
5073
5074 self.is_pending_maximized = maximize;
5075 self.update_tile_sizes(true);
5076 }
5077
5078 fn set_column_display(&mut self, display: ColumnDisplay) {
5079 if self.display_mode == display {
5080 return;
5081 }
5082
5083 // Animate the movement.
5084 //
5085 // We're doing some shortcuts here because we know that currently normal vs. tabbed can
5086 // only cause a vertical shift + a shift to the origin.
5087 //
5088 // Doing it this way to avoid storing all tile positions in a vector. If more display modes
5089 // are added it might be simpler to just collect everything into a smallvec.
5090 let prev_origin = self.tiles_origin();
5091 self.display_mode = display;
5092 let new_origin = self.tiles_origin();
5093 let origin_delta = prev_origin - new_origin;
5094
5095 // When need to walk the tiles in the normal display mode to get the right offsets.
5096 self.display_mode = ColumnDisplay::Normal;
5097 for (tile, pos) in self.tiles_mut() {
5098 let mut y_delta = pos.y - prev_origin.y;
5099
5100 // Invert the Y motion when transitioning *to* normal display mode.
5101 if display == ColumnDisplay::Normal {
5102 y_delta *= -1.;
5103 }
5104
5105 let mut delta = origin_delta;
5106 delta.y += y_delta;
5107 tile.animate_move_from(delta);
5108 }
5109
5110 // Animate the opacity.
5111 for (idx, tile) in self.tiles.iter_mut().enumerate() {
5112 let is_active = idx == self.active_tile_idx;
5113 if !is_active {
5114 let (from, to) = if display == ColumnDisplay::Tabbed {
5115 (1., 0.)
5116 } else {
5117 (0., 1.)
5118 };
5119 tile.animate_alpha(from, to, self.options.animations.window_movement.0);
5120 }
5121 }
5122
5123 // Animate the appearance of the tab indicator.
5124 if display == ColumnDisplay::Tabbed {
5125 self.tab_indicator.start_open_animation(
5126 self.clock.clone(),
5127 self.options.animations.window_movement.0,
5128 );
5129 }
5130
5131 // Now switch the display mode for real.
5132 self.display_mode = display;
5133 self.update_tile_sizes(true);
5134 }
5135
5136 fn tiles_origin(&self) -> Point<f64, Logical> {
5137 let mut origin = Point::from((0., 0.));
5138
5139 match self.sizing_mode() {
5140 SizingMode::Normal => (),
5141 SizingMode::Maximized => {
5142 origin.y += self.parent_area.loc.y;
5143 return origin;
5144 }
5145 SizingMode::Fullscreen => return origin,
5146 }
5147
5148 origin.y += self.working_area.loc.y + self.options.layout.gaps;
5149
5150 if self.display_mode == ColumnDisplay::Tabbed {
5151 origin += self
5152 .tab_indicator
5153 .content_offset(self.tiles.len(), self.scale);
5154 }
5155
5156 origin
5157 }
5158
5159 // HACK: pass a self.data iterator in manually as a workaround for the lack of method partial
5160 // borrowing. Note that this method's return value does not borrow the entire &Self!
5161 fn tile_offsets_iter(
5162 &self,
5163 data: impl Iterator<Item = TileData>,
5164 ) -> impl Iterator<Item = Point<f64, Logical>> {
5165 // FIXME: this should take into account always-center-single-column, which means that
5166 // Column should somehow know when it is being centered due to being the single column on
5167 // the workspace or some other reason.
5168 let center = self.options.layout.center_focused_column == CenterFocusedColumn::Always;
5169 let gaps = self.options.layout.gaps;
5170 let tabbed = self.display_mode == ColumnDisplay::Tabbed;
5171
5172 // Does not include extra size from the tab indicator.
5173 let tiles_width = self
5174 .data
5175 .iter()
5176 .map(|data| NotNan::new(data.size.w).unwrap())
5177 .max()
5178 .map(NotNan::into_inner)
5179 .unwrap_or(0.);
5180
5181 let mut origin = self.tiles_origin();
5182
5183 // Chain with a dummy value to be able to get one past all tiles' Y.
5184 let dummy = TileData {
5185 height: WindowHeight::auto_1(),
5186 size: Size::default(),
5187 interactively_resizing_by_left_edge: false,
5188 };
5189 let data = data.chain(iter::once(dummy));
5190
5191 data.map(move |data| {
5192 let mut pos = origin;
5193
5194 if center {
5195 pos.x += (tiles_width - data.size.w) / 2.;
5196 } else if data.interactively_resizing_by_left_edge {
5197 pos.x += tiles_width - data.size.w;
5198 }
5199
5200 if !tabbed {
5201 origin.y += data.size.h + gaps;
5202 }
5203
5204 pos
5205 })
5206 }
5207
5208 fn tile_offsets(&self) -> impl Iterator<Item = Point<f64, Logical>> + '_ {
5209 self.tile_offsets_iter(self.data.iter().copied())
5210 }
5211
5212 fn tile_offset(&self, tile_idx: usize) -> Point<f64, Logical> {
5213 self.tile_offsets().nth(tile_idx).unwrap()
5214 }
5215
5216 fn tile_offsets_in_render_order(
5217 &self,
5218 data: impl Iterator<Item = TileData>,
5219 ) -> impl Iterator<Item = Point<f64, Logical>> {
5220 let active_idx = self.active_tile_idx;
5221 let active_pos = self.tile_offset(active_idx);
5222 let offsets = self
5223 .tile_offsets_iter(data)
5224 .enumerate()
5225 .filter_map(move |(idx, pos)| (idx != active_idx).then_some(pos));
5226 iter::once(active_pos).chain(offsets)
5227 }
5228
5229 pub fn tiles(&self) -> impl Iterator<Item = (&Tile<W>, Point<f64, Logical>)> + '_ {
5230 let offsets = self.tile_offsets_iter(self.data.iter().copied());
5231 zip(&self.tiles, offsets)
5232 }
5233
5234 fn tiles_mut(&mut self) -> impl Iterator<Item = (&mut Tile<W>, Point<f64, Logical>)> + '_ {
5235 let offsets = self.tile_offsets_iter(self.data.iter().copied());
5236 zip(&mut self.tiles, offsets)
5237 }
5238
5239 fn tiles_in_render_order(
5240 &self,
5241 ) -> impl Iterator<Item = (&Tile<W>, Point<f64, Logical>, bool)> + '_ {
5242 let offsets = self.tile_offsets_in_render_order(self.data.iter().copied());
5243
5244 let (first, rest) = self.tiles.split_at(self.active_tile_idx);
5245 let (active, rest) = rest.split_at(1);
5246
5247 let active = active.iter().map(|tile| (tile, true));
5248
5249 let rest_visible = self.display_mode != ColumnDisplay::Tabbed;
5250 let rest = first.iter().chain(rest);
5251 let rest = rest.map(move |tile| (tile, rest_visible));
5252
5253 let tiles = active.chain(rest);
5254 zip(tiles, offsets).map(|((tile, visible), pos)| (tile, pos, visible))
5255 }
5256
5257 fn tiles_in_render_order_mut(
5258 &mut self,
5259 ) -> impl Iterator<Item = (&mut Tile<W>, Point<f64, Logical>)> + '_ {
5260 let offsets = self.tile_offsets_in_render_order(self.data.iter().copied());
5261
5262 let (first, rest) = self.tiles.split_at_mut(self.active_tile_idx);
5263 let (active, rest) = rest.split_at_mut(1);
5264
5265 let tiles = active.iter_mut().chain(first).chain(rest);
5266 zip(tiles, offsets)
5267 }
5268
5269 fn tab_indicator_area(&self) -> Rectangle<f64, Logical> {
5270 // We'd like to use the active tile's animated size for the tab indicator, however we need
5271 // to be mindful of the case where the active tile is smaller than some other tile in the
5272 // column. The column assumes the size of the largest tile.
5273 //
5274 // We expect users to mainly resize tabbed columns by width, so matching the animated size
5275 // is more important here. Besides, we always try to resize all windows in a column to the
5276 // same width when possible, and also the animation for going into tabbed mode doesn't move
5277 // tiles horizontally as much.
5278 //
5279 // For height though, it's a different story. First, users probably aren't resizing a
5280 // tabbed column by height. Second, we don't match windows by height, so it's easy to have
5281 // a smaller active tile than the rest of the column, e.g. by adding a fixed-size dialog.
5282 // Then, switching to that dialog and back should ideally keep the tab indicator position
5283 // fixed. Third, the animation for making a column tabbed moves tiles vertically, and using
5284 // the active tile's animated size in this case only works for the topmost tile, and looks
5285 // broken otherwise.
5286 let mut max_height = 0.;
5287 for tile in &self.tiles {
5288 max_height = f64::max(max_height, tile.tile_size().h);
5289 }
5290
5291 let tile = &self.tiles[self.active_tile_idx];
5292 let area_size = Size::from((tile.animated_tile_size().w, max_height));
5293
5294 Rectangle::new(self.tiles_origin(), area_size)
5295 }
5296
5297 pub fn start_open_animation(&mut self, id: &W::Id) -> bool {
5298 for tile in &mut self.tiles {
5299 if tile.window().id() == id {
5300 tile.start_open_animation();
5301
5302 // Animate the appearance of the tab indicator.
5303 if self.display_mode == ColumnDisplay::Tabbed
5304 && self.sizing_mode().is_normal()
5305 && self.tiles.len() == 1
5306 && !self.tab_indicator.config().hide_when_single_tab
5307 {
5308 self.tab_indicator.start_open_animation(
5309 self.clock.clone(),
5310 self.options.animations.window_open.anim,
5311 );
5312 }
5313
5314 return true;
5315 }
5316 }
5317
5318 false
5319 }
5320
5321 #[cfg(test)]
5322 fn verify_invariants(&self) {
5323 assert!(!self.tiles.is_empty(), "columns can't be empty");
5324 assert!(self.active_tile_idx < self.tiles.len());
5325 assert_eq!(self.tiles.len(), self.data.len());
5326
5327 if !self.pending_sizing_mode().is_normal() {
5328 assert!(self.tiles.len() == 1 || self.display_mode == ColumnDisplay::Tabbed);
5329 }
5330
5331 if let Some(idx) = self.preset_width_idx {
5332 assert!(idx < self.options.layout.preset_column_widths.len());
5333 }
5334
5335 let is_tabbed = self.display_mode == ColumnDisplay::Tabbed;
5336
5337 let tile_count = self.tiles.len();
5338 if tile_count == 1 {
5339 if let WindowHeight::Auto { weight } = self.data[0].height {
5340 assert_eq!(
5341 weight, 1.,
5342 "auto height weight must reset to 1 for a single window"
5343 );
5344 }
5345 }
5346
5347 let working_size = self.working_area.size;
5348 let extra_size = self.extra_size();
5349 let gaps = self.options.layout.gaps;
5350
5351 let mut found_fixed = false;
5352 let mut total_height = 0.;
5353 let mut total_min_height = 0.;
5354 for (tile, data) in zip(&self.tiles, &self.data) {
5355 assert!(Rc::ptr_eq(&self.options, &tile.options));
5356 assert_eq!(self.clock, tile.clock);
5357 assert_eq!(self.scale, tile.scale());
5358 assert_eq!(
5359 self.pending_sizing_mode(),
5360 tile.window().pending_sizing_mode()
5361 );
5362 assert_eq!(self.view_size, tile.view_size());
5363 tile.verify_invariants();
5364
5365 let mut data2 = *data;
5366 data2.update(tile);
5367 assert_eq!(data, &data2, "tile data must be up to date");
5368
5369 if matches!(data.height, WindowHeight::Fixed(_)) {
5370 assert!(
5371 !found_fixed,
5372 "there can only be one fixed-height window in a column"
5373 );
5374 found_fixed = true;
5375 }
5376
5377 if let WindowHeight::Preset(idx) = data.height {
5378 assert!(self.options.layout.preset_window_heights.len() > idx);
5379 }
5380
5381 let requested_size = tile.window().requested_size().unwrap();
5382 let requested_tile_height =
5383 tile.tile_height_for_window_height(f64::from(requested_size.h));
5384 let min_tile_height = f64::max(1., tile.min_size_nonfullscreen().h);
5385
5386 if self.pending_sizing_mode().is_normal()
5387 && self.scale.round() == self.scale
5388 && working_size.h.round() == working_size.h
5389 && gaps.round() == gaps
5390 {
5391 let total_height = requested_tile_height + gaps * 2. + extra_size.h;
5392 let total_min_height = min_tile_height + gaps * 2. + extra_size.h;
5393 let max_height = f64::max(total_min_height, working_size.h);
5394 assert!(
5395 total_height <= max_height,
5396 "each tile in a column mustn't go beyond working area height \
5397 (tile height {total_height} > max height {max_height})"
5398 );
5399 }
5400
5401 total_height += requested_tile_height;
5402 total_min_height += min_tile_height;
5403 }
5404
5405 if !is_tabbed
5406 && tile_count > 1
5407 && self.scale.round() == self.scale
5408 && working_size.h.round() == working_size.h
5409 && gaps.round() == gaps
5410 {
5411 total_height += gaps * (tile_count + 1) as f64 + extra_size.h;
5412 total_min_height += gaps * (tile_count + 1) as f64 + extra_size.h;
5413 let max_height = f64::max(total_min_height, working_size.h);
5414 assert!(
5415 total_height <= max_height,
5416 "multiple tiles in a column mustn't go beyond working area height \
5417 (total height {total_height} > max height {max_height})"
5418 );
5419 }
5420 }
5421}
5422
5423fn compute_new_view_offset(
5424 cur_x: f64,
5425 view_width: f64,
5426 new_col_x: f64,
5427 new_col_width: f64,
5428 gaps: f64,
5429) -> f64 {
5430 // If the column is wider than the view, always left-align it.
5431 if view_width <= new_col_width {
5432 return 0.;
5433 }
5434
5435 // Compute the padding in case it needs to be smaller due to large tile width.
5436 let padding = ((view_width - new_col_width) / 2.).clamp(0., gaps);
5437
5438 // Compute the desired new X with padding.
5439 let new_x = new_col_x - padding;
5440 let new_right_x = new_col_x + new_col_width + padding;
5441
5442 // If the column is already fully visible, leave the view as is.
5443 if cur_x <= new_x && new_right_x <= cur_x + view_width {
5444 return -(new_col_x - cur_x);
5445 }
5446
5447 // Otherwise, prefer the alignment that results in less motion from the current position.
5448 let dist_to_left = (cur_x - new_x).abs();
5449 let dist_to_right = ((cur_x + view_width) - new_right_x).abs();
5450 if dist_to_left <= dist_to_right {
5451 -padding
5452 } else {
5453 -(view_width - padding - new_col_width)
5454 }
5455}
5456
5457fn compute_working_area(
5458 parent_area: Rectangle<f64, Logical>,
5459 scale: f64,
5460 struts: Struts,
5461) -> Rectangle<f64, Logical> {
5462 let mut working_area = parent_area;
5463
5464 // Add struts.
5465 working_area.size.w = f64::max(0., working_area.size.w - struts.left.0 - struts.right.0);
5466 working_area.loc.x += struts.left.0;
5467
5468 working_area.size.h = f64::max(0., working_area.size.h - struts.top.0 - struts.bottom.0);
5469 working_area.loc.y += struts.top.0;
5470
5471 // Round location to start at a physical pixel.
5472 let loc = working_area
5473 .loc
5474 .to_physical_precise_ceil(scale)
5475 .to_logical(scale);
5476
5477 let mut size_diff = (loc - working_area.loc).to_size();
5478 size_diff.w = f64::min(working_area.size.w, size_diff.w);
5479 size_diff.h = f64::min(working_area.size.h, size_diff.h);
5480
5481 working_area.size -= size_diff;
5482 working_area.loc = loc;
5483
5484 working_area
5485}
5486
5487fn compute_toplevel_bounds(
5488 border_config: niri_config::Border,
5489 working_area_size: Size<f64, Logical>,
5490 extra_size: Size<f64, Logical>,
5491 gaps: f64,
5492) -> Size<i32, Logical> {
5493 let mut border = 0.;
5494 if !border_config.off {
5495 border = border_config.width * 2.;
5496 }
5497
5498 Size::from((
5499 f64::max(working_area_size.w - gaps * 2. - extra_size.w - border, 1.),
5500 f64::max(working_area_size.h - gaps * 2. - extra_size.h - border, 1.),
5501 ))
5502 .to_i32_floor()
5503}
5504
5505fn cancel_resize_for_column<W: LayoutElement>(
5506 interactive_resize: &mut Option<InteractiveResize<W>>,
5507 column: &mut Column<W>,
5508) {
5509 if let Some(resize) = interactive_resize {
5510 if column.contains(&resize.window) {
5511 *interactive_resize = None;
5512 }
5513 }
5514
5515 for tile in &mut column.tiles {
5516 tile.window_mut().cancel_interactive_resize();
5517 }
5518}
5519
5520fn resolve_preset_size(
5521 preset: PresetSize,
5522 options: &Options,
5523 view_size: f64,
5524 extra_size: f64,
5525) -> ResolvedSize {
5526 match preset {
5527 PresetSize::Proportion(proportion) => ResolvedSize::Tile(
5528 (view_size - options.layout.gaps) * proportion - options.layout.gaps - extra_size,
5529 ),
5530 PresetSize::Fixed(width) => ResolvedSize::Window(f64::from(width)),
5531 }
5532}
5533
5534#[cfg(test)]
5535mod tests {
5536 use niri_config::FloatOrInt;
5537
5538 use super::*;
5539 use crate::utils::round_logical_in_physical;
5540
5541 #[test]
5542 fn working_area_starts_at_physical_pixel() {
5543 let struts = Struts {
5544 left: FloatOrInt(0.5),
5545 right: FloatOrInt(1.),
5546 top: FloatOrInt(0.75),
5547 bottom: FloatOrInt(1.),
5548 };
5549
5550 let parent_area = Rectangle::from_size(Size::from((1280., 720.)));
5551 let area = compute_working_area(parent_area, 1., struts);
5552
5553 assert_eq!(round_logical_in_physical(1., area.loc.x), area.loc.x);
5554 assert_eq!(round_logical_in_physical(1., area.loc.y), area.loc.y);
5555 }
5556
5557 #[test]
5558 fn large_fractional_strut() {
5559 let struts = Struts {
5560 left: FloatOrInt(0.),
5561 right: FloatOrInt(0.),
5562 top: FloatOrInt(50000.5),
5563 bottom: FloatOrInt(0.),
5564 };
5565
5566 let parent_area = Rectangle::from_size(Size::from((1280., 720.)));
5567 compute_working_area(parent_area, 1., struts);
5568 }
5569}