forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB99bf2dfIvan Molodetskikh1 year ago2106 commits

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