forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB90ef202Ivan Molodetskikh1 year ago2349 commits

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