forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBdde9214Ivan Molodetskikh1 year ago1835 commits

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