forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBad3847fIvan Molodetskikh1 year ago2457 commits

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