forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

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