forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBf51dd67Ivan Molodetskikh2 years ago981 commits

workspace.rs2795 lines, 93.2 KiBHistoryRawDownload
1use std::cmp::{max, min};
2use std::iter::{self, zip};
3use std::rc::Rc;
4use std::time::Duration;
5
6use niri_config::{CenterFocusedColumn, PresetWidth, Struts};
7use niri_ipc::SizeChange;
8use smithay::backend::renderer::gles::GlesRenderer;
9use smithay::desktop::{layer_map_for_output, Window};
10use smithay::output::Output;
11use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
12use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
13use smithay::utils::{Logical, Point, Rectangle, Scale, Size};
14use smithay::wayland::compositor::send_surface_state;
15
16use super::closing_window::{ClosingWindow, ClosingWindowRenderElement};
17use super::tile::{Tile, TileRenderElement};
18use super::{LayoutElement, Options};
19use crate::animation::Animation;
20use crate::niri_render_elements;
21use crate::render_helpers::renderer::NiriRenderer;
22use crate::render_helpers::RenderTarget;
23use crate::swipe_tracker::SwipeTracker;
24use crate::utils::id::IdCounter;
25use crate::utils::output_size;
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#[derive(Debug)]
31pub struct Workspace<W: LayoutElement> {
32 /// The original output of this workspace.
33 ///
34 /// Most of the time this will be the workspace's current output, however, after an output
35 /// disconnection, it may remain pointing to the disconnected output.
36 pub original_output: OutputId,
37
38 /// Current output of this workspace.
39 output: Option<Output>,
40
41 /// Latest known view size for this workspace.
42 ///
43 /// This should be computed from the current workspace output size, or, if all outputs have
44 /// been disconnected, preserved until a new output is connected.
45 view_size: Size<i32, Logical>,
46
47 /// Latest known working area for this workspace.
48 ///
49 /// This is similar to view size, but takes into account things like layer shell exclusive
50 /// zones.
51 working_area: Rectangle<i32, Logical>,
52
53 /// Columns of windows on this workspace.
54 pub columns: Vec<Column<W>>,
55
56 /// Index of the currently active column, if any.
57 pub active_column_idx: usize,
58
59 /// Offset of the view computed from the active column.
60 ///
61 /// Any gaps, including left padding from work area left exclusive zone, is handled
62 /// with this view offset (rather than added as a constant elsewhere in the code). This allows
63 /// for natural handling of fullscreen windows, which must ignore work area padding.
64 view_offset: i32,
65
66 /// Adjustment of the view offset, if one is currently ongoing.
67 view_offset_adj: Option<ViewOffsetAdjustment>,
68
69 /// Whether to activate the previous, rather than the next, column upon column removal.
70 ///
71 /// When a new column is created and removed with no focus changes in-between, it is more
72 /// natural to activate the previously-focused column. This variable tracks that.
73 ///
74 /// Since we only create-and-activate columns immediately to the right of the active column (in
75 /// contrast to tabs in Firefox, for example), we can track this as a bool, rather than an
76 /// index of the previous column to activate.
77 ///
78 /// The value is the view offset that the previous column had before, to restore it.
79 activate_prev_column_on_removal: Option<i32>,
80
81 /// View offset to restore after unfullscreening.
82 view_offset_before_fullscreen: Option<i32>,
83
84 /// Windows in the closing animation.
85 closing_windows: Vec<ClosingWindow>,
86
87 /// Configurable properties of the layout.
88 pub options: Rc<Options>,
89
90 /// Unique ID of this workspace.
91 id: WorkspaceId,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct OutputId(String);
96
97static WORKSPACE_ID_COUNTER: IdCounter = IdCounter::new();
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100pub struct WorkspaceId(u32);
101
102impl WorkspaceId {
103 fn next() -> WorkspaceId {
104 WorkspaceId(WORKSPACE_ID_COUNTER.next())
105 }
106}
107
108niri_render_elements! {
109 WorkspaceRenderElement<R> => {
110 Tile = TileRenderElement<R>,
111 ClosingWindow = ClosingWindowRenderElement,
112 }
113}
114
115#[derive(Debug)]
116enum ViewOffsetAdjustment {
117 Animation(Animation),
118 Gesture(ViewGesture),
119}
120
121#[derive(Debug)]
122struct ViewGesture {
123 current_view_offset: f64,
124 tracker: SwipeTracker,
125 delta_from_tracker: f64,
126 // The view offset we'll use if needed for activate_prev_column_on_removal.
127 static_view_offset: i32,
128}
129
130/// Width of a column.
131#[derive(Debug, Clone, Copy, PartialEq)]
132pub enum ColumnWidth {
133 /// Proportion of the current view width.
134 Proportion(f64),
135 /// One of the proportion presets.
136 ///
137 /// This is separate from Proportion in order to be able to reliably cycle between preset
138 /// proportions.
139 Preset(usize),
140 /// Fixed width in logical pixels.
141 Fixed(i32),
142}
143
144/// Height of a window in a column.
145///
146/// Proportional height is intentionally omitted. With column widths you frequently want e.g. two
147/// columns side-by-side with 50% width each, and you want them to remain this way when moving to a
148/// differently sized monitor. Windows in a column, however, already auto-size to fill the available
149/// height, giving you this behavior. The only reason to set a different window height, then, is
150/// when you want something in the window to fit exactly, e.g. to fit 30 lines in a terminal, which
151/// corresponds to the `Fixed` variant.
152///
153/// This does not preclude the usual set of binds to set or resize a window proportionally. Just,
154/// they are converted to, and stored as fixed height right away, so that once you resize a window
155/// to fit the desired content, it can never become smaller than that when moving between monitors.
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub enum WindowHeight {
158 /// Automatically computed height, evenly distributed across the column.
159 Auto,
160 /// Fixed height in logical pixels.
161 Fixed(i32),
162}
163
164#[derive(Debug)]
165pub struct Column<W: LayoutElement> {
166 /// Tiles in this column.
167 ///
168 /// Must be non-empty.
169 pub tiles: Vec<Tile<W>>,
170
171 /// Heights of the windows.
172 ///
173 /// Must have the same number of elements as `tiles`.
174 ///
175 /// These heights are window heights, not tile heights, so they exclude tile decorations.
176 heights: Vec<WindowHeight>,
177
178 /// Index of the currently active tile.
179 pub active_tile_idx: usize,
180
181 /// Desired width of this column.
182 ///
183 /// If the column is full-width or full-screened, this is the width that should be restored
184 /// upon unfullscreening and untoggling full-width.
185 pub width: ColumnWidth,
186
187 /// Whether this column is full-width.
188 pub is_full_width: bool,
189
190 /// Whether this column contains a single full-screened window.
191 pub is_fullscreen: bool,
192
193 /// Animation of the render offset during window swapping.
194 move_animation: Option<Animation>,
195
196 /// Width right before a resize animation on one of the windows of the column.
197 pub width_before_resize: Option<i32>,
198
199 /// Latest known view size for this column's workspace.
200 view_size: Size<i32, Logical>,
201
202 /// Latest known working area for this column's workspace.
203 working_area: Rectangle<i32, Logical>,
204
205 /// Configurable properties of the layout.
206 options: Rc<Options>,
207}
208
209impl OutputId {
210 pub fn new(output: &Output) -> Self {
211 Self(output.name())
212 }
213}
214
215impl ViewOffsetAdjustment {
216 pub fn is_animation(&self) -> bool {
217 matches!(self, Self::Animation(_))
218 }
219
220 pub fn target_view_offset(&self) -> f64 {
221 match self {
222 ViewOffsetAdjustment::Animation(anim) => anim.to(),
223 ViewOffsetAdjustment::Gesture(gesture) => gesture.current_view_offset,
224 }
225 }
226}
227
228impl ColumnWidth {
229 fn resolve(self, options: &Options, view_width: i32) -> i32 {
230 match self {
231 ColumnWidth::Proportion(proportion) => {
232 ((view_width - options.gaps) as f64 * proportion).floor() as i32 - options.gaps
233 }
234 ColumnWidth::Preset(idx) => options.preset_widths[idx].resolve(options, view_width),
235 ColumnWidth::Fixed(width) => width,
236 }
237 }
238}
239
240impl From<PresetWidth> for ColumnWidth {
241 fn from(value: PresetWidth) -> Self {
242 match value {
243 PresetWidth::Proportion(p) => Self::Proportion(p.clamp(0., 10000.)),
244 PresetWidth::Fixed(f) => Self::Fixed(f.clamp(1, 100000)),
245 }
246 }
247}
248
249impl<W: LayoutElement> Workspace<W> {
250 pub fn new(output: Output, options: Rc<Options>) -> Self {
251 let working_area = compute_working_area(&output, options.struts);
252 Self {
253 original_output: OutputId::new(&output),
254 view_size: output_size(&output),
255 working_area,
256 output: Some(output),
257 columns: vec![],
258 active_column_idx: 0,
259 view_offset: 0,
260 view_offset_adj: None,
261 activate_prev_column_on_removal: None,
262 view_offset_before_fullscreen: None,
263 closing_windows: vec![],
264 options,
265 id: WorkspaceId::next(),
266 }
267 }
268
269 pub fn new_no_outputs(options: Rc<Options>) -> Self {
270 Self {
271 output: None,
272 original_output: OutputId(String::new()),
273 view_size: Size::from((1280, 720)),
274 working_area: Rectangle::from_loc_and_size((0, 0), (1280, 720)),
275 columns: vec![],
276 active_column_idx: 0,
277 view_offset: 0,
278 view_offset_adj: None,
279 activate_prev_column_on_removal: None,
280 view_offset_before_fullscreen: None,
281 closing_windows: vec![],
282 options,
283 id: WorkspaceId::next(),
284 }
285 }
286
287 pub fn id(&self) -> WorkspaceId {
288 self.id
289 }
290
291 pub fn advance_animations(&mut self, current_time: Duration, is_active: bool) {
292 if let Some(ViewOffsetAdjustment::Animation(anim)) = &mut self.view_offset_adj {
293 anim.set_current_time(current_time);
294 self.view_offset = anim.value().round() as i32;
295 if anim.is_done() {
296 self.view_offset_adj = None;
297 }
298 } else if let Some(ViewOffsetAdjustment::Gesture(gesture)) = &self.view_offset_adj {
299 self.view_offset = gesture.current_view_offset.round() as i32;
300 }
301
302 for (col_idx, col) in self.columns.iter_mut().enumerate() {
303 let is_active = is_active && col_idx == self.active_column_idx;
304 col.advance_animations(current_time, is_active);
305 }
306
307 self.closing_windows.retain_mut(|closing| {
308 closing.advance_animations(current_time);
309 closing.are_animations_ongoing()
310 });
311 }
312
313 pub fn are_animations_ongoing(&self) -> bool {
314 self.view_offset_adj
315 .as_ref()
316 .is_some_and(|s| s.is_animation())
317 || self.columns.iter().any(Column::are_animations_ongoing)
318 || !self.closing_windows.is_empty()
319 }
320
321 pub fn are_transitions_ongoing(&self) -> bool {
322 self.view_offset_adj.is_some()
323 || self.columns.iter().any(Column::are_animations_ongoing)
324 || !self.closing_windows.is_empty()
325 }
326
327 pub fn update_config(&mut self, options: Rc<Options>) {
328 for column in &mut self.columns {
329 column.update_config(options.clone());
330 }
331
332 self.options = options;
333 }
334
335 pub fn windows(&self) -> impl Iterator<Item = &W> + '_ {
336 self.columns
337 .iter()
338 .flat_map(|col| col.tiles.iter())
339 .map(Tile::window)
340 }
341
342 pub fn windows_mut(&mut self) -> impl Iterator<Item = &mut W> + '_ {
343 self.columns
344 .iter_mut()
345 .flat_map(|col| col.tiles.iter_mut())
346 .map(Tile::window_mut)
347 }
348
349 pub fn set_output(&mut self, output: Option<Output>) {
350 if self.output == output {
351 return;
352 }
353
354 if let Some(output) = self.output.take() {
355 for win in self.windows() {
356 win.output_leave(&output);
357 }
358 }
359
360 self.output = output;
361
362 if let Some(output) = &self.output {
363 let working_area = compute_working_area(output, self.options.struts);
364 self.set_view_size(output_size(output), working_area);
365
366 for win in self.windows() {
367 self.enter_output_for_window(win);
368 }
369 }
370 }
371
372 fn enter_output_for_window(&self, window: &W) {
373 if let Some(output) = &self.output {
374 set_preferred_scale_transform(window, output);
375 window.output_enter(output);
376 }
377 }
378
379 pub fn set_view_size(
380 &mut self,
381 size: Size<i32, Logical>,
382 working_area: Rectangle<i32, Logical>,
383 ) {
384 if self.view_size == size && self.working_area == working_area {
385 return;
386 }
387
388 self.view_size = size;
389 self.working_area = working_area;
390
391 for col in &mut self.columns {
392 col.set_view_size(self.view_size, self.working_area);
393 }
394 }
395
396 pub fn view_size(&self) -> Size<i32, Logical> {
397 self.view_size
398 }
399
400 pub fn update_output_scale_transform(&mut self) {
401 let Some(output) = self.output.as_ref() else {
402 return;
403 };
404 for window in self.windows() {
405 set_preferred_scale_transform(window, output);
406 }
407 }
408
409 fn toplevel_bounds(&self) -> Size<i32, Logical> {
410 let mut border = 0;
411 if !self.options.border.off {
412 border = self.options.border.width as i32 * 2;
413 }
414
415 Size::from((
416 max(self.working_area.size.w - self.options.gaps * 2 - border, 1),
417 max(self.working_area.size.h - self.options.gaps * 2 - border, 1),
418 ))
419 }
420
421 pub fn resolve_default_width(
422 &self,
423 default_width: Option<Option<ColumnWidth>>,
424 ) -> Option<ColumnWidth> {
425 match default_width {
426 Some(Some(width)) => Some(width),
427 Some(None) => None,
428 None => self.options.default_width,
429 }
430 }
431
432 pub fn new_window_size(&self, width: Option<ColumnWidth>) -> Size<i32, Logical> {
433 let width = if let Some(width) = width {
434 let is_fixed = matches!(width, ColumnWidth::Fixed(_));
435
436 let mut width = width.resolve(&self.options, self.working_area.size.w);
437
438 if !is_fixed && !self.options.border.off {
439 width -= self.options.border.width as i32 * 2;
440 }
441
442 max(1, width)
443 } else {
444 0
445 };
446
447 let mut height = self.working_area.size.h - self.options.gaps * 2;
448 if !self.options.border.off {
449 height -= self.options.border.width as i32 * 2;
450 }
451
452 Size::from((width, max(height, 1)))
453 }
454
455 pub fn configure_new_window(&self, window: &Window, width: Option<ColumnWidth>) {
456 if let Some(output) = self.output.as_ref() {
457 let scale = output.current_scale().integer_scale();
458 let transform = output.current_transform();
459 window.with_surfaces(|surface, data| {
460 send_surface_state(surface, data, scale, transform);
461 });
462 }
463
464 window
465 .toplevel()
466 .expect("no x11 support")
467 .with_pending_state(|state| {
468 if state.states.contains(xdg_toplevel::State::Fullscreen) {
469 state.size = Some(self.view_size);
470 } else {
471 state.size = Some(self.new_window_size(width));
472 }
473
474 state.bounds = Some(self.toplevel_bounds());
475 });
476 }
477
478 fn compute_new_view_offset_for_column(&self, current_x: i32, idx: usize) -> i32 {
479 if self.columns[idx].is_fullscreen {
480 return 0;
481 }
482
483 let new_col_x = self.column_x(idx);
484
485 let final_x = if let Some(ViewOffsetAdjustment::Animation(anim)) = &self.view_offset_adj {
486 current_x - self.view_offset + anim.to().round() as i32
487 } else {
488 current_x
489 };
490
491 let new_offset = compute_new_view_offset(
492 final_x + self.working_area.loc.x,
493 self.working_area.size.w,
494 new_col_x,
495 self.columns[idx].width(),
496 self.options.gaps,
497 );
498
499 // Non-fullscreen windows are always offset at least by the working area position.
500 new_offset - self.working_area.loc.x
501 }
502
503 fn animate_view_offset(&mut self, current_x: i32, idx: usize, new_view_offset: i32) {
504 self.animate_view_offset_with_config(
505 current_x,
506 idx,
507 new_view_offset,
508 self.options.animations.horizontal_view_movement.0,
509 );
510 }
511
512 fn animate_view_offset_with_config(
513 &mut self,
514 current_x: i32,
515 idx: usize,
516 new_view_offset: i32,
517 config: niri_config::Animation,
518 ) {
519 let new_col_x = self.column_x(idx);
520 let from_view_offset = current_x - new_col_x;
521 self.view_offset = from_view_offset;
522
523 // If we're already animating towards that, don't restart it.
524 if let Some(ViewOffsetAdjustment::Animation(anim)) = &self.view_offset_adj {
525 if anim.value().round() as i32 == self.view_offset
526 && anim.to().round() as i32 == new_view_offset
527 {
528 return;
529 }
530 }
531
532 // If our view offset is already this, we don't need to do anything.
533 if self.view_offset == new_view_offset {
534 self.view_offset_adj = None;
535 return;
536 }
537
538 // FIXME: also compute and use current velocity.
539 self.view_offset_adj = Some(ViewOffsetAdjustment::Animation(Animation::new(
540 self.view_offset as f64,
541 new_view_offset as f64,
542 0.,
543 config,
544 )));
545 }
546
547 fn animate_view_offset_to_column_fit(
548 &mut self,
549 current_x: i32,
550 idx: usize,
551 config: niri_config::Animation,
552 ) {
553 let new_view_offset = self.compute_new_view_offset_for_column(current_x, idx);
554 self.animate_view_offset_with_config(current_x, idx, new_view_offset, config);
555 }
556
557 fn animate_view_offset_to_column_centered(
558 &mut self,
559 current_x: i32,
560 idx: usize,
561 config: niri_config::Animation,
562 ) {
563 if self.columns.is_empty() {
564 return;
565 }
566
567 let col = &self.columns[idx];
568 if col.is_fullscreen {
569 self.animate_view_offset_to_column_fit(current_x, idx, config);
570 return;
571 }
572
573 let width = col.width();
574
575 // If the column is wider than the working area, then on commit it will be shifted to left
576 // edge alignment by the usual positioning code, so there's no use in trying to center it
577 // here.
578 if self.working_area.size.w <= width {
579 self.animate_view_offset_to_column_fit(current_x, idx, config);
580 return;
581 }
582
583 let new_view_offset = -(self.working_area.size.w - width) / 2 - self.working_area.loc.x;
584
585 self.animate_view_offset_with_config(current_x, idx, new_view_offset, config);
586 }
587
588 fn animate_view_offset_to_column(
589 &mut self,
590 current_x: i32,
591 idx: usize,
592 prev_idx: Option<usize>,
593 ) {
594 self.animate_view_offset_to_column_with_config(
595 current_x,
596 idx,
597 prev_idx,
598 self.options.animations.horizontal_view_movement.0,
599 )
600 }
601
602 fn animate_view_offset_to_column_with_config(
603 &mut self,
604 current_x: i32,
605 idx: usize,
606 prev_idx: Option<usize>,
607 config: niri_config::Animation,
608 ) {
609 match self.options.center_focused_column {
610 CenterFocusedColumn::Always => {
611 self.animate_view_offset_to_column_centered(current_x, idx, config)
612 }
613 CenterFocusedColumn::OnOverflow => {
614 let Some(prev_idx) = prev_idx else {
615 self.animate_view_offset_to_column_fit(current_x, idx, config);
616 return;
617 };
618
619 // Always take the left or right neighbor of the target as the source.
620 let source_idx = if prev_idx > idx {
621 min(idx + 1, self.columns.len() - 1)
622 } else {
623 idx.saturating_sub(1)
624 };
625
626 let source_x = self.column_x(source_idx);
627 let source_width = self.columns[source_idx].width();
628
629 let target_x = self.column_x(idx);
630 let target_width = self.columns[idx].width();
631
632 let total_width = if source_x < target_x {
633 // Source is left from target.
634 target_x - source_x + target_width
635 } else {
636 // Source is right from target.
637 source_x - target_x + source_width
638 } + self.options.gaps * 2;
639
640 // If it fits together, do a normal animation, otherwise center the new column.
641 if total_width <= self.working_area.size.w {
642 self.animate_view_offset_to_column_fit(current_x, idx, config);
643 } else {
644 self.animate_view_offset_to_column_centered(current_x, idx, config);
645 }
646 }
647 CenterFocusedColumn::Never => {
648 self.animate_view_offset_to_column_fit(current_x, idx, config)
649 }
650 };
651 }
652
653 fn activate_column(&mut self, idx: usize) {
654 self.activate_column_with_anim_config(
655 idx,
656 self.options.animations.horizontal_view_movement.0,
657 );
658 }
659
660 fn activate_column_with_anim_config(&mut self, idx: usize, config: niri_config::Animation) {
661 if self.active_column_idx == idx {
662 return;
663 }
664
665 let current_x = self.view_pos();
666 self.animate_view_offset_to_column_with_config(
667 current_x,
668 idx,
669 Some(self.active_column_idx),
670 config,
671 );
672
673 self.active_column_idx = idx;
674
675 // A different column was activated; reset the flag.
676 self.activate_prev_column_on_removal = None;
677 self.view_offset_before_fullscreen = None;
678 }
679
680 pub fn has_windows(&self) -> bool {
681 self.windows().next().is_some()
682 }
683
684 pub fn has_window(&self, window: &W::Id) -> bool {
685 self.windows().any(|win| win.id() == window)
686 }
687
688 pub fn find_wl_surface(&self, wl_surface: &WlSurface) -> Option<&W> {
689 self.windows().find(|win| win.is_wl_surface(wl_surface))
690 }
691
692 pub fn find_wl_surface_mut(&mut self, wl_surface: &WlSurface) -> Option<&mut W> {
693 self.windows_mut().find(|win| win.is_wl_surface(wl_surface))
694 }
695
696 /// Computes the X position of the windows in the given column, in logical coordinates.
697 pub fn column_x(&self, column_idx: usize) -> i32 {
698 let mut x = 0;
699
700 for column in self.columns.iter().take(column_idx) {
701 x += column.width() + self.options.gaps;
702 }
703
704 x
705 }
706
707 pub fn add_window_at(
708 &mut self,
709 col_idx: usize,
710 window: W,
711 activate: bool,
712 width: ColumnWidth,
713 is_full_width: bool,
714 ) {
715 let tile = Tile::new(window, self.options.clone());
716 self.add_tile_at(col_idx, tile, activate, width, is_full_width, None);
717 }
718
719 fn add_tile_at(
720 &mut self,
721 col_idx: usize,
722 tile: Tile<W>,
723 activate: bool,
724 width: ColumnWidth,
725 is_full_width: bool,
726 anim_config: Option<niri_config::Animation>,
727 ) {
728 self.enter_output_for_window(tile.window());
729
730 let was_empty = self.columns.is_empty();
731
732 let column = Column::new_with_tile(
733 tile,
734 self.view_size,
735 self.working_area,
736 self.options.clone(),
737 width,
738 is_full_width,
739 true,
740 );
741 let width = column.width();
742 self.columns.insert(col_idx, column);
743
744 if activate {
745 // If this is the first window on an empty workspace, skip the animation from whatever
746 // view_offset was left over.
747 if was_empty {
748 if self.options.center_focused_column == CenterFocusedColumn::Always {
749 self.view_offset =
750 -(self.working_area.size.w - width) / 2 - self.working_area.loc.x;
751 } else {
752 // Try to make the code produce a left-aligned offset, even in presence of left
753 // exclusive zones.
754 self.view_offset = self.compute_new_view_offset_for_column(self.column_x(0), 0);
755 }
756 self.view_offset_adj = None;
757 }
758
759 let prev_offset = (!was_empty).then(|| self.static_view_offset());
760
761 self.activate_column_with_anim_config(
762 col_idx,
763 anim_config.unwrap_or(self.options.animations.horizontal_view_movement.0),
764 );
765 self.activate_prev_column_on_removal = prev_offset;
766 }
767
768 // Animate movement of other columns.
769 let offset = self.column_x(col_idx + 1) - self.column_x(col_idx);
770 let config = anim_config.unwrap_or(self.options.animations.window_movement.0);
771 if self.active_column_idx <= col_idx {
772 for col in &mut self.columns[col_idx + 1..] {
773 col.animate_move_from_with_config(-offset, config);
774 }
775 } else {
776 for col in &mut self.columns[..col_idx] {
777 col.animate_move_from_with_config(offset, config);
778 }
779 }
780 }
781
782 pub fn add_window(
783 &mut self,
784 window: W,
785 activate: bool,
786 width: ColumnWidth,
787 is_full_width: bool,
788 ) {
789 let col_idx = if self.columns.is_empty() {
790 0
791 } else {
792 self.active_column_idx + 1
793 };
794
795 self.add_window_at(col_idx, window, activate, width, is_full_width);
796 }
797
798 fn add_tile(
799 &mut self,
800 tile: Tile<W>,
801 activate: bool,
802 width: ColumnWidth,
803 is_full_width: bool,
804 anim_config: Option<niri_config::Animation>,
805 ) {
806 let col_idx = if self.columns.is_empty() {
807 0
808 } else {
809 self.active_column_idx + 1
810 };
811
812 self.add_tile_at(col_idx, tile, activate, width, is_full_width, anim_config);
813 }
814
815 pub fn add_window_right_of(
816 &mut self,
817 right_of: &W::Id,
818 window: W,
819 width: ColumnWidth,
820 is_full_width: bool,
821 ) {
822 self.enter_output_for_window(&window);
823
824 let right_of_idx = self
825 .columns
826 .iter()
827 .position(|col| col.contains(right_of))
828 .unwrap();
829 let idx = right_of_idx + 1;
830
831 let column = Column::new(
832 window,
833 self.view_size,
834 self.working_area,
835 self.options.clone(),
836 width,
837 is_full_width,
838 true,
839 );
840 self.columns.insert(idx, column);
841
842 // Activate the new window if right_of was active.
843 if self.active_column_idx == right_of_idx {
844 let prev_offset = self.static_view_offset();
845 self.activate_column(idx);
846 self.activate_prev_column_on_removal = Some(prev_offset);
847 } else if idx <= self.active_column_idx {
848 self.active_column_idx += 1;
849 }
850
851 // Animate movement of other columns.
852 let offset = self.column_x(idx + 1) - self.column_x(idx);
853 if self.active_column_idx <= idx {
854 for col in &mut self.columns[idx + 1..] {
855 col.animate_move_from(-offset);
856 }
857 } else {
858 for col in &mut self.columns[..idx] {
859 col.animate_move_from(offset);
860 }
861 }
862 }
863
864 pub fn add_column(&mut self, mut column: Column<W>, activate: bool) {
865 for tile in &column.tiles {
866 self.enter_output_for_window(tile.window());
867 }
868
869 let was_empty = self.columns.is_empty();
870
871 let idx = if self.columns.is_empty() {
872 0
873 } else {
874 self.active_column_idx + 1
875 };
876
877 column.set_view_size(self.view_size, self.working_area);
878 let width = column.width();
879 self.columns.insert(idx, column);
880
881 if activate {
882 // If this is the first window on an empty workspace, skip the animation from whatever
883 // view_offset was left over.
884 if was_empty {
885 if self.options.center_focused_column == CenterFocusedColumn::Always {
886 self.view_offset =
887 -(self.working_area.size.w - width) / 2 - self.working_area.loc.x;
888 } else {
889 // Try to make the code produce a left-aligned offset, even in presence of left
890 // exclusive zones.
891 self.view_offset = self.compute_new_view_offset_for_column(self.column_x(0), 0);
892 }
893 self.view_offset_adj = None;
894 }
895
896 let prev_offset = (!was_empty).then(|| self.static_view_offset());
897
898 self.activate_column(idx);
899 self.activate_prev_column_on_removal = prev_offset;
900 }
901
902 // Animate movement of other columns.
903 let offset = self.column_x(idx + 1) - self.column_x(idx);
904 if self.active_column_idx <= idx {
905 for col in &mut self.columns[idx + 1..] {
906 col.animate_move_from(-offset);
907 }
908 } else {
909 for col in &mut self.columns[..idx] {
910 col.animate_move_from(offset);
911 }
912 }
913 }
914
915 pub fn remove_tile_by_idx(&mut self, column_idx: usize, window_idx: usize) -> Tile<W> {
916 let offset = self.column_x(column_idx + 1) - self.column_x(column_idx);
917
918 let column = &mut self.columns[column_idx];
919
920 // Animate movement of other tiles.
921 let offset_y = column.tile_y(window_idx + 1) - column.tile_y(window_idx);
922 for tile in &mut column.tiles[window_idx + 1..] {
923 tile.animate_move_from(Point::from((0, offset_y)));
924 }
925
926 let tile = column.tiles.remove(window_idx);
927 column.heights.remove(window_idx);
928
929 if let Some(output) = &self.output {
930 tile.window().output_leave(output);
931 }
932
933 if column.tiles.is_empty() {
934 if column_idx + 1 == self.active_column_idx {
935 // The previous column, that we were going to activate upon removal of the active
936 // column, has just been itself removed.
937 self.activate_prev_column_on_removal = None;
938 }
939
940 if column_idx == self.active_column_idx {
941 self.view_offset_before_fullscreen = None;
942 }
943
944 // Animate movement of the other columns.
945 if self.active_column_idx <= column_idx {
946 for col in &mut self.columns[column_idx + 1..] {
947 col.animate_move_from(offset);
948 }
949 } else {
950 for col in &mut self.columns[..column_idx] {
951 col.animate_move_from(-offset);
952 }
953 }
954
955 self.columns.remove(column_idx);
956 if self.columns.is_empty() {
957 return tile;
958 }
959
960 if column_idx < self.active_column_idx {
961 // A column to the left was removed; preserve the current position.
962 // FIXME: preserve activate_prev_column_on_removal.
963 self.active_column_idx -= 1;
964 self.activate_prev_column_on_removal = None;
965 } else if column_idx == self.active_column_idx
966 && self.activate_prev_column_on_removal.is_some()
967 {
968 // The active column was removed, and we needed to activate the previous column.
969 if 0 < column_idx {
970 let prev_offset = self.activate_prev_column_on_removal.unwrap();
971
972 self.activate_column(self.active_column_idx - 1);
973
974 // Restore the view offset but make sure to scroll the view in case the
975 // previous window had resized.
976 let current_x = self.view_pos();
977 self.animate_view_offset(current_x, self.active_column_idx, prev_offset);
978 self.animate_view_offset_to_column(current_x, self.active_column_idx, None);
979 }
980 } else {
981 self.activate_column(min(self.active_column_idx, self.columns.len() - 1));
982 }
983
984 return tile;
985 }
986
987 column.active_tile_idx = min(column.active_tile_idx, column.tiles.len() - 1);
988 column.update_tile_sizes(true);
989
990 tile
991 }
992
993 pub fn remove_column_by_idx(&mut self, column_idx: usize) -> Column<W> {
994 // Animate movement of the other columns.
995 let offset = self.column_x(column_idx + 1) - self.column_x(column_idx);
996 if self.active_column_idx <= column_idx {
997 for col in &mut self.columns[column_idx + 1..] {
998 col.animate_move_from(offset);
999 }
1000 } else {
1001 for col in &mut self.columns[..column_idx] {
1002 col.animate_move_from(-offset);
1003 }
1004 }
1005
1006 let column = self.columns.remove(column_idx);
1007
1008 if let Some(output) = &self.output {
1009 for tile in &column.tiles {
1010 tile.window().output_leave(output);
1011 }
1012 }
1013
1014 if column_idx + 1 == self.active_column_idx {
1015 // The previous column, that we were going to activate upon removal of the active
1016 // column, has just been itself removed.
1017 self.activate_prev_column_on_removal = None;
1018 }
1019
1020 if column_idx == self.active_column_idx {
1021 self.view_offset_before_fullscreen = None;
1022 }
1023
1024 if self.columns.is_empty() {
1025 return column;
1026 }
1027
1028 if column_idx < self.active_column_idx {
1029 // A column to the left was removed; preserve the current position.
1030 // FIXME: preserve activate_prev_column_on_removal.
1031 self.active_column_idx -= 1;
1032 self.activate_prev_column_on_removal = None;
1033 } else if column_idx == self.active_column_idx
1034 && self.activate_prev_column_on_removal.is_some()
1035 {
1036 // The active column was removed, and we needed to activate the previous column.
1037 if 0 < column_idx {
1038 let prev_offset = self.activate_prev_column_on_removal.unwrap();
1039
1040 self.activate_column(self.active_column_idx - 1);
1041
1042 // Restore the view offset but make sure to scroll the view in case the
1043 // previous window had resized.
1044 let current_x = self.view_pos();
1045 self.animate_view_offset(current_x, self.active_column_idx, prev_offset);
1046 self.animate_view_offset_to_column(current_x, self.active_column_idx, None);
1047 }
1048 } else {
1049 self.activate_column(min(self.active_column_idx, self.columns.len() - 1));
1050 }
1051
1052 column
1053 }
1054
1055 pub fn remove_window(&mut self, window: &W::Id) -> W {
1056 let column_idx = self
1057 .columns
1058 .iter()
1059 .position(|col| col.contains(window))
1060 .unwrap();
1061 let column = &self.columns[column_idx];
1062
1063 let window_idx = column.position(window).unwrap();
1064 self.remove_tile_by_idx(column_idx, window_idx)
1065 .into_window()
1066 }
1067
1068 pub fn update_window(&mut self, window: &W::Id) {
1069 let (col_idx, column) = self
1070 .columns
1071 .iter_mut()
1072 .enumerate()
1073 .find(|(_, col)| col.contains(window))
1074 .unwrap();
1075 let tile_idx = column
1076 .tiles
1077 .iter()
1078 .position(|tile| tile.window().id() == window)
1079 .unwrap();
1080
1081 let offset = column
1082 .width_before_resize
1083 .take()
1084 .map_or(0, |prev| prev - column.width());
1085
1086 let was_fullscreen = column.tiles[tile_idx].is_fullscreen();
1087
1088 column.update_window(window);
1089 column.update_tile_sizes(false);
1090
1091 // Move other columns in tandem with resizing.
1092 let started_resize_anim =
1093 column.tiles[tile_idx].resize_animation().is_some() && offset != 0;
1094 if started_resize_anim {
1095 if self.active_column_idx <= col_idx {
1096 for col in &mut self.columns[col_idx + 1..] {
1097 col.animate_move_from_with_config(
1098 offset,
1099 self.options.animations.window_resize.0,
1100 );
1101 }
1102 } else {
1103 for col in &mut self.columns[..=col_idx] {
1104 col.animate_move_from_with_config(
1105 -offset,
1106 self.options.animations.window_resize.0,
1107 );
1108 }
1109 }
1110 }
1111
1112 if col_idx == self.active_column_idx
1113 && !matches!(self.view_offset_adj, Some(ViewOffsetAdjustment::Gesture(_)))
1114 {
1115 // We might need to move the view to ensure the resized window is still visible.
1116 let current_x = self.view_pos();
1117
1118 // Upon unfullscreening, restore the view offset.
1119 let is_fullscreen = self.columns[col_idx].tiles[tile_idx].is_fullscreen();
1120 if was_fullscreen && !is_fullscreen {
1121 if let Some(prev_offset) = self.view_offset_before_fullscreen.take() {
1122 self.animate_view_offset(current_x, col_idx, prev_offset);
1123 }
1124 }
1125
1126 // Synchronize the horizontal view movement with the resize so that it looks nice. This
1127 // is especially important for always-centered view.
1128 let config = if started_resize_anim {
1129 self.options.animations.window_resize.0
1130 } else {
1131 self.options.animations.horizontal_view_movement.0
1132 };
1133
1134 // FIXME: we will want to skip the animation in some cases here to make continuously
1135 // resizing windows not look janky.
1136 self.animate_view_offset_to_column_with_config(current_x, col_idx, None, config);
1137 }
1138 }
1139
1140 pub fn activate_window(&mut self, window: &W::Id) {
1141 let column_idx = self
1142 .columns
1143 .iter()
1144 .position(|col| col.contains(window))
1145 .unwrap();
1146 let column = &mut self.columns[column_idx];
1147
1148 column.activate_window(window);
1149 self.activate_column(column_idx);
1150 }
1151
1152 pub fn start_close_animation_for_window(
1153 &mut self,
1154 renderer: &mut GlesRenderer,
1155 window: &W::Id,
1156 ) {
1157 let (tile, mut tile_pos) = self
1158 .tiles_in_render_order()
1159 .find(|(tile, _)| tile.window().id() == window)
1160 .unwrap();
1161
1162 // FIXME: workspaces should probably cache their last used scale so they can be correctly
1163 // rendered even with no outputs connected.
1164 let output_scale = self
1165 .output
1166 .as_ref()
1167 .map(|o| Scale::from(o.current_scale().fractional_scale()))
1168 .unwrap_or(Scale::from(1.));
1169
1170 let Some(snapshot) =
1171 tile.take_snapshot_for_close_anim(renderer, output_scale, self.view_size)
1172 else {
1173 return;
1174 };
1175
1176 let col_idx = self
1177 .columns
1178 .iter()
1179 .position(|col| col.contains(window))
1180 .unwrap();
1181
1182 let col = &self.columns[col_idx];
1183 let removing_last = col.tiles.len() == 1;
1184 let offset = self.column_x(col_idx + 1) - self.column_x(col_idx);
1185
1186 let mut center = Point::from((0, 0));
1187 center.x += tile.tile_size().w / 2;
1188 center.y += tile.tile_size().h / 2;
1189
1190 tile_pos.x += self.view_pos();
1191
1192 if col_idx < self.active_column_idx && removing_last {
1193 tile_pos.x -= offset;
1194 }
1195
1196 // FIXME: this is a bit cursed since it's relying on Tile's internal details.
1197 let (starting_alpha, starting_scale) = if let Some(anim) = tile.open_animation() {
1198 (
1199 anim.clamped_value().clamp(0., 1.) as f32,
1200 (anim.value() / 2. + 0.5).max(0.),
1201 )
1202 } else {
1203 (1., 1.)
1204 };
1205
1206 let anim = Animation::new(1., 0., 0., self.options.animations.window_close.0);
1207
1208 let res = ClosingWindow::new(
1209 renderer,
1210 snapshot,
1211 output_scale.x as i32,
1212 center,
1213 tile_pos,
1214 anim,
1215 starting_alpha,
1216 starting_scale,
1217 );
1218 match res {
1219 Ok(closing) => {
1220 self.closing_windows.push(closing);
1221 }
1222 Err(err) => {
1223 warn!("error creating a closing window animation: {err:?}");
1224 }
1225 }
1226 }
1227
1228 pub fn prepare_for_resize_animation(&mut self, window: &W::Id) {
1229 let column = self
1230 .columns
1231 .iter_mut()
1232 .find(|col| col.contains(window))
1233 .unwrap();
1234
1235 column.width_before_resize = Some(column.width());
1236 }
1237
1238 #[cfg(test)]
1239 pub fn verify_invariants(&self) {
1240 assert!(self.view_size.w > 0);
1241 assert!(self.view_size.h > 0);
1242
1243 if !self.columns.is_empty() {
1244 assert!(self.active_column_idx < self.columns.len());
1245
1246 for column in &self.columns {
1247 assert!(Rc::ptr_eq(&self.options, &column.options));
1248 column.verify_invariants();
1249 }
1250
1251 // When we have an unfullscreen view offset stored, the active column should have a
1252 // fullscreen tile.
1253 if self.view_offset_before_fullscreen.is_some() {
1254 let col = &self.columns[self.active_column_idx];
1255 assert!(
1256 col.is_fullscreen
1257 || col.tiles.iter().any(|tile| {
1258 tile.is_fullscreen() || tile.window().is_pending_fullscreen()
1259 })
1260 );
1261 }
1262 }
1263 }
1264
1265 pub fn focus_left(&mut self) {
1266 self.activate_column(self.active_column_idx.saturating_sub(1));
1267 }
1268
1269 pub fn focus_right(&mut self) {
1270 if self.columns.is_empty() {
1271 return;
1272 }
1273
1274 self.activate_column(min(self.active_column_idx + 1, self.columns.len() - 1));
1275 }
1276
1277 pub fn focus_column_first(&mut self) {
1278 self.activate_column(0);
1279 }
1280
1281 pub fn focus_column_last(&mut self) {
1282 if self.columns.is_empty() {
1283 return;
1284 }
1285
1286 self.activate_column(self.columns.len() - 1);
1287 }
1288
1289 pub fn focus_down(&mut self) {
1290 if self.columns.is_empty() {
1291 return;
1292 }
1293
1294 self.columns[self.active_column_idx].focus_down();
1295 }
1296
1297 pub fn focus_up(&mut self) {
1298 if self.columns.is_empty() {
1299 return;
1300 }
1301
1302 self.columns[self.active_column_idx].focus_up();
1303 }
1304
1305 fn move_column_to(&mut self, new_idx: usize) {
1306 if self.active_column_idx == new_idx {
1307 return;
1308 }
1309
1310 let current_col_x = self.column_x(self.active_column_idx);
1311 let next_col_x = self.column_x(self.active_column_idx + 1);
1312
1313 let column = self.columns.remove(self.active_column_idx);
1314 self.columns.insert(new_idx, column);
1315
1316 // Preserve the camera position when moving to the left.
1317 let view_offset_delta = -self.column_x(self.active_column_idx) + current_col_x;
1318 self.view_offset += view_offset_delta;
1319 if let Some(ViewOffsetAdjustment::Animation(anim)) = &mut self.view_offset_adj {
1320 anim.offset(view_offset_delta as f64);
1321 }
1322
1323 // The column we just moved is offset by the difference between its new and old position.
1324 let new_col_x = self.column_x(new_idx);
1325 self.columns[new_idx].animate_move_from(current_col_x - new_col_x);
1326
1327 // All columns in between moved by the width of the column that we just moved.
1328 let others_x_offset = next_col_x - current_col_x;
1329 if self.active_column_idx < new_idx {
1330 for col in &mut self.columns[self.active_column_idx..new_idx] {
1331 col.animate_move_from(others_x_offset);
1332 }
1333 } else {
1334 for col in &mut self.columns[new_idx + 1..=self.active_column_idx] {
1335 col.animate_move_from(-others_x_offset);
1336 }
1337 }
1338
1339 self.activate_column_with_anim_config(new_idx, self.options.animations.window_movement.0);
1340 }
1341
1342 pub fn move_left(&mut self) {
1343 let new_idx = self.active_column_idx.saturating_sub(1);
1344 self.move_column_to(new_idx);
1345 }
1346
1347 pub fn move_right(&mut self) {
1348 if self.columns.is_empty() {
1349 return;
1350 }
1351
1352 let new_idx = min(self.active_column_idx + 1, self.columns.len() - 1);
1353 self.move_column_to(new_idx);
1354 }
1355
1356 pub fn move_column_to_first(&mut self) {
1357 self.move_column_to(0);
1358 }
1359
1360 pub fn move_column_to_last(&mut self) {
1361 if self.columns.is_empty() {
1362 return;
1363 }
1364
1365 let new_idx = self.columns.len() - 1;
1366 self.move_column_to(new_idx);
1367 }
1368
1369 pub fn move_down(&mut self) {
1370 if self.columns.is_empty() {
1371 return;
1372 }
1373
1374 self.columns[self.active_column_idx].move_down();
1375 }
1376
1377 pub fn move_up(&mut self) {
1378 if self.columns.is_empty() {
1379 return;
1380 }
1381
1382 self.columns[self.active_column_idx].move_up();
1383 }
1384
1385 pub fn consume_or_expel_window_left(&mut self) {
1386 if self.columns.is_empty() {
1387 return;
1388 }
1389
1390 let source_col_idx = self.active_column_idx;
1391 let source_column = &self.columns[source_col_idx];
1392 let prev_y = source_column.tile_y(source_column.active_tile_idx);
1393
1394 if source_column.tiles.len() == 1 {
1395 if self.active_column_idx == 0 {
1396 return;
1397 }
1398
1399 let offset_x = self.column_x(source_col_idx) - self.column_x(source_col_idx - 1);
1400
1401 // Move into adjacent column.
1402 let target_column_idx = source_col_idx - 1;
1403
1404 // Make sure the previous (target) column is activated so the animation looks right.
1405 self.activate_prev_column_on_removal = Some(self.static_view_offset() + offset_x);
1406 let offset_x = offset_x + self.columns[source_col_idx].render_offset().x;
1407 let tile = self.remove_tile_by_idx(source_col_idx, 0);
1408 self.enter_output_for_window(tile.window());
1409
1410 let next_col_idx = source_col_idx;
1411 let prev_next_x = self.column_x(next_col_idx);
1412
1413 let target_column = &mut self.columns[target_column_idx];
1414 let offset_x = offset_x - target_column.render_offset().x;
1415 let offset_y = prev_y - target_column.tile_y(target_column.tiles.len());
1416
1417 target_column.add_tile(tile, true);
1418 target_column.focus_last();
1419
1420 let new_tile = target_column.tiles.last_mut().unwrap();
1421 new_tile.animate_move_from(Point::from((offset_x, offset_y)));
1422
1423 // Consuming a window into a column could've increased its width if the new window had a
1424 // larger min width. Move the next columns to account for this.
1425 let offset_next = prev_next_x - self.column_x(next_col_idx);
1426 for col in &mut self.columns[next_col_idx..] {
1427 col.animate_move_from(offset_next);
1428 }
1429 } else {
1430 // Move out of column.
1431 let width = source_column.width;
1432 let is_full_width = source_column.is_full_width;
1433
1434 let offset_x = source_column.render_offset().x;
1435
1436 let tile = self.remove_tile_by_idx(source_col_idx, source_column.active_tile_idx);
1437
1438 self.add_tile_at(
1439 self.active_column_idx,
1440 tile,
1441 true,
1442 width,
1443 is_full_width,
1444 Some(self.options.animations.window_movement.0),
1445 );
1446
1447 // We added to the left, don't activate even further left on removal.
1448 self.activate_prev_column_on_removal = None;
1449
1450 let new_col = &mut self.columns[self.active_column_idx];
1451 let offset_y = prev_y - new_col.tile_y(0);
1452 new_col.tiles[0].animate_move_from(Point::from((offset_x, offset_y)));
1453 }
1454 }
1455
1456 pub fn consume_or_expel_window_right(&mut self) {
1457 if self.columns.is_empty() {
1458 return;
1459 }
1460
1461 let source_col_idx = self.active_column_idx;
1462 let offset_x = self.column_x(source_col_idx) - self.column_x(source_col_idx + 1);
1463
1464 let source_column = &self.columns[source_col_idx];
1465 let offset_x = offset_x + source_column.render_offset().x;
1466 let prev_y = source_column.tile_y(source_column.active_tile_idx);
1467
1468 if source_column.tiles.len() == 1 {
1469 if self.active_column_idx + 1 == self.columns.len() {
1470 return;
1471 }
1472
1473 // Move into adjacent column.
1474 let target_column_idx = source_col_idx;
1475
1476 let offset_x = offset_x - self.columns[source_col_idx + 1].render_offset().x;
1477
1478 // Make sure the target column gets activated.
1479 self.activate_prev_column_on_removal = None;
1480 let tile = self.remove_tile_by_idx(source_col_idx, 0);
1481 self.enter_output_for_window(tile.window());
1482
1483 let prev_next_x = self.column_x(target_column_idx + 1);
1484
1485 let target_column = &mut self.columns[target_column_idx];
1486 let offset_y = prev_y - target_column.tile_y(target_column.tiles.len());
1487
1488 target_column.add_tile(tile, true);
1489 target_column.focus_last();
1490
1491 let new_tile = target_column.tiles.last_mut().unwrap();
1492 new_tile.animate_move_from(Point::from((offset_x, offset_y)));
1493
1494 // Consuming a window into a column could've increased its width if the new window had a
1495 // larger min width. Move the next columns to account for this.
1496 let offset_next = prev_next_x - self.column_x(target_column_idx + 1);
1497 for col in &mut self.columns[target_column_idx + 1..] {
1498 col.animate_move_from(offset_next);
1499 }
1500 } else {
1501 // Move out of column.
1502 let width = source_column.width;
1503 let is_full_width = source_column.is_full_width;
1504
1505 let tile = self.remove_tile_by_idx(source_col_idx, source_column.active_tile_idx);
1506
1507 self.add_tile(
1508 tile,
1509 true,
1510 width,
1511 is_full_width,
1512 Some(self.options.animations.window_movement.0),
1513 );
1514
1515 let new_col = &mut self.columns[self.active_column_idx];
1516 let offset_y = prev_y - new_col.tile_y(0);
1517 new_col.tiles[0].animate_move_from(Point::from((offset_x, offset_y)));
1518 }
1519 }
1520
1521 pub fn consume_into_column(&mut self) {
1522 if self.columns.len() < 2 {
1523 return;
1524 }
1525
1526 if self.active_column_idx == self.columns.len() - 1 {
1527 return;
1528 }
1529
1530 let source_column_idx = self.active_column_idx + 1;
1531
1532 let offset_x = self.column_x(source_column_idx)
1533 + self.columns[source_column_idx].render_offset().x
1534 - self.column_x(self.active_column_idx);
1535 let prev_y = self.columns[source_column_idx].tile_y(0);
1536
1537 let tile = self.remove_tile_by_idx(source_column_idx, 0);
1538 self.enter_output_for_window(tile.window());
1539
1540 let prev_next_x = self.column_x(self.active_column_idx + 1);
1541
1542 let target_column = &mut self.columns[self.active_column_idx];
1543 let was_fullscreen = target_column.tiles[target_column.active_tile_idx].is_fullscreen();
1544 let offset_y = prev_y - target_column.tile_y(target_column.tiles.len());
1545
1546 target_column.add_tile(tile, true);
1547
1548 if !was_fullscreen {
1549 self.view_offset_before_fullscreen = None;
1550 }
1551
1552 let offset_x = offset_x - target_column.render_offset().x;
1553
1554 let new_tile = target_column.tiles.last_mut().unwrap();
1555 new_tile.animate_move_from(Point::from((offset_x, offset_y)));
1556
1557 // Consuming a window into a column could've increased its width if the new window had a
1558 // larger min width. Move the next columns to account for this.
1559 let offset_next = prev_next_x - self.column_x(self.active_column_idx + 1);
1560 for col in &mut self.columns[self.active_column_idx + 1..] {
1561 col.animate_move_from(offset_next);
1562 }
1563 }
1564
1565 pub fn expel_from_column(&mut self) {
1566 if self.columns.is_empty() {
1567 return;
1568 }
1569
1570 let offset_x =
1571 self.column_x(self.active_column_idx) - self.column_x(self.active_column_idx + 1);
1572
1573 let source_column = &self.columns[self.active_column_idx];
1574 if source_column.tiles.len() == 1 {
1575 return;
1576 }
1577
1578 let offset_x = offset_x + source_column.render_offset().x;
1579
1580 let prev_y = source_column.tile_y(source_column.active_tile_idx);
1581
1582 let width = source_column.width;
1583 let is_full_width = source_column.is_full_width;
1584 let tile = self.remove_tile_by_idx(self.active_column_idx, source_column.active_tile_idx);
1585
1586 self.add_tile(
1587 tile,
1588 true,
1589 width,
1590 is_full_width,
1591 Some(self.options.animations.window_movement.0),
1592 );
1593
1594 let new_col = &mut self.columns[self.active_column_idx];
1595 let offset_y = prev_y - new_col.tile_y(0);
1596 new_col.tiles[0].animate_move_from(Point::from((offset_x, offset_y)));
1597 }
1598
1599 pub fn center_column(&mut self) {
1600 let center_x = self.view_pos();
1601 self.animate_view_offset_to_column_centered(
1602 center_x,
1603 self.active_column_idx,
1604 self.options.animations.horizontal_view_movement.0,
1605 );
1606 }
1607
1608 fn view_pos(&self) -> i32 {
1609 self.column_x(self.active_column_idx) + self.view_offset
1610 }
1611
1612 /// Returns a view offset value suitable for saving and later restoration.
1613 ///
1614 /// This means that it shouldn't return an in-progress animation or gesture value.
1615 fn static_view_offset(&self) -> i32 {
1616 match &self.view_offset_adj {
1617 // For animations we can return the final value.
1618 Some(ViewOffsetAdjustment::Animation(anim)) => anim.to().round() as i32,
1619 Some(ViewOffsetAdjustment::Gesture(gesture)) => gesture.static_view_offset,
1620 _ => self.view_offset,
1621 }
1622 }
1623
1624 fn tiles_in_render_order(&self) -> impl Iterator<Item = (&'_ Tile<W>, Point<i32, Logical>)> {
1625 let view_pos = self.view_pos();
1626
1627 // Start with the active window since it's drawn on top.
1628 let col = &self.columns[self.active_column_idx];
1629 let tile = &col.tiles[col.active_tile_idx];
1630 let tile_pos = Point::from((-self.view_offset, col.tile_y(col.active_tile_idx)))
1631 + col.render_offset()
1632 + tile.render_offset();
1633 let first = iter::once((tile, tile_pos));
1634
1635 // Next, the rest of the tiles in the active column, since it should be drawn on top as a
1636 // whole during animations.
1637 let next =
1638 zip(&col.tiles, col.tile_ys())
1639 .enumerate()
1640 .filter_map(move |(tile_idx, (tile, y))| {
1641 if tile_idx == col.active_tile_idx {
1642 // Active tile comes first.
1643 return None;
1644 }
1645
1646 let tile_pos = Point::from((-self.view_offset, y))
1647 + col.render_offset()
1648 + tile.render_offset();
1649 Some((tile, tile_pos))
1650 });
1651
1652 let mut x = -view_pos;
1653 let rest = self
1654 .columns
1655 .iter()
1656 .enumerate()
1657 // Keep track of column X position.
1658 .map(move |(col_idx, col)| {
1659 let rv = (col_idx, col, x);
1660 x += col.width() + self.options.gaps;
1661 rv
1662 })
1663 .filter_map(|(col_idx, col, x)| {
1664 if col_idx == self.active_column_idx {
1665 // Active column comes before.
1666 return None;
1667 }
1668
1669 Some((col, x))
1670 })
1671 .flat_map(move |(col, x)| {
1672 zip(&col.tiles, col.tile_ys()).map(move |(tile, y)| {
1673 let tile_pos = Point::from((x, y)) + col.render_offset() + tile.render_offset();
1674 (tile, tile_pos)
1675 })
1676 });
1677
1678 first.chain(next).chain(rest)
1679 }
1680
1681 fn active_column_ref(&self) -> Option<&Column<W>> {
1682 if self.columns.is_empty() {
1683 return None;
1684 }
1685 Some(&self.columns[self.active_column_idx])
1686 }
1687
1688 /// Returns the geometry of the active tile relative to and clamped to the view.
1689 ///
1690 /// During animations, assumes the final view position.
1691 pub fn active_tile_visual_rectangle(&self) -> Option<Rectangle<i32, Logical>> {
1692 let col = self.active_column_ref()?;
1693 let view_pos = self
1694 .view_offset_adj
1695 .as_ref()
1696 .map_or(self.view_offset, |adj| adj.target_view_offset() as i32);
1697
1698 let tile_pos = Point::from((-view_pos, col.tile_y(col.active_tile_idx)));
1699 let tile_size = col.active_tile_ref().tile_size();
1700 let tile_rect = Rectangle::from_loc_and_size(tile_pos, tile_size);
1701
1702 let view = Rectangle::from_loc_and_size((0, 0), self.view_size);
1703 view.intersection(tile_rect)
1704 }
1705
1706 pub fn window_under(
1707 &self,
1708 pos: Point<f64, Logical>,
1709 ) -> Option<(&W, Option<Point<i32, Logical>>)> {
1710 if self.columns.is_empty() {
1711 return None;
1712 }
1713
1714 self.tiles_in_render_order().find_map(|(tile, tile_pos)| {
1715 let pos_within_tile = pos - tile_pos.to_f64();
1716
1717 if tile.is_in_input_region(pos_within_tile) {
1718 let pos_within_surface = tile_pos + tile.buf_loc();
1719 return Some((tile.window(), Some(pos_within_surface)));
1720 } else if tile.is_in_activation_region(pos_within_tile) {
1721 return Some((tile.window(), None));
1722 }
1723
1724 None
1725 })
1726 }
1727
1728 pub fn toggle_width(&mut self) {
1729 if self.columns.is_empty() {
1730 return;
1731 }
1732
1733 self.columns[self.active_column_idx].toggle_width();
1734 }
1735
1736 pub fn toggle_full_width(&mut self) {
1737 if self.columns.is_empty() {
1738 return;
1739 }
1740
1741 self.columns[self.active_column_idx].toggle_full_width();
1742 }
1743
1744 pub fn set_column_width(&mut self, change: SizeChange) {
1745 if self.columns.is_empty() {
1746 return;
1747 }
1748
1749 self.columns[self.active_column_idx].set_column_width(change);
1750 }
1751
1752 pub fn set_window_height(&mut self, change: SizeChange) {
1753 if self.columns.is_empty() {
1754 return;
1755 }
1756
1757 self.columns[self.active_column_idx].set_window_height(change);
1758 }
1759
1760 pub fn set_fullscreen(&mut self, window: &W::Id, is_fullscreen: bool) {
1761 let (mut col_idx, tile_idx) = self
1762 .columns
1763 .iter()
1764 .enumerate()
1765 .find_map(|(col_idx, col)| col.position(window).map(|tile_idx| (col_idx, tile_idx)))
1766 .unwrap();
1767
1768 if is_fullscreen
1769 && col_idx == self.active_column_idx
1770 && self.columns[col_idx].tiles.len() == 1
1771 {
1772 self.view_offset_before_fullscreen = Some(self.static_view_offset());
1773 }
1774
1775 let mut col = &mut self.columns[col_idx];
1776
1777 if is_fullscreen && col.tiles.len() > 1 {
1778 // This wasn't the only window in its column; extract it into a separate column.
1779 let target_window_was_focused =
1780 self.active_column_idx == col_idx && col.active_tile_idx == tile_idx;
1781 let window = col.tiles.remove(tile_idx).into_window();
1782 col.heights.remove(tile_idx);
1783 col.active_tile_idx = min(col.active_tile_idx, col.tiles.len() - 1);
1784 col.update_tile_sizes(false);
1785 let width = col.width;
1786 let is_full_width = col.is_full_width;
1787
1788 col_idx += 1;
1789 self.columns.insert(
1790 col_idx,
1791 Column::new(
1792 window,
1793 self.view_size,
1794 self.working_area,
1795 self.options.clone(),
1796 width,
1797 is_full_width,
1798 false,
1799 ),
1800 );
1801
1802 if target_window_was_focused {
1803 self.activate_column(col_idx);
1804 self.view_offset_before_fullscreen = Some(self.static_view_offset());
1805 } else if self.active_column_idx >= col_idx {
1806 self.active_column_idx += 1;
1807 }
1808
1809 col = &mut self.columns[col_idx];
1810 }
1811
1812 col.set_fullscreen(is_fullscreen);
1813
1814 // If we quickly fullscreen and unfullscreen before any window has a chance to receive the
1815 // request, we need to reset the offset.
1816 if col_idx == self.active_column_idx
1817 && !is_fullscreen
1818 && !col
1819 .tiles
1820 .iter()
1821 .any(|tile| tile.is_fullscreen() || tile.window().is_pending_fullscreen())
1822 {
1823 self.view_offset_before_fullscreen = None;
1824 }
1825 }
1826
1827 pub fn toggle_fullscreen(&mut self, window: &W::Id) {
1828 let col = self
1829 .columns
1830 .iter_mut()
1831 .find(|col| col.contains(window))
1832 .unwrap();
1833 let value = !col.is_fullscreen;
1834 self.set_fullscreen(window, value);
1835 }
1836
1837 pub fn render_above_top_layer(&self) -> bool {
1838 // Render above the top layer if we're on a fullscreen window and the view is stationary.
1839 if self.columns.is_empty() {
1840 return false;
1841 }
1842
1843 if self.view_offset_adj.is_some() {
1844 return false;
1845 }
1846
1847 self.columns[self.active_column_idx].is_fullscreen
1848 }
1849
1850 pub fn render_elements<R: NiriRenderer>(
1851 &self,
1852 renderer: &mut R,
1853 target: RenderTarget,
1854 ) -> Vec<WorkspaceRenderElement<R>> {
1855 // FIXME: workspaces should probably cache their last used scale so they can be correctly
1856 // rendered even with no outputs connected.
1857 let output_scale = self
1858 .output
1859 .as_ref()
1860 .map(|o| Scale::from(o.current_scale().fractional_scale()))
1861 .unwrap_or(Scale::from(1.));
1862
1863 let mut rv = vec![];
1864
1865 // Draw the closing windows on top.
1866 let view_pos = self.view_pos();
1867 for closing in &self.closing_windows {
1868 rv.push(closing.render(view_pos, output_scale, target).into());
1869 }
1870
1871 if self.columns.is_empty() {
1872 return rv;
1873 }
1874
1875 let mut first = true;
1876 for (tile, tile_pos) in self.tiles_in_render_order() {
1877 // For the active tile (which comes first), draw the focus ring.
1878 let focus_ring = first;
1879 first = false;
1880
1881 rv.extend(
1882 tile.render(
1883 renderer,
1884 tile_pos,
1885 output_scale,
1886 self.view_size,
1887 focus_ring,
1888 target,
1889 )
1890 .map(Into::into),
1891 );
1892 }
1893
1894 rv
1895 }
1896
1897 pub fn view_offset_gesture_begin(&mut self) {
1898 if self.columns.is_empty() {
1899 return;
1900 }
1901
1902 let gesture = ViewGesture {
1903 current_view_offset: self.view_offset as f64,
1904 tracker: SwipeTracker::new(),
1905 delta_from_tracker: self.view_offset as f64,
1906 static_view_offset: self.static_view_offset(),
1907 };
1908 self.view_offset_adj = Some(ViewOffsetAdjustment::Gesture(gesture));
1909 }
1910
1911 pub fn view_offset_gesture_update(
1912 &mut self,
1913 delta_x: f64,
1914 timestamp: Duration,
1915 ) -> Option<bool> {
1916 let Some(ViewOffsetAdjustment::Gesture(gesture)) = &mut self.view_offset_adj else {
1917 return None;
1918 };
1919
1920 gesture.tracker.push(delta_x, timestamp);
1921
1922 let norm_factor = self.working_area.size.w as f64 / VIEW_GESTURE_WORKING_AREA_MOVEMENT;
1923 let pos = gesture.tracker.pos() * norm_factor;
1924 let view_offset = pos + gesture.delta_from_tracker;
1925 gesture.current_view_offset = view_offset;
1926
1927 Some(true)
1928 }
1929
1930 pub fn view_offset_gesture_end(&mut self, _cancelled: bool) -> bool {
1931 let Some(ViewOffsetAdjustment::Gesture(gesture)) = &self.view_offset_adj else {
1932 return false;
1933 };
1934
1935 // We do not handle cancelling, just like GNOME Shell doesn't. For this gesture, proper
1936 // cancelling would require keeping track of the original active column, and then updating
1937 // it in all the right places (adding columns, removing columns, etc.) -- quite a bit of
1938 // effort and bug potential.
1939
1940 let norm_factor = self.working_area.size.w as f64 / VIEW_GESTURE_WORKING_AREA_MOVEMENT;
1941 let velocity = gesture.tracker.velocity() * norm_factor;
1942 let pos = gesture.tracker.pos() * norm_factor;
1943 let current_view_offset = pos + gesture.delta_from_tracker;
1944
1945 if self.columns.is_empty() {
1946 self.view_offset = current_view_offset.round() as i32;
1947 self.view_offset_adj = None;
1948 return true;
1949 }
1950
1951 // Figure out where the gesture would stop after deceleration.
1952 let end_pos = gesture.tracker.projected_end_pos() * norm_factor;
1953 let target_view_offset = end_pos + gesture.delta_from_tracker;
1954
1955 // Compute the snapping points. These are where the view aligns with column boundaries on
1956 // either side.
1957 struct Snap {
1958 // View position relative to x = 0 (the first column).
1959 view_pos: i32,
1960 // Column to activate for this snapping point.
1961 col_idx: usize,
1962 }
1963
1964 let mut snapping_points = Vec::new();
1965
1966 let left_strut = self.working_area.loc.x;
1967 let right_strut = self.view_size.w - self.working_area.size.w - self.working_area.loc.x;
1968
1969 if self.options.center_focused_column == CenterFocusedColumn::Always {
1970 let mut col_x = 0;
1971 for (col_idx, col) in self.columns.iter().enumerate() {
1972 let col_w = col.width();
1973
1974 let view_pos = if col.is_fullscreen {
1975 col_x
1976 } else if self.working_area.size.w <= col_w {
1977 col_x - left_strut
1978 } else {
1979 col_x - (self.working_area.size.w - col_w) / 2 - left_strut
1980 };
1981 snapping_points.push(Snap { view_pos, col_idx });
1982
1983 col_x += col_w + self.options.gaps;
1984 }
1985 } else {
1986 let view_width = self.view_size.w;
1987 let mut push = |col_idx, left, right| {
1988 snapping_points.push(Snap {
1989 view_pos: left,
1990 col_idx,
1991 });
1992 snapping_points.push(Snap {
1993 view_pos: right - view_width,
1994 col_idx,
1995 });
1996 };
1997
1998 let mut col_x = 0;
1999 for (col_idx, col) in self.columns.iter().enumerate() {
2000 let col_w = col.width();
2001
2002 // Normal columns align with the working area, but fullscreen columns align with the
2003 // view size.
2004 if col.is_fullscreen {
2005 let left = col_x;
2006 let right = col_x + col_w;
2007 push(col_idx, left, right);
2008 } else {
2009 // Logic from compute_new_view_offset.
2010 let padding =
2011 ((self.working_area.size.w - col_w) / 2).clamp(0, self.options.gaps);
2012 let left = col_x - padding - left_strut;
2013 let right = col_x + col_w + padding + right_strut;
2014 push(col_idx, left, right);
2015 }
2016
2017 col_x += col_w + self.options.gaps;
2018 }
2019 }
2020
2021 // Find the closest snapping point.
2022 snapping_points.sort_by_key(|snap| snap.view_pos);
2023
2024 let active_col_x = self.column_x(self.active_column_idx);
2025 let target_view_pos = (active_col_x as f64 + target_view_offset).round() as i32;
2026 let target_snap = snapping_points
2027 .iter()
2028 .min_by_key(|snap| snap.view_pos.abs_diff(target_view_pos))
2029 .unwrap();
2030
2031 let mut new_col_idx = target_snap.col_idx;
2032
2033 if self.options.center_focused_column != CenterFocusedColumn::Always {
2034 // Focus the furthest window towards the direction of the gesture.
2035 if target_view_offset >= current_view_offset {
2036 for col_idx in (new_col_idx + 1)..self.columns.len() {
2037 let col = &self.columns[col_idx];
2038 let col_x = self.column_x(col_idx);
2039 let col_w = col.width();
2040
2041 if col.is_fullscreen {
2042 if target_snap.view_pos + self.view_size.w < col_x + col_w {
2043 break;
2044 }
2045 } else {
2046 let padding =
2047 ((self.working_area.size.w - col_w) / 2).clamp(0, self.options.gaps);
2048 if target_snap.view_pos + left_strut + self.working_area.size.w
2049 < col_x + col_w + padding
2050 {
2051 break;
2052 }
2053 }
2054
2055 new_col_idx = col_idx;
2056 }
2057 } else {
2058 for col_idx in (0..new_col_idx).rev() {
2059 let col = &self.columns[col_idx];
2060 let col_x = self.column_x(col_idx);
2061 let col_w = col.width();
2062
2063 if col.is_fullscreen {
2064 if col_x < target_snap.view_pos {
2065 break;
2066 }
2067 } else {
2068 let padding =
2069 ((self.working_area.size.w - col_w) / 2).clamp(0, self.options.gaps);
2070 if col_x - padding < target_snap.view_pos + left_strut {
2071 break;
2072 }
2073 }
2074
2075 new_col_idx = col_idx;
2076 }
2077 }
2078 }
2079
2080 let new_col_x = self.column_x(new_col_idx);
2081 let delta = (active_col_x - new_col_x) as f64;
2082 self.view_offset = (current_view_offset + delta).round() as i32;
2083
2084 if self.active_column_idx != new_col_idx {
2085 self.view_offset_before_fullscreen = None;
2086 }
2087
2088 self.active_column_idx = new_col_idx;
2089
2090 let target_view_offset = target_snap.view_pos - new_col_x;
2091
2092 self.view_offset_adj = Some(ViewOffsetAdjustment::Animation(Animation::new(
2093 current_view_offset + delta,
2094 target_view_offset as f64,
2095 velocity,
2096 self.options.animations.horizontal_view_movement.0,
2097 )));
2098
2099 // HACK: deal with things like snapping to the right edge of a larger-than-view window.
2100 self.animate_view_offset_to_column(self.view_pos(), new_col_idx, None);
2101
2102 true
2103 }
2104
2105 pub fn refresh(&mut self, is_active: bool) {
2106 let bounds = self.toplevel_bounds();
2107
2108 for (col_idx, col) in self.columns.iter_mut().enumerate() {
2109 for (tile_idx, tile) in col.tiles.iter_mut().enumerate() {
2110 let win = tile.window_mut();
2111 let active = is_active
2112 && self.active_column_idx == col_idx
2113 && col.active_tile_idx == tile_idx;
2114 win.set_activated(active);
2115
2116 win.set_bounds(bounds);
2117 win.send_pending_configure();
2118 win.refresh();
2119 }
2120 }
2121 }
2122}
2123
2124impl<W: LayoutElement> Column<W> {
2125 fn new(
2126 window: W,
2127 view_size: Size<i32, Logical>,
2128 working_area: Rectangle<i32, Logical>,
2129 options: Rc<Options>,
2130 width: ColumnWidth,
2131 is_full_width: bool,
2132 animate_resize: bool,
2133 ) -> Self {
2134 let tile = Tile::new(window, options.clone());
2135 Self::new_with_tile(
2136 tile,
2137 view_size,
2138 working_area,
2139 options,
2140 width,
2141 is_full_width,
2142 animate_resize,
2143 )
2144 }
2145
2146 fn new_with_tile(
2147 tile: Tile<W>,
2148 view_size: Size<i32, Logical>,
2149 working_area: Rectangle<i32, Logical>,
2150 options: Rc<Options>,
2151 width: ColumnWidth,
2152 is_full_width: bool,
2153 animate_resize: bool,
2154 ) -> Self {
2155 let mut rv = Self {
2156 tiles: vec![],
2157 heights: vec![],
2158 active_tile_idx: 0,
2159 width,
2160 is_full_width,
2161 is_fullscreen: false,
2162 move_animation: None,
2163 width_before_resize: None,
2164 view_size,
2165 working_area,
2166 options,
2167 };
2168
2169 let is_pending_fullscreen = tile.window().is_pending_fullscreen();
2170
2171 rv.add_tile(tile, animate_resize);
2172
2173 if is_pending_fullscreen {
2174 rv.set_fullscreen(true);
2175 }
2176
2177 rv
2178 }
2179
2180 fn set_view_size(&mut self, size: Size<i32, Logical>, working_area: Rectangle<i32, Logical>) {
2181 if self.view_size == size && self.working_area == working_area {
2182 return;
2183 }
2184
2185 self.view_size = size;
2186 self.working_area = working_area;
2187
2188 self.update_tile_sizes(false);
2189 }
2190
2191 fn update_config(&mut self, options: Rc<Options>) {
2192 let mut update_sizes = false;
2193
2194 // If preset widths changed, make our width non-preset.
2195 if self.options.preset_widths != options.preset_widths {
2196 if let ColumnWidth::Preset(idx) = self.width {
2197 self.width = self.options.preset_widths[idx];
2198 }
2199 }
2200
2201 if self.options.gaps != options.gaps {
2202 update_sizes = true;
2203 }
2204
2205 if self.options.border.off != options.border.off
2206 || self.options.border.width != options.border.width
2207 {
2208 update_sizes = true;
2209 }
2210
2211 for tile in &mut self.tiles {
2212 tile.update_config(options.clone());
2213 }
2214
2215 self.options = options;
2216
2217 if update_sizes {
2218 self.update_tile_sizes(false);
2219 }
2220 }
2221
2222 fn set_width(&mut self, width: ColumnWidth) {
2223 self.width = width;
2224 self.is_full_width = false;
2225 self.update_tile_sizes(true);
2226 }
2227
2228 pub fn advance_animations(&mut self, current_time: Duration, is_active: bool) {
2229 match &mut self.move_animation {
2230 Some(anim) => {
2231 anim.set_current_time(current_time);
2232 if anim.is_done() {
2233 self.move_animation = None;
2234 }
2235 }
2236 None => (),
2237 }
2238
2239 for (tile_idx, tile) in self.tiles.iter_mut().enumerate() {
2240 let is_active = is_active && tile_idx == self.active_tile_idx;
2241 tile.advance_animations(current_time, is_active);
2242 }
2243 }
2244
2245 pub fn are_animations_ongoing(&self) -> bool {
2246 self.move_animation.is_some() || self.tiles.iter().any(Tile::are_animations_ongoing)
2247 }
2248
2249 pub fn render_offset(&self) -> Point<i32, Logical> {
2250 let mut offset = Point::from((0., 0.));
2251
2252 if let Some(anim) = &self.move_animation {
2253 offset.x += anim.value();
2254 }
2255
2256 offset.to_i32_round()
2257 }
2258
2259 pub fn animate_move_from(&mut self, from_x_offset: i32) {
2260 self.animate_move_from_with_config(
2261 from_x_offset,
2262 self.options.animations.window_movement.0,
2263 );
2264 }
2265
2266 pub fn animate_move_from_with_config(
2267 &mut self,
2268 from_x_offset: i32,
2269 config: niri_config::Animation,
2270 ) {
2271 let current_offset = self.move_animation.as_ref().map_or(0., Animation::value);
2272
2273 self.move_animation = Some(Animation::new(
2274 f64::from(from_x_offset) + current_offset,
2275 0.,
2276 0.,
2277 config,
2278 ));
2279 }
2280
2281 pub fn contains(&self, window: &W::Id) -> bool {
2282 self.tiles
2283 .iter()
2284 .map(Tile::window)
2285 .any(|win| win.id() == window)
2286 }
2287
2288 pub fn position(&self, window: &W::Id) -> Option<usize> {
2289 self.tiles
2290 .iter()
2291 .map(Tile::window)
2292 .position(|win| win.id() == window)
2293 }
2294
2295 fn activate_window(&mut self, window: &W::Id) {
2296 let idx = self.position(window).unwrap();
2297 self.active_tile_idx = idx;
2298 }
2299
2300 fn add_tile(&mut self, tile: Tile<W>, animate: bool) {
2301 self.is_fullscreen = false;
2302 self.tiles.push(tile);
2303 self.heights.push(WindowHeight::Auto);
2304 self.update_tile_sizes(animate);
2305 }
2306
2307 fn update_window(&mut self, window: &W::Id) {
2308 let (tile_idx, tile) = self
2309 .tiles
2310 .iter_mut()
2311 .enumerate()
2312 .find(|(_, tile)| tile.window().id() == window)
2313 .unwrap();
2314
2315 let height = tile.window().size().h;
2316 let offset = tile
2317 .window()
2318 .animation_snapshot()
2319 .map_or(0, |from| from.size.h - height);
2320
2321 tile.update_window();
2322
2323 // Move windows below in tandem with resizing.
2324 if tile.resize_animation().is_some() && offset != 0 {
2325 for tile in &mut self.tiles[tile_idx + 1..] {
2326 tile.animate_move_from_with_config(
2327 Point::from((0, offset)),
2328 self.options.animations.window_resize.0,
2329 );
2330 }
2331 }
2332 }
2333
2334 fn update_tile_sizes(&mut self, animate: bool) {
2335 if self.is_fullscreen {
2336 self.tiles[0].request_fullscreen(self.view_size);
2337 return;
2338 }
2339
2340 let min_size: Vec<_> = self.tiles.iter().map(Tile::min_size).collect();
2341 let max_size: Vec<_> = self.tiles.iter().map(Tile::max_size).collect();
2342
2343 // Compute the column width.
2344 let min_width = min_size
2345 .iter()
2346 .filter_map(|size| {
2347 let w = size.w;
2348 if w == 0 {
2349 None
2350 } else {
2351 Some(w)
2352 }
2353 })
2354 .max()
2355 .unwrap_or(1);
2356 let max_width = max_size
2357 .iter()
2358 .filter_map(|size| {
2359 let w = size.w;
2360 if w == 0 {
2361 None
2362 } else {
2363 Some(w)
2364 }
2365 })
2366 .min()
2367 .unwrap_or(i32::MAX);
2368 let max_width = max(max_width, min_width);
2369
2370 let width = if self.is_full_width {
2371 ColumnWidth::Proportion(1.)
2372 } else {
2373 self.width
2374 };
2375
2376 let width = width.resolve(&self.options, self.working_area.size.w);
2377 let width = max(min(width, max_width), min_width);
2378
2379 // Compute the tile heights. Start by converting window heights to tile heights.
2380 let mut heights = zip(&self.tiles, &self.heights)
2381 .map(|(tile, height)| match *height {
2382 WindowHeight::Auto => WindowHeight::Auto,
2383 WindowHeight::Fixed(height) => {
2384 WindowHeight::Fixed(tile.tile_height_for_window_height(height))
2385 }
2386 })
2387 .collect::<Vec<_>>();
2388 let mut height_left = self.working_area.size.h - self.options.gaps;
2389 let mut auto_tiles_left = self.tiles.len();
2390
2391 // Subtract all fixed-height tiles.
2392 for (h, (min_size, max_size)) in zip(&mut heights, zip(&min_size, &max_size)) {
2393 // Check if the tile has an exact height constraint.
2394 if min_size.h > 0 && min_size.h == max_size.h {
2395 *h = WindowHeight::Fixed(min_size.h);
2396 }
2397
2398 if let WindowHeight::Fixed(h) = h {
2399 if max_size.h > 0 {
2400 *h = min(*h, max_size.h);
2401 }
2402 if min_size.h > 0 {
2403 *h = max(*h, min_size.h);
2404 }
2405 *h = max(*h, 1);
2406
2407 height_left -= *h + self.options.gaps;
2408 auto_tiles_left -= 1;
2409 }
2410 }
2411
2412 // Iteratively try to distribute the remaining height, checking against tile min heights.
2413 // Pick an auto height according to the current sizes, then check if it satisfies all
2414 // remaining min heights. If not, allocate fixed height to those tiles and repeat the
2415 // loop. On each iteration the auto height will get smaller.
2416 //
2417 // NOTE: we do not respect max height here. Doing so would complicate things: if the current
2418 // auto height is above some tile's max height, then the auto height can become larger.
2419 // Combining this with the min height loop is where the complexity appears.
2420 //
2421 // However, most max height uses are for fixed-size dialogs, where min height == max_height.
2422 // This case is separately handled above.
2423 while auto_tiles_left > 0 {
2424 // Compute the current auto height.
2425 let auto_height = height_left / auto_tiles_left as i32 - self.options.gaps;
2426 let auto_height = max(auto_height, 1);
2427
2428 // Integer division above can result in imperfect height distribution. We will make some
2429 // tiles 1 px taller to account for this.
2430 let mut ones_left = height_left
2431 .saturating_sub((auto_height + self.options.gaps) * auto_tiles_left as i32);
2432
2433 let mut unsatisfied_min = false;
2434 let mut ones_left_2 = ones_left;
2435 for (h, min_size) in zip(&mut heights, &min_size) {
2436 if matches!(h, WindowHeight::Fixed(_)) {
2437 continue;
2438 }
2439
2440 let mut auto = auto_height;
2441 if ones_left_2 > 0 {
2442 auto += 1;
2443 ones_left_2 -= 1;
2444 }
2445
2446 // Check if the auto height satisfies the min height.
2447 if min_size.h > 0 && min_size.h > auto {
2448 *h = WindowHeight::Fixed(min_size.h);
2449 height_left -= min_size.h + self.options.gaps;
2450 auto_tiles_left -= 1;
2451 unsatisfied_min = true;
2452 }
2453 }
2454
2455 // If some min height was unsatisfied, then we allocated the tile more than the auto
2456 // height, which means that the remaining auto tiles now have less height to work
2457 // with, and the loop must run again.
2458 if unsatisfied_min {
2459 continue;
2460 }
2461
2462 // All min heights were satisfied, fill them in.
2463 for h in &mut heights {
2464 if matches!(h, WindowHeight::Fixed(_)) {
2465 continue;
2466 }
2467
2468 let mut auto = auto_height;
2469 if ones_left > 0 {
2470 auto += 1;
2471 ones_left -= 1;
2472 }
2473
2474 *h = WindowHeight::Fixed(auto);
2475 auto_tiles_left -= 1;
2476 }
2477
2478 assert_eq!(auto_tiles_left, 0);
2479 }
2480
2481 for (tile, h) in zip(&mut self.tiles, heights) {
2482 let WindowHeight::Fixed(height) = h else {
2483 unreachable!()
2484 };
2485
2486 let size = Size::from((width, height));
2487 tile.request_tile_size(size, animate);
2488 }
2489 }
2490
2491 fn width(&self) -> i32 {
2492 self.tiles
2493 .iter()
2494 .map(|tile| tile.tile_size().w)
2495 .max()
2496 .unwrap()
2497 }
2498
2499 fn focus_up(&mut self) {
2500 self.active_tile_idx = self.active_tile_idx.saturating_sub(1);
2501 }
2502
2503 fn focus_down(&mut self) {
2504 self.active_tile_idx = min(self.active_tile_idx + 1, self.tiles.len() - 1);
2505 }
2506
2507 fn focus_last(&mut self) {
2508 self.active_tile_idx = self.tiles.len() - 1;
2509 }
2510
2511 fn move_up(&mut self) {
2512 let new_idx = self.active_tile_idx.saturating_sub(1);
2513 if self.active_tile_idx == new_idx {
2514 return;
2515 }
2516
2517 let mut ys = self.tile_ys().skip(self.active_tile_idx);
2518 let active_y = ys.next().unwrap();
2519 let next_y = ys.next().unwrap();
2520 drop(ys);
2521
2522 self.tiles.swap(self.active_tile_idx, new_idx);
2523 self.heights.swap(self.active_tile_idx, new_idx);
2524 self.active_tile_idx = new_idx;
2525
2526 // Animate the movement.
2527 let new_active_y = self.tile_y(new_idx);
2528 self.tiles[new_idx].animate_move_from(Point::from((0, active_y - new_active_y)));
2529 self.tiles[new_idx + 1].animate_move_from(Point::from((0, active_y - next_y)));
2530 }
2531
2532 fn move_down(&mut self) {
2533 let new_idx = min(self.active_tile_idx + 1, self.tiles.len() - 1);
2534 if self.active_tile_idx == new_idx {
2535 return;
2536 }
2537
2538 let mut ys = self.tile_ys().skip(self.active_tile_idx);
2539 let active_y = ys.next().unwrap();
2540 let next_y = ys.next().unwrap();
2541 drop(ys);
2542
2543 self.tiles.swap(self.active_tile_idx, new_idx);
2544 self.heights.swap(self.active_tile_idx, new_idx);
2545 self.active_tile_idx = new_idx;
2546
2547 // Animate the movement.
2548 let new_active_y = self.tile_y(new_idx);
2549 self.tiles[new_idx].animate_move_from(Point::from((0, active_y - new_active_y)));
2550 self.tiles[new_idx - 1].animate_move_from(Point::from((0, next_y - active_y)));
2551 }
2552
2553 #[cfg(test)]
2554 fn verify_invariants(&self) {
2555 assert!(!self.tiles.is_empty(), "columns can't be empty");
2556 assert!(self.active_tile_idx < self.tiles.len());
2557 assert_eq!(self.tiles.len(), self.heights.len());
2558
2559 if self.is_fullscreen {
2560 assert_eq!(self.tiles.len(), 1);
2561 }
2562
2563 for tile in &self.tiles {
2564 assert!(Rc::ptr_eq(&self.options, &tile.options));
2565 assert_eq!(self.is_fullscreen, tile.window().is_pending_fullscreen());
2566 }
2567 }
2568
2569 fn toggle_width(&mut self) {
2570 let width = if self.is_full_width {
2571 ColumnWidth::Proportion(1.)
2572 } else {
2573 self.width
2574 };
2575
2576 let idx = match width {
2577 ColumnWidth::Preset(idx) => (idx + 1) % self.options.preset_widths.len(),
2578 _ => {
2579 let current = self.width();
2580 self.options
2581 .preset_widths
2582 .iter()
2583 .position(|prop| {
2584 prop.resolve(&self.options, self.working_area.size.w) > current
2585 })
2586 .unwrap_or(0)
2587 }
2588 };
2589 let width = ColumnWidth::Preset(idx);
2590 self.set_width(width);
2591 }
2592
2593 fn toggle_full_width(&mut self) {
2594 self.is_full_width = !self.is_full_width;
2595 self.update_tile_sizes(true);
2596 }
2597
2598 fn set_column_width(&mut self, change: SizeChange) {
2599 let width = if self.is_full_width {
2600 ColumnWidth::Proportion(1.)
2601 } else {
2602 self.width
2603 };
2604
2605 let current_px = width.resolve(&self.options, self.working_area.size.w);
2606
2607 let current = match width {
2608 ColumnWidth::Preset(idx) => self.options.preset_widths[idx],
2609 current => current,
2610 };
2611
2612 // FIXME: fix overflows then remove limits.
2613 const MAX_PX: i32 = 100000;
2614 const MAX_F: f64 = 10000.;
2615
2616 let width = match (current, change) {
2617 (_, SizeChange::SetFixed(fixed)) => {
2618 // As a special case, setting a fixed column width will compute it in such a way
2619 // that the active window gets that width. This is the intention behind the ability
2620 // to set a fixed size.
2621 let tile = &self.tiles[self.active_tile_idx];
2622 ColumnWidth::Fixed(tile.tile_width_for_window_width(fixed).clamp(1, MAX_PX))
2623 }
2624 (_, SizeChange::SetProportion(proportion)) => {
2625 ColumnWidth::Proportion((proportion / 100.).clamp(0., MAX_F))
2626 }
2627 (_, SizeChange::AdjustFixed(delta)) => {
2628 let width = current_px.saturating_add(delta).clamp(1, MAX_PX);
2629 ColumnWidth::Fixed(width)
2630 }
2631 (ColumnWidth::Proportion(current), SizeChange::AdjustProportion(delta)) => {
2632 let proportion = (current + delta / 100.).clamp(0., MAX_F);
2633 ColumnWidth::Proportion(proportion)
2634 }
2635 (ColumnWidth::Fixed(_), SizeChange::AdjustProportion(delta)) => {
2636 let current = (current_px + self.options.gaps) as f64
2637 / (self.working_area.size.w - self.options.gaps) as f64;
2638 let proportion = (current + delta / 100.).clamp(0., MAX_F);
2639 ColumnWidth::Proportion(proportion)
2640 }
2641 (ColumnWidth::Preset(_), _) => unreachable!(),
2642 };
2643
2644 self.set_width(width);
2645 }
2646
2647 fn set_window_height(&mut self, change: SizeChange) {
2648 let current = self.heights[self.active_tile_idx];
2649 let tile = &self.tiles[self.active_tile_idx];
2650 let current_window_px = match current {
2651 WindowHeight::Auto => tile.window_size().h,
2652 WindowHeight::Fixed(height) => height,
2653 };
2654 let current_tile_px = tile.tile_height_for_window_height(current_window_px);
2655 let current_prop = (current_tile_px + self.options.gaps) as f64
2656 / (self.working_area.size.h - self.options.gaps) as f64;
2657
2658 // FIXME: fix overflows then remove limits.
2659 const MAX_PX: i32 = 100000;
2660
2661 let mut window_height = match change {
2662 SizeChange::SetFixed(fixed) => fixed,
2663 SizeChange::SetProportion(proportion) => {
2664 let tile_height = ((self.working_area.size.h - self.options.gaps) as f64
2665 * proportion
2666 - self.options.gaps as f64)
2667 .round() as i32;
2668 tile.window_height_for_tile_height(tile_height)
2669 }
2670 SizeChange::AdjustFixed(delta) => current_window_px.saturating_add(delta),
2671 SizeChange::AdjustProportion(delta) => {
2672 let proportion = current_prop + delta / 100.;
2673 let tile_height = ((self.working_area.size.h - self.options.gaps) as f64
2674 * proportion
2675 - self.options.gaps as f64)
2676 .round() as i32;
2677 tile.window_height_for_tile_height(tile_height)
2678 }
2679 };
2680
2681 // Clamp it against the window height constraints.
2682 let win = &self.tiles[self.active_tile_idx].window();
2683 let min_h = win.min_size().h;
2684 let max_h = win.max_size().h;
2685
2686 if max_h > 0 {
2687 window_height = window_height.min(max_h);
2688 }
2689 if min_h > 0 {
2690 window_height = window_height.max(min_h);
2691 }
2692
2693 self.heights[self.active_tile_idx] = WindowHeight::Fixed(window_height.clamp(1, MAX_PX));
2694 self.update_tile_sizes(true);
2695 }
2696
2697 fn set_fullscreen(&mut self, is_fullscreen: bool) {
2698 assert_eq!(self.tiles.len(), 1);
2699 self.is_fullscreen = is_fullscreen;
2700 self.update_tile_sizes(false);
2701 }
2702
2703 pub fn window_y(&self, tile_idx: usize) -> i32 {
2704 let (tile, tile_y) = zip(&self.tiles, self.tile_ys()).nth(tile_idx).unwrap();
2705 tile_y + tile.window_loc().y
2706 }
2707
2708 fn tile_y(&self, tile_idx: usize) -> i32 {
2709 self.tile_ys().nth(tile_idx).unwrap()
2710 }
2711
2712 fn tile_ys(&self) -> impl Iterator<Item = i32> + '_ {
2713 let mut y = 0;
2714
2715 if !self.is_fullscreen {
2716 y = self.working_area.loc.y + self.options.gaps;
2717 }
2718
2719 let heights = self.tiles.iter().map(|tile| tile.tile_size().h);
2720
2721 // Chain an arbitrary height to be able to get the Y that the next tile past the end would
2722 // have.
2723 heights.chain(iter::once(0)).map(move |h| {
2724 let pos = y;
2725 y += h + self.options.gaps;
2726 pos
2727 })
2728 }
2729
2730 fn active_tile_ref(&self) -> &Tile<W> {
2731 &self.tiles[self.active_tile_idx]
2732 }
2733}
2734
2735fn compute_new_view_offset(
2736 cur_x: i32,
2737 view_width: i32,
2738 new_col_x: i32,
2739 new_col_width: i32,
2740 gaps: i32,
2741) -> i32 {
2742 // If the column is wider than the view, always left-align it.
2743 if view_width <= new_col_width {
2744 return 0;
2745 }
2746
2747 // Compute the padding in case it needs to be smaller due to large tile width.
2748 let padding = ((view_width - new_col_width) / 2).clamp(0, gaps);
2749
2750 // Compute the desired new X with padding.
2751 let new_x = new_col_x - padding;
2752 let new_right_x = new_col_x + new_col_width + padding;
2753
2754 // If the column is already fully visible, leave the view as is.
2755 if cur_x <= new_x && new_right_x <= cur_x + view_width {
2756 return -(new_col_x - cur_x);
2757 }
2758
2759 // Otherwise, prefer the aligment that results in less motion from the current position.
2760 let dist_to_left = cur_x.abs_diff(new_x);
2761 let dist_to_right = (cur_x + view_width).abs_diff(new_right_x);
2762 if dist_to_left <= dist_to_right {
2763 -padding
2764 } else {
2765 -(view_width - padding - new_col_width)
2766 }
2767}
2768
2769fn set_preferred_scale_transform(window: &impl LayoutElement, output: &Output) {
2770 // FIXME: cache this on the workspace.
2771 let scale = output.current_scale().integer_scale();
2772 let transform = output.current_transform();
2773 window.set_preferred_scale_transform(scale, transform);
2774}
2775
2776pub fn compute_working_area(output: &Output, struts: Struts) -> Rectangle<i32, Logical> {
2777 // Start with the layer-shell non-exclusive zone.
2778 let mut working_area = layer_map_for_output(output).non_exclusive_zone();
2779
2780 // Add struts.
2781 let w = working_area.size.w;
2782 let h = working_area.size.h;
2783
2784 working_area.size.w = w
2785 .saturating_sub(struts.left.into())
2786 .saturating_sub(struts.right.into());
2787 working_area.loc.x += struts.left as i32;
2788
2789 working_area.size.h = h
2790 .saturating_sub(struts.top.into())
2791 .saturating_sub(struts.bottom.into());
2792 working_area.loc.y += struts.top as i32;
2793
2794 working_area
2795}