forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB53500dcTahinli1 month ago2998 commits

monitor.rs2234 lines, 78.0 KiBHistoryRawDownload
1use std::cmp::min;
2use std::iter::zip;
3use std::rc::Rc;
4use std::time::Duration;
5
6use niri_config::{CornerRadius, LayoutPart};
7use smithay::backend::renderer::element::utils::{
8 CropRenderElement, Relocate, RelocateRenderElement, RescaleRenderElement,
9};
10use smithay::output::Output;
11use smithay::utils::{Logical, Point, Rectangle, Size};
12
13use super::insert_hint_element::{InsertHintElement, InsertHintRenderElement};
14use super::scrolling::{Column, ColumnWidth};
15use super::tile::Tile;
16use super::workspace::{
17 compute_working_area, OutputId, Workspace, WorkspaceAddWindowTarget, WorkspaceId,
18 WorkspaceRenderElement,
19};
20use super::{compute_overview_zoom, ActivateWindow, HitType, LayoutElement, Options};
21use crate::animation::{Animation, Clock};
22use crate::input::swipe_tracker::SwipeTracker;
23use crate::layout::RenderLayer;
24use crate::niri_render_elements;
25use crate::render_helpers::renderer::NiriRenderer;
26use crate::render_helpers::shadow::ShadowRenderElement;
27use crate::render_helpers::solid_color::SolidColorRenderElement;
28use crate::render_helpers::xray::XrayPos;
29use crate::render_helpers::RenderCtx;
30use crate::rubber_band::RubberBand;
31use crate::utils::transaction::Transaction;
32use crate::utils::{
33 output_size, round_logical_in_physical, round_logical_in_physical_max1, ResizeEdge,
34};
35
36/// Amount of touchpad movement to scroll the height of one workspace.
37const WORKSPACE_GESTURE_MOVEMENT: f64 = 300.;
38
39const WORKSPACE_GESTURE_RUBBER_BAND: RubberBand = RubberBand {
40 stiffness: 0.5,
41 limit: 0.05,
42};
43
44/// Amount of DnD edge scrolling to scroll the height of one workspace.
45///
46/// This constant is tied to the default dnd-edge-workspace-switch max-speed setting.
47const WORKSPACE_DND_EDGE_SCROLL_MOVEMENT: f64 = 1500.;
48
49#[derive(Debug)]
50pub struct Monitor<W: LayoutElement> {
51 /// Output for this monitor.
52 pub(super) output: Output,
53 /// Cached name of the output.
54 output_name: String,
55 /// Latest known scale for this output.
56 scale: smithay::output::Scale,
57 /// Latest known size for this output.
58 view_size: Size<f64, Logical>,
59 /// Latest known working area for this output.
60 ///
61 /// Not rounded to physical pixels.
62 // FIXME: since this is used for things like DnD scrolling edges in the overview, ideally this
63 // should only consider overlay and top layer-shell surfaces. However, Smithay doesn't easily
64 // let you do this at the moment.
65 working_area: Rectangle<f64, Logical>,
66 // Must always contain at least one.
67 pub(super) workspaces: Vec<Workspace<W>>,
68 /// Index of the currently active workspace.
69 pub(super) active_workspace_idx: usize,
70 /// ID of the previously active workspace.
71 pub(super) previous_workspace_id: Option<WorkspaceId>,
72 /// In-progress switch between workspaces.
73 pub(super) workspace_switch: Option<WorkspaceSwitch>,
74 /// Indication where an interactively-moved window is about to be placed.
75 pub(super) insert_hint: Option<InsertHint>,
76 /// Insert hint element for rendering.
77 insert_hint_element: InsertHintElement,
78 /// Location to render the insert hint element.
79 insert_hint_render_loc: Option<InsertHintRenderLoc>,
80 /// Whether the overview is open.
81 pub(super) overview_open: bool,
82 /// Progress of the overview zoom animation, 1 is fully in overview.
83 overview_progress: Option<OverviewProgress>,
84 /// Clock for driving animations.
85 pub(super) clock: Clock,
86 /// Configurable properties of the layout as received from the parent layout.
87 pub(super) base_options: Rc<Options>,
88 /// Configurable properties of the layout.
89 pub(super) options: Rc<Options>,
90 /// Layout config overrides for this monitor.
91 layout_config: Option<niri_config::LayoutPart>,
92}
93
94#[derive(Debug)]
95pub enum WorkspaceSwitch {
96 Animation(Animation),
97 Gesture(WorkspaceSwitchGesture),
98}
99
100#[derive(Debug)]
101pub struct WorkspaceSwitchGesture {
102 /// Index of the workspace where the gesture was started.
103 center_idx: usize,
104 /// Fractional workspace index where the gesture was started.
105 ///
106 /// Can differ from center_idx when starting a gesture in the middle between workspaces, for
107 /// example by "catching" an animation.
108 start_idx: f64,
109 /// Current, fractional workspace index.
110 pub(super) current_idx: f64,
111 /// Animation for the extra offset to the current position.
112 ///
113 /// For example, if there's a workspace switch during a DnD scroll.
114 animation: Option<Animation>,
115 tracker: SwipeTracker,
116 /// Whether the gesture is controlled by the touchpad.
117 is_touchpad: bool,
118 /// Whether the gesture is clamped to +-1 workspace around the center.
119 is_clamped: bool,
120
121 // If this gesture is for drag-and-drop scrolling, this is the last event's unadjusted
122 // timestamp.
123 dnd_last_event_time: Option<Duration>,
124 // Time when the drag-and-drop scroll delta became non-zero, used for debouncing.
125 //
126 // If `None` then the scroll delta is currently zero.
127 dnd_nonzero_start_time: Option<Duration>,
128}
129
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub(super) enum InsertPosition {
132 NewColumn(usize),
133 InColumn(usize, usize),
134 Floating,
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub(super) enum InsertWorkspace {
139 Existing(WorkspaceId),
140 NewAt(usize),
141}
142
143#[derive(Debug)]
144pub(super) struct InsertHint {
145 pub workspace: InsertWorkspace,
146 pub position: InsertPosition,
147 pub corner_radius: CornerRadius,
148}
149
150#[derive(Debug, Clone, Copy)]
151struct InsertHintRenderLoc {
152 workspace: InsertWorkspace,
153 location: Point<f64, Logical>,
154}
155
156#[derive(Debug)]
157pub(super) enum OverviewProgress {
158 Animation(Animation),
159 Value(f64),
160}
161
162/// Where to put a newly added window.
163#[derive(Debug, Default, PartialEq, Eq)]
164pub enum MonitorAddWindowTarget<'a, W: LayoutElement> {
165 /// No particular preference.
166 #[default]
167 Auto,
168 /// On this workspace.
169 Workspace {
170 /// Id of the target workspace.
171 id: WorkspaceId,
172 /// Override where the window will open as a new column.
173 column_idx: Option<usize>,
174 },
175 /// Next to this existing window.
176 NextTo(&'a W::Id),
177}
178
179impl<'a, W: LayoutElement> Copy for MonitorAddWindowTarget<'a, W> {}
180
181impl<'a, W: LayoutElement> Clone for MonitorAddWindowTarget<'a, W> {
182 fn clone(&self) -> Self {
183 *self
184 }
185}
186
187niri_render_elements! {
188 MonitorInnerRenderElement<R> => {
189 Workspace = CropRenderElement<WorkspaceRenderElement<R>>,
190 InsertHint = CropRenderElement<InsertHintRenderElement>,
191 UncroppedInsertHint = InsertHintRenderElement,
192 Shadow = ShadowRenderElement,
193 SolidColor = SolidColorRenderElement,
194 }
195}
196
197pub type MonitorRenderElement<R> =
198 RelocateRenderElement<RescaleRenderElement<MonitorInnerRenderElement<R>>>;
199
200impl WorkspaceSwitch {
201 pub fn current_idx(&self) -> f64 {
202 match self {
203 WorkspaceSwitch::Animation(anim) => anim.value(),
204 WorkspaceSwitch::Gesture(gesture) => {
205 gesture.current_idx + gesture.animation.as_ref().map_or(0., |anim| anim.value())
206 }
207 }
208 }
209
210 pub fn target_idx(&self) -> f64 {
211 match self {
212 WorkspaceSwitch::Animation(anim) => anim.to(),
213 WorkspaceSwitch::Gesture(gesture) => gesture.current_idx,
214 }
215 }
216
217 pub fn offset(&mut self, delta: isize) {
218 match self {
219 WorkspaceSwitch::Animation(anim) => anim.offset(delta as f64),
220 WorkspaceSwitch::Gesture(gesture) => {
221 if delta >= 0 {
222 gesture.center_idx += delta as usize;
223 } else {
224 gesture.center_idx -= (-delta) as usize;
225 }
226 gesture.start_idx += delta as f64;
227 gesture.current_idx += delta as f64;
228 }
229 }
230 }
231
232 fn is_animation_ongoing(&self) -> bool {
233 match self {
234 WorkspaceSwitch::Animation(_) => true,
235 WorkspaceSwitch::Gesture(gesture) => gesture.animation.is_some(),
236 }
237 }
238}
239
240impl WorkspaceSwitchGesture {
241 fn min_max(&self, workspace_count: usize) -> (f64, f64) {
242 if self.is_clamped {
243 let min = self.center_idx.saturating_sub(1) as f64;
244 let max = (self.center_idx + 1).min(workspace_count - 1) as f64;
245 (min, max)
246 } else {
247 (0., (workspace_count - 1) as f64)
248 }
249 }
250
251 fn animate_from(&mut self, from: f64, clock: Clock, config: niri_config::Animation) {
252 let current = self.animation.as_ref().map_or(0., Animation::value);
253 self.animation = Some(Animation::new(clock, from + current, 0., 0., config));
254 }
255}
256
257impl InsertWorkspace {
258 fn existing_id(self) -> Option<WorkspaceId> {
259 match self {
260 InsertWorkspace::Existing(id) => Some(id),
261 InsertWorkspace::NewAt(_) => None,
262 }
263 }
264}
265
266impl OverviewProgress {
267 pub fn value(&self) -> f64 {
268 match self {
269 OverviewProgress::Animation(anim) => anim.value(),
270 OverviewProgress::Value(v) => *v,
271 }
272 }
273
274 pub fn clamped_value(&self) -> f64 {
275 match self {
276 OverviewProgress::Animation(anim) => anim.clamped_value(),
277 OverviewProgress::Value(v) => *v,
278 }
279 }
280}
281
282impl From<&super::OverviewProgress> for OverviewProgress {
283 fn from(value: &super::OverviewProgress) -> Self {
284 match value {
285 super::OverviewProgress::Animation(anim) => Self::Animation(anim.clone()),
286 super::OverviewProgress::Gesture(gesture) => Self::Value(gesture.value),
287 super::OverviewProgress::Open => Self::Value(1.),
288 }
289 }
290}
291
292impl<W: LayoutElement> Monitor<W> {
293 pub fn new(
294 output: Output,
295 mut workspaces: Vec<Workspace<W>>,
296 ws_id_to_activate: Option<WorkspaceId>,
297 clock: Clock,
298 base_options: Rc<Options>,
299 layout_config: Option<LayoutPart>,
300 ) -> Self {
301 let options =
302 Rc::new(Options::clone(&base_options).with_merged_layout(layout_config.as_ref()));
303
304 let scale = output.current_scale();
305 let view_size = output_size(&output);
306 let working_area = compute_working_area(&output);
307
308 // Prepare the workspaces: set output, empty first, empty last.
309 let mut active_workspace_idx = 0;
310
311 for (idx, ws) in workspaces.iter_mut().enumerate() {
312 assert!(ws.has_windows_or_name());
313
314 ws.set_output(Some(output.clone()));
315 ws.update_config(options.clone());
316
317 if ws_id_to_activate.is_some_and(|id| ws.id() == id) {
318 active_workspace_idx = idx;
319 }
320 }
321
322 if options.layout.empty_workspace_above_first && !workspaces.is_empty() {
323 let ws = Workspace::new(output.clone(), clock.clone(), options.clone());
324 workspaces.insert(0, ws);
325 active_workspace_idx += 1;
326 }
327
328 let ws = Workspace::new(output.clone(), clock.clone(), options.clone());
329 workspaces.push(ws);
330
331 Self {
332 output_name: output.name(),
333 output,
334 scale,
335 view_size,
336 working_area,
337 workspaces,
338 active_workspace_idx,
339 previous_workspace_id: None,
340 insert_hint: None,
341 insert_hint_element: InsertHintElement::new(options.layout.insert_hint),
342 insert_hint_render_loc: None,
343 overview_open: false,
344 overview_progress: None,
345 workspace_switch: None,
346 clock,
347 base_options,
348 options,
349 layout_config,
350 }
351 }
352
353 pub fn into_workspaces(mut self) -> Vec<Workspace<W>> {
354 self.workspaces.retain(|ws| ws.has_windows_or_name());
355
356 for ws in &mut self.workspaces {
357 ws.set_output(None);
358 }
359
360 self.workspaces
361 }
362
363 pub fn output(&self) -> &Output {
364 &self.output
365 }
366
367 pub fn output_name(&self) -> &String {
368 &self.output_name
369 }
370
371 pub fn active_workspace_idx(&self) -> usize {
372 self.active_workspace_idx
373 }
374
375 pub fn active_workspace_ref(&self) -> &Workspace<W> {
376 &self.workspaces[self.active_workspace_idx]
377 }
378
379 pub fn find_named_workspace(&self, workspace_name: &str) -> Option<&Workspace<W>> {
380 self.workspaces.iter().find(|ws| {
381 ws.name
382 .as_ref()
383 .is_some_and(|name| name.eq_ignore_ascii_case(workspace_name))
384 })
385 }
386
387 pub fn find_named_workspace_index(&self, workspace_name: &str) -> Option<usize> {
388 self.workspaces.iter().position(|ws| {
389 ws.name
390 .as_ref()
391 .is_some_and(|name| name.eq_ignore_ascii_case(workspace_name))
392 })
393 }
394
395 pub fn active_workspace(&mut self) -> &mut Workspace<W> {
396 &mut self.workspaces[self.active_workspace_idx]
397 }
398
399 pub fn idx_of_ws(&self, id: WorkspaceId) -> Option<usize> {
400 self.workspaces.iter().position(|ws| ws.id() == id)
401 }
402
403 pub fn has_ws(&self, id: WorkspaceId) -> bool {
404 self.idx_of_ws(id).is_some()
405 }
406
407 pub fn windows(&self) -> impl Iterator<Item = &W> {
408 self.workspaces.iter().flat_map(|ws| ws.windows())
409 }
410
411 pub fn has_window(&self, window: &W::Id) -> bool {
412 self.windows().any(|win| win.id() == window)
413 }
414
415 pub fn add_workspace_at(&mut self, idx: usize) {
416 let ws = Workspace::new(
417 self.output.clone(),
418 self.clock.clone(),
419 self.options.clone(),
420 );
421
422 self.workspaces.insert(idx, ws);
423 if idx <= self.active_workspace_idx {
424 self.active_workspace_idx += 1;
425 }
426
427 if let Some(switch) = &mut self.workspace_switch {
428 if idx as f64 <= switch.target_idx() {
429 switch.offset(1);
430 }
431 }
432 }
433
434 pub fn add_workspace_top(&mut self) {
435 self.add_workspace_at(0);
436 }
437
438 pub fn add_workspace_bottom(&mut self) {
439 self.add_workspace_at(self.workspaces.len());
440 }
441
442 pub fn activate_workspace(&mut self, idx: usize) {
443 self.activate_workspace_with_anim_config(idx, None);
444 }
445
446 pub fn activate_workspace_with_anim_config(
447 &mut self,
448 idx: usize,
449 config: Option<niri_config::Animation>,
450 ) {
451 // FIXME: also compute and use current velocity.
452 let current_idx = self.workspace_render_idx();
453
454 if self.active_workspace_idx != idx {
455 self.previous_workspace_id = Some(self.workspaces[self.active_workspace_idx].id());
456 }
457
458 let prev_active_idx = self.active_workspace_idx;
459 self.active_workspace_idx = idx;
460
461 let config = config.unwrap_or(self.options.animations.workspace_switch.0);
462
463 match &mut self.workspace_switch {
464 // During a DnD scroll, we want to visually animate even if idx matches the active idx.
465 Some(WorkspaceSwitch::Gesture(gesture)) if gesture.dnd_last_event_time.is_some() => {
466 gesture.center_idx = idx;
467
468 // Adjust start_idx to make current_idx point at idx.
469 let current_pos = gesture.current_idx - gesture.start_idx;
470 gesture.start_idx = idx as f64 - current_pos;
471 let prev_current_idx = gesture.current_idx;
472 gesture.current_idx = idx as f64;
473
474 let current_idx_delta = gesture.current_idx - prev_current_idx;
475 gesture.animate_from(-current_idx_delta, self.clock.clone(), config);
476 }
477 _ => {
478 // Don't animate if nothing changed.
479 if prev_active_idx == idx {
480 return;
481 }
482
483 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
484 self.clock.clone(),
485 current_idx,
486 idx as f64,
487 0.,
488 config,
489 )));
490 }
491 }
492 }
493
494 pub(super) fn resolve_add_window_target<'a>(
495 &mut self,
496 target: MonitorAddWindowTarget<'a, W>,
497 ) -> (usize, WorkspaceAddWindowTarget<'a, W>) {
498 match target {
499 MonitorAddWindowTarget::Auto => {
500 (self.active_workspace_idx, WorkspaceAddWindowTarget::Auto)
501 }
502 MonitorAddWindowTarget::Workspace { id, column_idx } => {
503 let idx = self.idx_of_ws(id).unwrap();
504 let target = if let Some(column_idx) = column_idx {
505 WorkspaceAddWindowTarget::NewColumnAt(column_idx)
506 } else {
507 WorkspaceAddWindowTarget::Auto
508 };
509 (idx, target)
510 }
511 MonitorAddWindowTarget::NextTo(win_id) => {
512 let idx = self
513 .workspaces
514 .iter_mut()
515 .position(|ws| ws.has_window(win_id))
516 .unwrap();
517 (idx, WorkspaceAddWindowTarget::NextTo(win_id))
518 }
519 }
520 }
521
522 pub fn add_window(
523 &mut self,
524 window: W,
525 target: MonitorAddWindowTarget<W>,
526 activate: ActivateWindow,
527 width: ColumnWidth,
528 is_full_width: bool,
529 is_floating: bool,
530 ) {
531 // Currently, everything a workspace sets on a Tile is the same across all workspaces of a
532 // monitor. So we can use any workspace, not necessarily the exact target workspace.
533 let tile = self.workspaces[0].make_tile(window);
534
535 self.add_tile(
536 tile,
537 target,
538 activate,
539 true,
540 width,
541 is_full_width,
542 is_floating,
543 None,
544 );
545 }
546
547 pub fn add_column(
548 &mut self,
549 mut workspace_idx: usize,
550 column: Column<W>,
551 activate: bool,
552 anim: Option<niri_config::Animation>,
553 ) {
554 let workspace = &mut self.workspaces[workspace_idx];
555
556 workspace.add_column(column, activate, anim);
557
558 // After adding a new window, workspace becomes this output's own.
559 if workspace.name().is_none() {
560 workspace.original_outputs = vec![OutputId::new(&self.output)];
561 }
562
563 if workspace_idx == self.workspaces.len() - 1 {
564 self.add_workspace_bottom();
565 }
566 if self.options.layout.empty_workspace_above_first && workspace_idx == 0 {
567 self.add_workspace_top();
568 workspace_idx += 1;
569 }
570
571 if activate {
572 self.activate_workspace(workspace_idx);
573 }
574 }
575
576 #[allow(clippy::too_many_arguments)]
577 pub fn add_tile(
578 &mut self,
579 tile: Tile<W>,
580 target: MonitorAddWindowTarget<W>,
581 activate: ActivateWindow,
582 // FIXME: Refactor ActivateWindow enum to make this better.
583 allow_to_activate_workspace: bool,
584 width: ColumnWidth,
585 is_full_width: bool,
586 is_floating: bool,
587 anim: Option<niri_config::Animation>,
588 ) {
589 let (mut workspace_idx, target) = self.resolve_add_window_target(target);
590
591 let workspace = &mut self.workspaces[workspace_idx];
592
593 workspace.add_tile(
594 tile,
595 target,
596 activate,
597 width,
598 is_full_width,
599 is_floating,
600 anim,
601 );
602
603 // After adding a new window, workspace becomes this output's own.
604 if workspace.name().is_none() {
605 workspace.original_outputs = vec![OutputId::new(&self.output)];
606 }
607
608 if workspace_idx == self.workspaces.len() - 1 {
609 // Insert a new empty workspace.
610 self.add_workspace_bottom();
611 }
612
613 if self.options.layout.empty_workspace_above_first && workspace_idx == 0 {
614 self.add_workspace_top();
615 workspace_idx += 1;
616 }
617
618 if allow_to_activate_workspace && activate.map_smart(|| false) {
619 self.activate_workspace(workspace_idx);
620 }
621 }
622
623 pub fn add_tile_to_column(
624 &mut self,
625 workspace_idx: usize,
626 column_idx: usize,
627 tile_idx: Option<usize>,
628 tile: Tile<W>,
629 activate: bool,
630 // FIXME: Refactor ActivateWindow enum to make this better.
631 allow_to_activate_workspace: bool,
632 ) {
633 let workspace = &mut self.workspaces[workspace_idx];
634
635 workspace.add_tile_to_column(column_idx, tile_idx, tile, activate);
636
637 // After adding a new window, workspace becomes this output's own.
638 if workspace.name().is_none() {
639 workspace.original_outputs = vec![OutputId::new(&self.output)];
640 }
641
642 // Since we're adding window to an existing column, the workspace isn't empty, and
643 // therefore cannot be the last one, so we never need to insert a new empty workspace.
644
645 if allow_to_activate_workspace && activate {
646 self.activate_workspace(workspace_idx);
647 }
648 }
649
650 pub fn clean_up_workspaces(&mut self) {
651 assert!(self.workspace_switch.is_none());
652
653 let range_start = if self.options.layout.empty_workspace_above_first {
654 1
655 } else {
656 0
657 };
658 for idx in (range_start..self.workspaces.len() - 1).rev() {
659 if self.active_workspace_idx == idx {
660 continue;
661 }
662
663 if !self.workspaces[idx].has_windows_or_name() {
664 self.workspaces.remove(idx);
665 if self.active_workspace_idx > idx {
666 self.active_workspace_idx -= 1;
667 }
668 }
669 }
670
671 // Special case handling when empty_workspace_above_first is set and all workspaces
672 // are empty.
673 if self.options.layout.empty_workspace_above_first && self.workspaces.len() == 2 {
674 assert!(!self.workspaces[0].has_windows_or_name());
675 assert!(!self.workspaces[1].has_windows_or_name());
676 self.workspaces.remove(1);
677 self.active_workspace_idx = 0;
678 }
679 }
680
681 pub fn unname_workspace(&mut self, id: WorkspaceId) -> bool {
682 let Some(idx) = self.idx_of_ws(id) else {
683 return false;
684 };
685 let ws = &mut self.workspaces[idx];
686
687 ws.unname();
688
689 if self.workspace_switch.is_none() {
690 self.clean_up_workspaces();
691 }
692
693 true
694 }
695
696 pub fn remove_workspace_by_idx(&mut self, mut idx: usize) -> Workspace<W> {
697 if idx == self.workspaces.len() - 1 {
698 self.add_workspace_bottom();
699 }
700 if self.options.layout.empty_workspace_above_first && idx == 0 {
701 self.add_workspace_top();
702 idx += 1;
703 }
704
705 let mut ws = self.workspaces.remove(idx);
706 ws.set_output(None);
707
708 // For monitor current workspace removal, we focus previous rather than next (<= rather
709 // than <). This is different from columns and tiles, but it lets move-workspace-to-monitor
710 // back and forth to preserve position.
711 if idx <= self.active_workspace_idx && self.active_workspace_idx > 0 {
712 self.active_workspace_idx -= 1;
713 }
714
715 self.workspace_switch = None;
716 self.clean_up_workspaces();
717
718 ws
719 }
720
721 pub fn insert_workspace(&mut self, mut ws: Workspace<W>, mut idx: usize, activate: bool) {
722 ws.set_output(Some(self.output.clone()));
723 ws.update_config(self.options.clone());
724
725 // Don't insert past the last empty workspace.
726 if idx == self.workspaces.len() {
727 idx -= 1;
728 }
729 if idx == 0 && self.options.layout.empty_workspace_above_first {
730 // Insert a new empty workspace on top to prepare for insertion of new workspace.
731 self.add_workspace_top();
732 idx += 1;
733 }
734
735 self.workspaces.insert(idx, ws);
736
737 if idx <= self.active_workspace_idx {
738 self.active_workspace_idx += 1;
739 }
740
741 if activate {
742 self.workspace_switch = None;
743 self.activate_workspace(idx);
744 }
745
746 self.workspace_switch = None;
747 self.clean_up_workspaces();
748 }
749
750 pub fn append_workspaces(&mut self, mut workspaces: Vec<Workspace<W>>) {
751 if workspaces.is_empty() {
752 return;
753 }
754
755 for ws in &mut workspaces {
756 ws.set_output(Some(self.output.clone()));
757 ws.update_config(self.options.clone());
758 }
759
760 let empty_was_focused = self.active_workspace_idx == self.workspaces.len() - 1;
761
762 // Push the workspaces from the removed monitor in the end, right before the
763 // last, empty, workspace.
764 let empty = self.workspaces.remove(self.workspaces.len() - 1);
765 self.workspaces.extend(workspaces);
766 self.workspaces.push(empty);
767
768 // If empty_workspace_above_first is set and the first workspace is now no longer empty,
769 // add a new empty workspace on top.
770 if self.options.layout.empty_workspace_above_first
771 && self.workspaces[0].has_windows_or_name()
772 {
773 self.add_workspace_top();
774 }
775
776 // If the empty workspace was focused on the primary monitor, keep it focused.
777 if empty_was_focused {
778 self.active_workspace_idx = self.workspaces.len() - 1;
779 }
780
781 // FIXME: if we're adding workspaces to currently invisible positions
782 // (outside the workspace switch), we don't need to cancel it.
783 self.workspace_switch = None;
784 self.clean_up_workspaces();
785 }
786
787 pub fn move_down_or_to_workspace_down(&mut self) {
788 if !self.active_workspace().move_down() {
789 self.move_to_workspace_down(ActivateWindow::Smart);
790 }
791 }
792
793 pub fn move_up_or_to_workspace_up(&mut self) {
794 if !self.active_workspace().move_up() {
795 self.move_to_workspace_up(ActivateWindow::Smart);
796 }
797 }
798
799 pub fn focus_window_or_workspace_down(&mut self) {
800 if !self.active_workspace().focus_down() {
801 self.switch_workspace_down();
802 }
803 }
804
805 pub fn focus_window_or_workspace_up(&mut self) {
806 if !self.active_workspace().focus_up() {
807 self.switch_workspace_up();
808 }
809 }
810
811 pub fn move_to_workspace_up(&mut self, activate: ActivateWindow) {
812 let new_idx = self.active_workspace_idx.saturating_sub(1);
813 self.move_to_workspace(None, new_idx, activate);
814 }
815
816 pub fn move_to_workspace_down(&mut self, activate: ActivateWindow) {
817 let new_idx = min(self.active_workspace_idx + 1, self.workspaces.len() - 1);
818 self.move_to_workspace(None, new_idx, activate);
819 }
820
821 pub fn move_to_workspace(
822 &mut self,
823 window: Option<&W::Id>,
824 idx: usize,
825 activate: ActivateWindow,
826 ) {
827 let source_workspace_idx = if let Some(window) = window {
828 self.workspaces
829 .iter()
830 .position(|ws| ws.has_window(window))
831 .unwrap()
832 } else {
833 self.active_workspace_idx
834 };
835 let source_id = self.workspaces[source_workspace_idx].id();
836
837 let new_idx = min(idx, self.workspaces.len() - 1);
838 if new_idx == source_workspace_idx {
839 return;
840 }
841 let new_id = self.workspaces[new_idx].id();
842
843 let activate = activate.map_smart(|| {
844 window.is_none_or(|win| self.active_window().map(|win| win.id()) == Some(win))
845 });
846
847 let workspace = &mut self.workspaces[source_workspace_idx];
848 let Some(window) = window.or_else(|| workspace.active_window().map(|win| win.id())) else {
849 return;
850 };
851 let window = window.clone();
852
853 let mut old_render_pos = workspace
854 .tiles_with_render_positions()
855 .find_map(|(tile, offset, _visible)| (tile.window().id() == &window).then_some(offset))
856 .unwrap();
857
858 let transaction = Transaction::new();
859 let removed = workspace.remove_tile(&window, transaction);
860
861 // If the view is following the tile, match the animation.
862 let config = if activate {
863 self.options.animations.workspace_switch.0
864 } else {
865 self.options.animations.window_movement.0
866 };
867
868 self.add_tile(
869 removed.tile,
870 MonitorAddWindowTarget::Workspace {
871 id: new_id,
872 column_idx: None,
873 },
874 if activate {
875 ActivateWindow::Yes
876 } else {
877 ActivateWindow::No
878 },
879 true,
880 removed.width,
881 removed.is_full_width,
882 removed.is_floating,
883 Some(config),
884 );
885
886 if self.workspace_switch.is_none() {
887 self.clean_up_workspaces();
888 }
889
890 let new_idx = self.idx_of_ws(new_id).unwrap();
891
892 // Animate vertical movement between workspaces.
893 //
894 // Recompute the source idx in case some workspace was removed during clean-up. If the
895 // source workspace itself was removed, don't bother animating this since the removal is
896 // instant anyway.
897 if let Some(source_workspace_idx) = self.idx_of_ws(source_id) {
898 old_render_pos.y +=
899 self.workspace_size_with_gap(1.).h * (source_workspace_idx as f64 - new_idx as f64);
900 }
901
902 let (tile, new_render_pos) = self.workspaces[new_idx]
903 .tiles_with_render_positions_mut(false)
904 .find(|(tile, _)| tile.window().id() == &window)
905 .unwrap();
906 tile.animate_move_from_with_config(old_render_pos - new_render_pos, config);
907 tile.set_anim_y_between_workspaces();
908 }
909
910 pub fn move_column_to_workspace_up(&mut self, activate: bool) {
911 let new_idx = self.active_workspace_idx.saturating_sub(1);
912 self.move_column_to_workspace(new_idx, activate);
913 }
914
915 pub fn move_column_to_workspace_down(&mut self, activate: bool) {
916 let new_idx = min(self.active_workspace_idx + 1, self.workspaces.len() - 1);
917 self.move_column_to_workspace(new_idx, activate);
918 }
919
920 pub fn move_column_to_workspace(&mut self, idx: usize, activate: bool) {
921 let source_workspace_idx = self.active_workspace_idx;
922
923 let new_idx = min(idx, self.workspaces.len() - 1);
924 if new_idx == source_workspace_idx {
925 return;
926 }
927
928 let workspace = &mut self.workspaces[source_workspace_idx];
929 if workspace.floating_is_active() {
930 let activate = if activate {
931 ActivateWindow::Smart
932 } else {
933 ActivateWindow::No
934 };
935 self.move_to_workspace(None, idx, activate);
936 return;
937 }
938
939 let Some(id) = workspace.scrolling().active_column().map(Column::id) else {
940 return;
941 };
942 let mut old_render_pos = workspace
943 .scrolling()
944 .columns_with_render_positions()
945 .find_map(|(col, pos)| (col.id() == id).then_some(pos))
946 .unwrap();
947
948 let column = workspace.remove_active_column().unwrap();
949
950 // Animate vertical movement between workspaces.
951 old_render_pos.y +=
952 self.workspace_size_with_gap(1.).h * (source_workspace_idx as f64 - new_idx as f64);
953
954 // If the view is following the column, match the animation.
955 let config = if activate {
956 self.options.animations.workspace_switch.0
957 } else {
958 self.options.animations.window_movement.0
959 };
960
961 let new_id = self.workspaces[new_idx].id();
962 self.add_column(new_idx, column, activate, Some(config));
963
964 let new_idx = self.idx_of_ws(new_id).unwrap();
965 let (column, new_render_pos) = self.workspaces[new_idx]
966 .scrolling_mut()
967 .columns_with_render_positions_mut()
968 .find(|(col, _pos)| col.id() == id)
969 .unwrap();
970 column.animate_move_from_with_config(old_render_pos - new_render_pos, config);
971 column.set_anim_y_between_workspaces();
972 }
973
974 pub fn switch_workspace_up(&mut self) {
975 let new_idx = match &self.workspace_switch {
976 // During a DnD scroll, select the prev apparent workspace.
977 Some(WorkspaceSwitch::Gesture(gesture)) if gesture.dnd_last_event_time.is_some() => {
978 let current = gesture.current_idx;
979 let new = current.ceil() - 1.;
980 new.clamp(0., (self.workspaces.len() - 1) as f64) as usize
981 }
982 _ => self.active_workspace_idx.saturating_sub(1),
983 };
984
985 self.activate_workspace(new_idx);
986 }
987
988 pub fn switch_workspace_down(&mut self) {
989 let new_idx = match &self.workspace_switch {
990 // During a DnD scroll, select the next apparent workspace.
991 Some(WorkspaceSwitch::Gesture(gesture)) if gesture.dnd_last_event_time.is_some() => {
992 let current = gesture.current_idx;
993 let new = current.floor() + 1.;
994 new.clamp(0., (self.workspaces.len() - 1) as f64) as usize
995 }
996 _ => min(self.active_workspace_idx + 1, self.workspaces.len() - 1),
997 };
998
999 self.activate_workspace(new_idx);
1000 }
1001
1002 fn previous_workspace_idx(&self) -> Option<usize> {
1003 let id = self.previous_workspace_id?;
1004 self.idx_of_ws(id)
1005 }
1006
1007 pub fn switch_workspace(&mut self, idx: usize) {
1008 self.activate_workspace(min(idx, self.workspaces.len() - 1));
1009 }
1010
1011 pub fn switch_workspace_auto_back_and_forth(&mut self, idx: usize) {
1012 let idx = min(idx, self.workspaces.len() - 1);
1013
1014 if idx == self.active_workspace_idx {
1015 if let Some(prev_idx) = self.previous_workspace_idx() {
1016 self.switch_workspace(prev_idx);
1017 }
1018 } else {
1019 self.switch_workspace(idx);
1020 }
1021 }
1022
1023 pub fn switch_workspace_previous(&mut self) {
1024 if let Some(idx) = self.previous_workspace_idx() {
1025 self.switch_workspace(idx);
1026 }
1027 }
1028
1029 pub fn active_window(&self) -> Option<&W> {
1030 self.active_workspace_ref().active_window()
1031 }
1032
1033 pub fn advance_animations(&mut self) {
1034 match &mut self.workspace_switch {
1035 Some(WorkspaceSwitch::Animation(anim)) => {
1036 if anim.is_done() {
1037 self.workspace_switch = None;
1038 self.clean_up_workspaces();
1039 }
1040 }
1041 Some(WorkspaceSwitch::Gesture(gesture)) => {
1042 // Make sure the last event time doesn't go too much out of date (for
1043 // monitors not under cursor), causing sudden jumps.
1044 //
1045 // This happens after any dnd_scroll_gesture_scroll() calls (in
1046 // Layout::advance_animations()), so it doesn't mess up the time delta there.
1047 if let Some(last_time) = &mut gesture.dnd_last_event_time {
1048 let now = self.clock.now_unadjusted();
1049 if *last_time != now {
1050 *last_time = now;
1051
1052 // If last_time was already == now, then dnd_scroll_gesture_scroll() must've
1053 // updated the gesture already. Therefore, when this code runs, the pointer
1054 // must be outside the DnD scrolling zone.
1055 gesture.dnd_nonzero_start_time = None;
1056 }
1057 }
1058
1059 if let Some(anim) = &mut gesture.animation {
1060 if anim.is_done() {
1061 gesture.animation = None;
1062 }
1063 }
1064 }
1065 None => (),
1066 }
1067
1068 for ws in &mut self.workspaces {
1069 ws.advance_animations();
1070 }
1071 }
1072
1073 pub(super) fn are_animations_ongoing(&self) -> bool {
1074 self.workspace_switch
1075 .as_ref()
1076 .is_some_and(|s| s.is_animation_ongoing())
1077 || self.workspaces.iter().any(|ws| ws.are_animations_ongoing())
1078 }
1079
1080 pub fn are_transitions_ongoing(&self) -> bool {
1081 self.workspace_switch.is_some()
1082 || self
1083 .workspaces
1084 .iter()
1085 .any(|ws| ws.are_transitions_ongoing())
1086 }
1087
1088 pub fn update_render_elements(&mut self, is_active: bool) {
1089 let mut insert_hint_ws_geo = None;
1090 let insert_hint_ws_id = self
1091 .insert_hint
1092 .as_ref()
1093 .and_then(|hint| hint.workspace.existing_id());
1094
1095 for ws in &mut self.workspaces {
1096 ws.update_render_elements(is_active, RenderLayer::MovingBetweenWorkspaces);
1097 }
1098
1099 for (ws, geo) in self.workspaces_with_render_geo_mut(true) {
1100 ws.update_render_elements(is_active, RenderLayer::Normal);
1101
1102 if Some(ws.id()) == insert_hint_ws_id {
1103 insert_hint_ws_geo = Some(geo);
1104 }
1105 }
1106
1107 self.insert_hint_render_loc = None;
1108 if let Some(hint) = &self.insert_hint {
1109 match hint.workspace {
1110 InsertWorkspace::Existing(ws_id) => {
1111 if let Some(idx) = self.idx_of_ws(ws_id) {
1112 let ws = &self.workspaces[idx];
1113 if let Some(mut area) = ws.insert_hint_area(hint.position) {
1114 let scale = ws.scale().fractional_scale();
1115 let view_size = ws.view_size();
1116
1117 // Make sure the hint is at least partially visible.
1118 if matches!(hint.position, InsertPosition::NewColumn(_)) {
1119 let zoom = self.overview_zoom();
1120 let geo = insert_hint_ws_geo.unwrap();
1121 let geo = geo.downscale(zoom);
1122
1123 area.loc.x = area.loc.x.max(-geo.loc.x - area.size.w / 2.);
1124 area.loc.x =
1125 area.loc.x.min(geo.loc.x + geo.size.w - area.size.w / 2.);
1126 }
1127
1128 // Round to physical pixels.
1129 area = area.to_physical_precise_round(scale).to_logical(scale);
1130
1131 let view_rect = Rectangle::new(area.loc.upscale(-1.), view_size);
1132 self.insert_hint_element.update_render_elements(
1133 area.size,
1134 view_rect,
1135 hint.corner_radius,
1136 scale,
1137 );
1138 self.insert_hint_render_loc = Some(InsertHintRenderLoc {
1139 workspace: hint.workspace,
1140 location: area.loc,
1141 });
1142 }
1143 } else {
1144 error!("insert hint workspace missing from monitor");
1145 }
1146 }
1147 InsertWorkspace::NewAt(ws_idx) => {
1148 let scale = self.scale.fractional_scale();
1149 let zoom = self.overview_zoom();
1150 let gap = self.workspace_gap(zoom);
1151
1152 let hint_gap = round_logical_in_physical(scale, gap * 0.1);
1153 let hint_height = gap - hint_gap * 2.;
1154
1155 let next_ws_geo = self.workspaces_render_geo().nth(ws_idx).unwrap();
1156 let hint_width = round_logical_in_physical(scale, next_ws_geo.size.w * 0.75);
1157 let hint_x =
1158 round_logical_in_physical(scale, (next_ws_geo.size.w - hint_width) / 2.);
1159
1160 let hint_loc_diff = Point::from((-hint_x, hint_height + hint_gap));
1161 let hint_loc = next_ws_geo.loc - hint_loc_diff;
1162 let hint_size = Size::from((hint_width, hint_height));
1163
1164 // Sometimes the hint ends up 1 px wider than necessary and/or 1 px
1165 // narrower than necessary. The values here seem correct. Might have to do with
1166 // how zooming out currently doesn't round to output scale properly.
1167
1168 // Compute view rect as if we're above the next workspace (rather than below
1169 // the previous one).
1170 let view_rect = Rectangle::new(hint_loc_diff, next_ws_geo.size);
1171
1172 self.insert_hint_element.update_render_elements(
1173 hint_size,
1174 view_rect,
1175 CornerRadius::default(),
1176 scale,
1177 );
1178 self.insert_hint_render_loc = Some(InsertHintRenderLoc {
1179 workspace: hint.workspace,
1180 location: hint_loc,
1181 });
1182 }
1183 }
1184 }
1185 }
1186
1187 pub fn update_config(&mut self, base_options: Rc<Options>) {
1188 let options =
1189 Rc::new(Options::clone(&base_options).with_merged_layout(self.layout_config.as_ref()));
1190
1191 if self.options.layout.empty_workspace_above_first
1192 != options.layout.empty_workspace_above_first
1193 && self.workspaces.len() > 1
1194 {
1195 if options.layout.empty_workspace_above_first {
1196 self.add_workspace_top();
1197 } else if self.workspace_switch.is_none() && self.active_workspace_idx != 0 {
1198 self.workspaces.remove(0);
1199 self.active_workspace_idx = self.active_workspace_idx.saturating_sub(1);
1200 }
1201 }
1202
1203 for ws in &mut self.workspaces {
1204 ws.update_config(options.clone());
1205 }
1206
1207 self.insert_hint_element
1208 .update_config(options.layout.insert_hint);
1209
1210 self.base_options = base_options;
1211 self.options = options;
1212 }
1213
1214 pub fn update_layout_config(&mut self, layout_config: Option<niri_config::LayoutPart>) -> bool {
1215 if self.layout_config == layout_config {
1216 return false;
1217 }
1218
1219 self.layout_config = layout_config;
1220 self.update_config(self.base_options.clone());
1221
1222 true
1223 }
1224
1225 pub fn update_shaders(&mut self) {
1226 for ws in &mut self.workspaces {
1227 ws.update_shaders();
1228 }
1229
1230 self.insert_hint_element.update_shaders();
1231 }
1232
1233 pub fn update_output_size(&mut self) {
1234 self.scale = self.output.current_scale();
1235 self.view_size = output_size(&self.output);
1236 self.working_area = compute_working_area(&self.output);
1237
1238 for ws in &mut self.workspaces {
1239 ws.update_output_size();
1240 }
1241 }
1242
1243 pub fn move_workspace_down(&mut self) {
1244 let mut new_idx = min(self.active_workspace_idx + 1, self.workspaces.len() - 1);
1245 if new_idx == self.active_workspace_idx {
1246 return;
1247 }
1248
1249 self.workspaces.swap(self.active_workspace_idx, new_idx);
1250
1251 if new_idx == self.workspaces.len() - 1 {
1252 // Insert a new empty workspace.
1253 self.add_workspace_bottom();
1254 }
1255
1256 if self.options.layout.empty_workspace_above_first && self.active_workspace_idx == 0 {
1257 self.add_workspace_top();
1258 new_idx += 1;
1259 }
1260
1261 let previous_workspace_id = self.previous_workspace_id;
1262 self.activate_workspace(new_idx);
1263 self.workspace_switch = None;
1264 self.previous_workspace_id = previous_workspace_id;
1265
1266 self.clean_up_workspaces();
1267 }
1268
1269 pub fn move_workspace_up(&mut self) {
1270 let mut new_idx = self.active_workspace_idx.saturating_sub(1);
1271 if new_idx == self.active_workspace_idx {
1272 return;
1273 }
1274
1275 self.workspaces.swap(self.active_workspace_idx, new_idx);
1276
1277 if self.active_workspace_idx == self.workspaces.len() - 1 {
1278 // Insert a new empty workspace.
1279 self.add_workspace_bottom();
1280 }
1281
1282 if self.options.layout.empty_workspace_above_first && new_idx == 0 {
1283 self.add_workspace_top();
1284 new_idx += 1;
1285 }
1286
1287 let previous_workspace_id = self.previous_workspace_id;
1288 self.activate_workspace(new_idx);
1289 self.workspace_switch = None;
1290 self.previous_workspace_id = previous_workspace_id;
1291
1292 self.clean_up_workspaces();
1293 }
1294
1295 pub fn move_workspace_to_idx(&mut self, old_idx: usize, new_idx: usize) {
1296 if self.workspaces.len() <= old_idx {
1297 return;
1298 }
1299
1300 let mut new_idx = new_idx.clamp(0, self.workspaces.len() - 1);
1301 if old_idx == new_idx {
1302 return;
1303 }
1304
1305 let ws = self.workspaces.remove(old_idx);
1306 self.workspaces.insert(new_idx, ws);
1307
1308 if new_idx > old_idx {
1309 if new_idx == self.workspaces.len() - 1 {
1310 // Insert a new empty workspace.
1311 self.add_workspace_bottom();
1312 }
1313
1314 if self.options.layout.empty_workspace_above_first && old_idx == 0 {
1315 self.add_workspace_top();
1316 new_idx += 1;
1317 }
1318 } else {
1319 if old_idx == self.workspaces.len() - 1 {
1320 // Insert a new empty workspace.
1321 self.add_workspace_bottom();
1322 }
1323
1324 if self.options.layout.empty_workspace_above_first && new_idx == 0 {
1325 self.add_workspace_top();
1326 new_idx += 1;
1327 }
1328 }
1329
1330 // Only refocus the workspace if it was already focused
1331 if self.active_workspace_idx == old_idx {
1332 self.active_workspace_idx = new_idx;
1333 // If the workspace order was switched so that the current workspace moved down the
1334 // workspace stack, focus correctly
1335 } else if new_idx <= self.active_workspace_idx && old_idx > self.active_workspace_idx {
1336 self.active_workspace_idx += 1;
1337 } else if new_idx >= self.active_workspace_idx && old_idx < self.active_workspace_idx {
1338 self.active_workspace_idx = self.active_workspace_idx.saturating_sub(1);
1339 }
1340
1341 self.workspace_switch = None;
1342
1343 self.clean_up_workspaces();
1344 }
1345
1346 /// Returns the geometry of the active window relative to and clamped to the output.
1347 ///
1348 /// During animations, assumes the final view position.
1349 pub fn active_window_visual_rectangle(&self) -> Option<Rectangle<f64, Logical>> {
1350 if self.overview_open {
1351 return None;
1352 }
1353
1354 self.active_workspace_ref().active_window_visual_rectangle()
1355 }
1356
1357 fn workspace_size(&self, zoom: f64) -> Size<f64, Logical> {
1358 let ws_size = self.view_size.upscale(zoom);
1359 let scale = self.scale.fractional_scale();
1360 ws_size.to_physical_precise_ceil(scale).to_logical(scale)
1361 }
1362
1363 fn workspace_gap(&self, zoom: f64) -> f64 {
1364 let scale = self.scale.fractional_scale();
1365 let gap = self.view_size.h * 0.1 * zoom;
1366 round_logical_in_physical_max1(scale, gap)
1367 }
1368
1369 fn workspace_size_with_gap(&self, zoom: f64) -> Size<f64, Logical> {
1370 let gap = self.workspace_gap(zoom);
1371 self.workspace_size(zoom) + Size::from((0., gap))
1372 }
1373
1374 pub fn overview_zoom(&self) -> f64 {
1375 let progress = self.overview_progress.as_ref().map(|p| p.value());
1376 compute_overview_zoom(&self.options, progress)
1377 }
1378
1379 pub(super) fn set_overview_progress(&mut self, progress: Option<&super::OverviewProgress>) {
1380 let prev_render_idx = self.workspace_render_idx();
1381 self.overview_progress = progress.map(OverviewProgress::from);
1382 let new_render_idx = self.workspace_render_idx();
1383
1384 // If the view jumped (can happen when going from corrected to uncorrected render_idx, for
1385 // example when toggling the overview in the middle of an overview animation), then restart
1386 // the workspace switch to avoid jumps.
1387 if prev_render_idx != new_render_idx {
1388 if let Some(WorkspaceSwitch::Animation(anim)) = &mut self.workspace_switch {
1389 // FIXME: maintain velocity.
1390 *anim = anim.restarted(prev_render_idx, anim.to(), 0.);
1391 }
1392 }
1393 }
1394
1395 #[cfg(test)]
1396 pub(super) fn overview_progress_value(&self) -> Option<f64> {
1397 self.overview_progress.as_ref().map(|p| p.value())
1398 }
1399
1400 pub fn workspace_render_idx(&self) -> f64 {
1401 // If workspace switch and overview progress are matching animations, then compute a
1402 // correction term to make the movement appear monotonic.
1403 if let (
1404 Some(WorkspaceSwitch::Animation(switch_anim)),
1405 Some(OverviewProgress::Animation(progress_anim)),
1406 ) = (&self.workspace_switch, &self.overview_progress)
1407 {
1408 if switch_anim.start_time() == progress_anim.start_time()
1409 && (switch_anim.duration().as_secs_f64() - progress_anim.duration().as_secs_f64())
1410 .abs()
1411 <= 0.001
1412 {
1413 #[rustfmt::skip]
1414 // How this was derived:
1415 //
1416 // - Assume we're animating a zoom + switch. Consider switch "from" and "to".
1417 // These are render_idx values, so first workspace to second would have switch
1418 // from = 0. and to = 1. regardless of the zoom level.
1419 //
1420 // - At the start, the point at "from" is at Y = 0. We're moving the point at "to"
1421 // to Y = 0. We want this to be a monotonic motion in apparent coordinates (after
1422 // zoom).
1423 //
1424 // - Height at the start:
1425 // from_height = (size.h + gap) * from_zoom.
1426 //
1427 // - Current height:
1428 // current_height = (size.h + gap) * zoom.
1429 //
1430 // - We're moving the "to" point to Y = 0:
1431 // to_y = 0.
1432 //
1433 // - The initial position of the point we're moving:
1434 // from_y = (to - from) * from_height.
1435 //
1436 // - We want this point to travel monotonically in apparent coordinates:
1437 // current_y = from_y + (to_y - from_y) * progress,
1438 // where progress is from 0 to 1, equals to the animation progress (switch and
1439 // zoom are the same since they are synchronized).
1440 //
1441 // - Derive the Y of the first workspace from this:
1442 // first_y = current_y - to * current_height.
1443 //
1444 // Now, let's substitute and rearrange the terms.
1445 //
1446 // - current_y = from_y + (0 - (to - from) * from_height) * progress
1447 // - progress = (switch_anim.value() - from) / (to - from)
1448 // - current_y = from_y - (to - from) * from_height * (switch_anim.value() - from) / (to - from)
1449 // - current_y = from_y - from_height * (switch_anim.value() - from)
1450 // - first_y = from_y - from_height * (switch_anim.value() - from) - to * current_height
1451 // - first_y = (to - from) * from_height - from_height * (switch_anim.value() - from) - to * current_height
1452 // - first_y = to * from_height - switch_anim.value() * from_height - to * current_height
1453 // - first_y = -switch_anim.value() * from_height + to * (from_height - current_height)
1454 let from = progress_anim.from();
1455 let from_zoom = compute_overview_zoom(&self.options, Some(from));
1456 let from_ws_height_with_gap = self.workspace_size_with_gap(from_zoom).h;
1457
1458 let zoom = self.overview_zoom();
1459 let ws_height_with_gap = self.workspace_size_with_gap(zoom).h;
1460
1461 let first_ws_y = -switch_anim.value() * from_ws_height_with_gap
1462 + switch_anim.to() * (from_ws_height_with_gap - ws_height_with_gap);
1463
1464 return -first_ws_y / ws_height_with_gap;
1465 }
1466 };
1467
1468 if let Some(switch) = &self.workspace_switch {
1469 switch.current_idx()
1470 } else {
1471 self.active_workspace_idx as f64
1472 }
1473 }
1474
1475 pub fn workspaces_render_geo(&self) -> impl Iterator<Item = Rectangle<f64, Logical>> {
1476 let scale = self.scale.fractional_scale();
1477 let zoom = self.overview_zoom();
1478
1479 let ws_size = self.workspace_size(zoom);
1480 let gap = self.workspace_gap(zoom);
1481 let ws_height_with_gap = ws_size.h + gap;
1482
1483 let static_offset = (self.view_size.to_point() - ws_size.to_point()).downscale(2.);
1484 let static_offset = static_offset
1485 .to_physical_precise_round(scale)
1486 .to_logical(scale);
1487
1488 let first_ws_y = -self.workspace_render_idx() * ws_height_with_gap;
1489 let first_ws_y = round_logical_in_physical(scale, first_ws_y);
1490
1491 // Return position for one-past-last workspace too.
1492 (0..=self.workspaces.len()).map(move |idx| {
1493 let y = first_ws_y + idx as f64 * ws_height_with_gap;
1494 let loc = Point::from((0., y)) + static_offset;
1495
1496 // Even though all components that go into loc are rounded to physical pixels, the
1497 // floating point addition may lose precision. This can result for example in the
1498 // current workspace having y = 0.0000000000002 and thus missing pointer hits at the
1499 // monitor edge with y = 0. So, post-round the location too.
1500 let loc = loc.to_physical_precise_round(scale).to_logical(scale);
1501
1502 Rectangle::new(loc, ws_size)
1503 })
1504 }
1505
1506 pub fn workspaces_with_render_geo_cull(
1507 &self,
1508 cull: bool,
1509 ) -> impl Iterator<Item = (&Workspace<W>, Rectangle<f64, Logical>)> {
1510 let output_geo = Rectangle::from_size(self.view_size);
1511
1512 let geo = self.workspaces_render_geo();
1513 zip(self.workspaces.iter(), geo)
1514 // Cull out workspaces outside the output.
1515 .filter(move |(_ws, geo)| !cull || geo.intersection(output_geo).is_some())
1516 }
1517
1518 pub fn workspaces_with_render_geo(
1519 &self,
1520 ) -> impl Iterator<Item = (&Workspace<W>, Rectangle<f64, Logical>)> {
1521 self.workspaces_with_render_geo_cull(true)
1522 }
1523
1524 pub fn workspaces_with_render_geo_idx(
1525 &self,
1526 ) -> impl Iterator<Item = ((usize, &Workspace<W>), Rectangle<f64, Logical>)> {
1527 let output_geo = Rectangle::from_size(self.view_size);
1528
1529 let geo = self.workspaces_render_geo();
1530 zip(self.workspaces.iter().enumerate(), geo)
1531 // Cull out workspaces outside the output.
1532 .filter(move |(_ws, geo)| geo.intersection(output_geo).is_some())
1533 }
1534
1535 pub fn workspaces_with_render_geo_mut(
1536 &mut self,
1537 cull: bool,
1538 ) -> impl Iterator<Item = (&mut Workspace<W>, Rectangle<f64, Logical>)> {
1539 let output_geo = Rectangle::from_size(self.view_size);
1540
1541 let geo = self.workspaces_render_geo();
1542 zip(self.workspaces.iter_mut(), geo)
1543 // Cull out workspaces outside the output.
1544 .filter(move |(_ws, geo)| !cull || geo.intersection(output_geo).is_some())
1545 }
1546
1547 pub fn workspace_under(
1548 &self,
1549 pos_within_output: Point<f64, Logical>,
1550 ) -> Option<(&Workspace<W>, Rectangle<f64, Logical>)> {
1551 let (ws, geo) = self.workspaces_with_render_geo().find_map(|(ws, geo)| {
1552 // Extend width to entire output.
1553 let loc = Point::from((0., geo.loc.y));
1554 let size = Size::from((self.view_size.w, geo.size.h));
1555 let bounds = Rectangle::new(loc, size);
1556
1557 bounds.contains(pos_within_output).then_some((ws, geo))
1558 })?;
1559 Some((ws, geo))
1560 }
1561
1562 pub fn workspace_under_narrow(
1563 &self,
1564 pos_within_output: Point<f64, Logical>,
1565 ) -> Option<&Workspace<W>> {
1566 self.workspaces_with_render_geo()
1567 .find_map(|(ws, geo)| geo.contains(pos_within_output).then_some(ws))
1568 }
1569
1570 pub fn window_under(&self, pos_within_output: Point<f64, Logical>) -> Option<(&W, HitType)> {
1571 let (ws, geo) = self.workspace_under(pos_within_output)?;
1572
1573 if self.overview_progress.is_some() {
1574 let zoom = self.overview_zoom();
1575 let pos_within_workspace = (pos_within_output - geo.loc).downscale(zoom);
1576 let (win, hit) = ws.window_under(pos_within_workspace)?;
1577 // During the overview animation, we cannot do input hits because we cannot really
1578 // represent scaled windows properly.
1579 Some((win, hit.to_activate()))
1580 } else {
1581 let (win, hit) = ws.window_under(pos_within_output - geo.loc)?;
1582 Some((win, hit.offset_win_pos(geo.loc)))
1583 }
1584 }
1585
1586 pub fn resize_edges_under(&self, pos_within_output: Point<f64, Logical>) -> Option<ResizeEdge> {
1587 if self.overview_progress.is_some() {
1588 return None;
1589 }
1590
1591 let (ws, geo) = self.workspace_under(pos_within_output)?;
1592 ws.resize_edges_under(pos_within_output - geo.loc)
1593 }
1594
1595 pub(super) fn insert_position(
1596 &self,
1597 pos_within_output: Point<f64, Logical>,
1598 ) -> (InsertWorkspace, Rectangle<f64, Logical>) {
1599 let mut iter = self.workspaces_with_render_geo_idx();
1600
1601 let dummy = Rectangle::default();
1602
1603 // Monitors always have at least one workspace.
1604 let ((idx, ws), geo) = iter.next().unwrap();
1605
1606 // Check if above first.
1607 if pos_within_output.y < geo.loc.y {
1608 return (InsertWorkspace::NewAt(idx), dummy);
1609 }
1610
1611 let contains = move |geo: Rectangle<f64, Logical>| {
1612 geo.loc.y <= pos_within_output.y && pos_within_output.y < geo.loc.y + geo.size.h
1613 };
1614
1615 // Check first.
1616 if contains(geo) {
1617 return (InsertWorkspace::Existing(ws.id()), geo);
1618 }
1619
1620 let mut last_geo = geo;
1621 let mut last_idx = idx;
1622 for ((idx, ws), geo) in iter {
1623 // Check gap above.
1624 let gap_loc = Point::from((last_geo.loc.x, last_geo.loc.y + last_geo.size.h));
1625 let gap_size = Size::from((geo.size.w, geo.loc.y - gap_loc.y));
1626 let gap_geo = Rectangle::new(gap_loc, gap_size);
1627 if contains(gap_geo) {
1628 return (InsertWorkspace::NewAt(idx), dummy);
1629 }
1630
1631 // Check workspace itself.
1632 if contains(geo) {
1633 return (InsertWorkspace::Existing(ws.id()), geo);
1634 }
1635
1636 last_geo = geo;
1637 last_idx = idx;
1638 }
1639
1640 // Anything below.
1641 (InsertWorkspace::NewAt(last_idx + 1), dummy)
1642 }
1643
1644 pub fn fullscreen_window_above_top_layer(&self) -> Option<&W> {
1645 // Render above the top layer only if the view is stationary.
1646 if self.workspace_switch.is_some() || self.overview_progress.is_some() {
1647 return None;
1648 }
1649
1650 let ws = &self.workspaces[self.active_workspace_idx];
1651 ws.fullscreen_window_above_top_layer()
1652 }
1653
1654 pub fn render_above_top_layer(&self) -> bool {
1655 self.fullscreen_window_above_top_layer().is_some()
1656 }
1657
1658 pub fn render_insert_hint_between_workspaces<R: NiriRenderer>(
1659 &self,
1660 renderer: &mut R,
1661 push: &mut dyn FnMut(MonitorRenderElement<R>),
1662 ) {
1663 if self.options.layout.insert_hint.off {
1664 return;
1665 }
1666 let Some(render_loc) = self.insert_hint_render_loc else {
1667 return;
1668 };
1669 let InsertWorkspace::NewAt(_) = render_loc.workspace else {
1670 return;
1671 };
1672
1673 self.insert_hint_element
1674 .render(renderer, render_loc.location, &mut |elem| {
1675 let elem = MonitorInnerRenderElement::UncroppedInsertHint(elem);
1676 let elem = RescaleRenderElement::from_element(elem, Point::default(), 1.);
1677 let elem =
1678 RelocateRenderElement::from_element(elem, Point::default(), Relocate::Relative);
1679 push(elem);
1680 });
1681 }
1682
1683 pub fn render_workspaces<R: NiriRenderer>(
1684 &self,
1685 mut ctx: RenderCtx<R>,
1686 focus_ring: bool,
1687 push: &mut dyn FnMut(MonitorRenderElement<R>),
1688 ) {
1689 let _span = tracy_client::span!("Monitor::render_workspaces");
1690
1691 let scale = self.scale.fractional_scale();
1692 // Ceil the height in physical pixels.
1693 let height = (self.view_size.h * scale).ceil() as i32;
1694
1695 let zoom = self.overview_zoom();
1696
1697 let insert_hint_render_loc = self
1698 .insert_hint_render_loc
1699 .filter(|_| !self.options.layout.insert_hint.off);
1700
1701 let scale_relocate = move |geo: Rectangle<f64, Logical>, elem| {
1702 let elem = RescaleRenderElement::from_element(elem, Point::from((0, 0)), zoom);
1703 RelocateRenderElement::from_element(
1704 elem,
1705 // The offset we get from workspaces_with_render_geo() is already
1706 // rounded to physical pixels, but it's in the logical coordinate
1707 // space, so we need to convert it to physical.
1708 geo.loc.to_physical_precise_round(scale),
1709 Relocate::Relative,
1710 )
1711 };
1712
1713 // Draw in passes for correct Z ordering during window movement between workspaces:
1714 // - floating windows moving between workspaces
1715 // - normal floating windows
1716 // - scrolling windows moving between workspaces
1717 // - normal scrolling windows
1718 for pass in 0..4 {
1719 // Don't cull when drawing windows moving between workspaces so that windows moving to
1720 // workspaces off-screen will still render.
1721 let cull = matches!(pass, 1 | 3);
1722
1723 // Crop the elements to prevent them overflowing, currently visible during a workspace
1724 // switch.
1725 //
1726 // HACK: crop to infinite bounds at least horizontally where we
1727 // know there's no workspace joining or monitor bounds, otherwise
1728 // it will cut pixel shaders and mess up the coordinate space.
1729 // There's also a damage tracking bug which causes glitched
1730 // rendering for maximized GTK windows.
1731 //
1732 // FIXME: use proper bounds after fixing the Crop element.
1733 //
1734 // Also, check cull here to avoid cropping windows moving between workspaces.
1735 //
1736 // FIXME: for cull=true, it might be better visually to crop to a workspace-high region
1737 // anchored to the window/column as it moves between workspaces, to prevent overflowing
1738 // windows from appearing and disappearing.
1739 let crop_bounds =
1740 if cull && (self.workspace_switch.is_some() || self.overview_progress.is_some()) {
1741 Rectangle::new(
1742 Point::from((-i32::MAX / 2, 0)),
1743 Size::from((i32::MAX, height)),
1744 )
1745 } else {
1746 Rectangle::new(
1747 Point::from((-i32::MAX / 2, -i32::MAX / 2)),
1748 Size::from((i32::MAX, i32::MAX)),
1749 )
1750 };
1751
1752 for (ws, geo) in self.workspaces_with_render_geo_cull(cull) {
1753 // Macro instead of closure because ws and insert hint have different elem types.
1754 macro_rules! push {
1755 () => {{
1756 &mut |elem| {
1757 let elem = CropRenderElement::from_element(elem, scale, crop_bounds);
1758 if let Some(elem) = elem {
1759 let elem = MonitorInnerRenderElement::from(elem);
1760 push(scale_relocate(geo, elem));
1761 }
1762 }
1763 }};
1764 }
1765
1766 let xray_pos = XrayPos::new(geo.loc, zoom);
1767
1768 match pass {
1769 0 => {
1770 ws.render_floating(
1771 ctx.r(),
1772 xray_pos,
1773 focus_ring,
1774 RenderLayer::MovingBetweenWorkspaces,
1775 push!(),
1776 );
1777 }
1778 1 => {
1779 ws.render_floating(
1780 ctx.r(),
1781 xray_pos,
1782 focus_ring,
1783 RenderLayer::Normal,
1784 push!(),
1785 );
1786
1787 if let Some(loc) = insert_hint_render_loc {
1788 if loc.workspace == InsertWorkspace::Existing(ws.id()) {
1789 self.insert_hint_element.render(
1790 ctx.renderer,
1791 loc.location,
1792 push!(),
1793 );
1794 }
1795 }
1796 }
1797 2 => {
1798 ws.render_scrolling(
1799 ctx.r(),
1800 xray_pos,
1801 focus_ring,
1802 RenderLayer::MovingBetweenWorkspaces,
1803 push!(),
1804 );
1805 }
1806 _ => {
1807 ws.render_scrolling(
1808 ctx.r(),
1809 xray_pos,
1810 focus_ring,
1811 RenderLayer::Normal,
1812 push!(),
1813 );
1814 }
1815 }
1816 }
1817 }
1818 }
1819
1820 pub fn render_workspace_shadows<R: NiriRenderer>(
1821 &self,
1822 renderer: &mut R,
1823 push: &mut dyn FnMut(MonitorRenderElement<R>),
1824 ) {
1825 let Some(progress) = self.overview_progress.as_ref().map(|p| p.clamped_value()) else {
1826 return;
1827 };
1828 let alpha = progress.clamp(0., 1.) as f32;
1829
1830 let _span = tracy_client::span!("Monitor::render_workspace_shadows");
1831
1832 let scale = self.scale.fractional_scale();
1833 let zoom = self.overview_zoom();
1834
1835 for (ws, geo) in self.workspaces_with_render_geo() {
1836 ws.render_shadow(renderer, &mut |elem| {
1837 let elem = elem.with_alpha(alpha);
1838 let elem = MonitorInnerRenderElement::Shadow(elem);
1839 let elem = RescaleRenderElement::from_element(elem, Point::from((0, 0)), zoom);
1840 let elem = RelocateRenderElement::from_element(
1841 elem,
1842 geo.loc.to_physical_precise_round(scale),
1843 Relocate::Relative,
1844 );
1845 push(elem);
1846 });
1847 }
1848 }
1849
1850 pub fn workspace_switch_gesture_begin(&mut self, is_touchpad: bool) {
1851 let center_idx = self.active_workspace_idx;
1852 let current_idx = self.workspace_render_idx();
1853
1854 let gesture = WorkspaceSwitchGesture {
1855 center_idx,
1856 start_idx: current_idx,
1857 current_idx,
1858 animation: None,
1859 tracker: SwipeTracker::new(),
1860 is_touchpad,
1861 is_clamped: !self.overview_open,
1862 dnd_last_event_time: None,
1863 dnd_nonzero_start_time: None,
1864 };
1865 self.workspace_switch = Some(WorkspaceSwitch::Gesture(gesture));
1866 }
1867
1868 pub fn dnd_scroll_gesture_begin(&mut self) {
1869 if let Some(WorkspaceSwitch::Gesture(WorkspaceSwitchGesture {
1870 dnd_last_event_time: Some(_),
1871 ..
1872 })) = &self.workspace_switch
1873 {
1874 // Already active.
1875 return;
1876 }
1877
1878 if !self.overview_open {
1879 // This gesture is only for the overview.
1880 return;
1881 }
1882
1883 let center_idx = self.active_workspace_idx;
1884 let current_idx = self.workspace_render_idx();
1885
1886 let gesture = WorkspaceSwitchGesture {
1887 center_idx,
1888 start_idx: current_idx,
1889 current_idx,
1890 animation: None,
1891 tracker: SwipeTracker::new(),
1892 is_touchpad: false,
1893 is_clamped: false,
1894 dnd_last_event_time: Some(self.clock.now_unadjusted()),
1895 dnd_nonzero_start_time: None,
1896 };
1897 self.workspace_switch = Some(WorkspaceSwitch::Gesture(gesture));
1898 }
1899
1900 pub fn workspace_switch_gesture_update(
1901 &mut self,
1902 delta_y: f64,
1903 timestamp: Duration,
1904 is_touchpad: bool,
1905 ) -> Option<bool> {
1906 let Some(WorkspaceSwitch::Gesture(gesture)) = &self.workspace_switch else {
1907 return None;
1908 };
1909
1910 if gesture.is_touchpad != is_touchpad || gesture.dnd_last_event_time.is_some() {
1911 return None;
1912 }
1913
1914 let zoom = self.overview_zoom();
1915 let total_height = if gesture.is_touchpad {
1916 WORKSPACE_GESTURE_MOVEMENT
1917 } else {
1918 self.workspace_size_with_gap(1.).h
1919 };
1920
1921 let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
1922 return None;
1923 };
1924
1925 // Reduce the effect of zoom on the touchpad somewhat.
1926 let delta_scale = if gesture.is_touchpad {
1927 (zoom - 1.) / 2.5 + 1.
1928 } else {
1929 zoom
1930 };
1931
1932 let delta_y = delta_y / delta_scale;
1933 let mut rubber_band = WORKSPACE_GESTURE_RUBBER_BAND;
1934 rubber_band.limit /= zoom;
1935
1936 gesture.tracker.push(delta_y, timestamp);
1937
1938 let pos = gesture.tracker.pos() / total_height;
1939
1940 let (min, max) = gesture.min_max(self.workspaces.len());
1941 let new_idx = gesture.start_idx + pos;
1942 let new_idx = rubber_band.clamp(min, max, new_idx);
1943
1944 if gesture.current_idx == new_idx {
1945 return Some(false);
1946 }
1947
1948 gesture.current_idx = new_idx;
1949 Some(true)
1950 }
1951
1952 pub fn dnd_scroll_gesture_scroll(&mut self, pos: Point<f64, Logical>, speed: f64) -> bool {
1953 let zoom = self.overview_zoom();
1954
1955 let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
1956 return false;
1957 };
1958
1959 let Some(last_time) = gesture.dnd_last_event_time else {
1960 // Not a DnD scroll.
1961 return false;
1962 };
1963
1964 let config = &self.options.gestures.dnd_edge_workspace_switch;
1965 let trigger_height = config.trigger_height;
1966
1967 // Restrict the scrolling horizontally to the strip of workspaces to avoid unwanted trigger
1968 // after using the hot corner or during horizontal scroll.
1969 let width = self.view_size.w * zoom;
1970 let x = pos.x - (self.view_size.w - width) / 2.;
1971
1972 // Consider the working area so layer-shell docks and such don't prevent scrolling.
1973 let y = pos.y - self.working_area.loc.y;
1974 let height = self.working_area.size.h;
1975
1976 let y = y.clamp(0., height);
1977 let trigger_height = trigger_height.clamp(0., height / 2.);
1978
1979 let delta = if x < 0. || width <= x {
1980 // Outside the bounds horizontally.
1981 0.
1982 } else if y < trigger_height {
1983 -(trigger_height - y)
1984 } else if height - y < trigger_height {
1985 trigger_height - (height - y)
1986 } else {
1987 0.
1988 };
1989
1990 let delta = if trigger_height < 0.01 {
1991 // Sanity check for trigger-height 0 or small window sizes.
1992 0.
1993 } else {
1994 // Normalize to [0, 1].
1995 delta / trigger_height
1996 };
1997 let delta = delta * speed;
1998
1999 let now = self.clock.now_unadjusted();
2000 gesture.dnd_last_event_time = Some(now);
2001
2002 if delta == 0. {
2003 // We're outside the scrolling zone.
2004 gesture.dnd_nonzero_start_time = None;
2005 return false;
2006 }
2007
2008 let nonzero_start = *gesture.dnd_nonzero_start_time.get_or_insert(now);
2009
2010 // Delay starting the gesture a bit to avoid unwanted movement when dragging across
2011 // monitors.
2012 let delay = Duration::from_millis(u64::from(config.delay_ms));
2013 if now.saturating_sub(nonzero_start) < delay {
2014 return true;
2015 }
2016
2017 let time_delta = now.saturating_sub(last_time).as_secs_f64();
2018
2019 let delta = delta * time_delta * config.max_speed;
2020
2021 gesture.tracker.push(delta, now);
2022
2023 let total_height = WORKSPACE_DND_EDGE_SCROLL_MOVEMENT;
2024 let pos = gesture.tracker.pos() / total_height;
2025 let unclamped = gesture.start_idx + pos;
2026
2027 let (min, max) = gesture.min_max(self.workspaces.len());
2028 let clamped = unclamped.clamp(min, max);
2029
2030 // Make sure that DnD scrolling too much outside the min/max does not "build up".
2031 gesture.start_idx += clamped - unclamped;
2032 gesture.current_idx = clamped;
2033
2034 true
2035 }
2036
2037 pub fn workspace_switch_gesture_end(&mut self, is_touchpad: Option<bool>) -> bool {
2038 let Some(WorkspaceSwitch::Gesture(gesture)) = &self.workspace_switch else {
2039 return false;
2040 };
2041
2042 if is_touchpad.is_some_and(|x| gesture.is_touchpad != x) {
2043 return false;
2044 }
2045
2046 let zoom = self.overview_zoom();
2047 let total_height = if gesture.dnd_last_event_time.is_some() {
2048 WORKSPACE_DND_EDGE_SCROLL_MOVEMENT
2049 } else if gesture.is_touchpad {
2050 WORKSPACE_GESTURE_MOVEMENT
2051 } else {
2052 self.workspace_size_with_gap(1.).h
2053 };
2054
2055 let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
2056 return false;
2057 };
2058
2059 // Take into account any idle time between the last event and now.
2060 let now = self.clock.now_unadjusted();
2061 gesture.tracker.push(0., now);
2062
2063 let mut rubber_band = WORKSPACE_GESTURE_RUBBER_BAND;
2064 rubber_band.limit /= zoom;
2065
2066 let mut velocity = gesture.tracker.velocity() / total_height;
2067 let current_pos = gesture.tracker.pos() / total_height;
2068 let pos = gesture.tracker.projected_end_pos() / total_height;
2069
2070 let (min, max) = gesture.min_max(self.workspaces.len());
2071 let new_idx = gesture.start_idx + pos;
2072
2073 let new_idx = new_idx.clamp(min, max);
2074 let new_idx = new_idx.round() as usize;
2075
2076 velocity *= rubber_band.clamp_derivative(min, max, gesture.start_idx + current_pos);
2077
2078 if self.active_workspace_idx != new_idx {
2079 self.previous_workspace_id = Some(self.workspaces[self.active_workspace_idx].id());
2080 }
2081
2082 self.active_workspace_idx = new_idx;
2083 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
2084 self.clock.clone(),
2085 gesture.current_idx,
2086 new_idx as f64,
2087 velocity,
2088 self.options.animations.workspace_switch.0,
2089 )));
2090
2091 true
2092 }
2093
2094 pub fn dnd_scroll_gesture_end(&mut self) {
2095 if !matches!(
2096 self.workspace_switch,
2097 Some(WorkspaceSwitch::Gesture(WorkspaceSwitchGesture {
2098 dnd_last_event_time: Some(_),
2099 ..
2100 }))
2101 ) {
2102 // Not a DnD scroll.
2103 return;
2104 };
2105
2106 self.workspace_switch_gesture_end(None);
2107 }
2108
2109 pub fn scale(&self) -> smithay::output::Scale {
2110 self.scale
2111 }
2112
2113 pub fn view_size(&self) -> Size<f64, Logical> {
2114 self.view_size
2115 }
2116
2117 pub fn working_area(&self) -> Rectangle<f64, Logical> {
2118 self.working_area
2119 }
2120
2121 pub fn layout_config(&self) -> Option<&niri_config::LayoutPart> {
2122 self.layout_config.as_ref()
2123 }
2124
2125 #[cfg(test)]
2126 pub(super) fn verify_invariants(&self) {
2127 use approx::assert_abs_diff_eq;
2128
2129 let options =
2130 Options::clone(&self.base_options).with_merged_layout(self.layout_config.as_ref());
2131 assert_eq!(&*self.options, &options);
2132
2133 assert!(
2134 !self.workspaces.is_empty(),
2135 "monitor must have at least one workspace"
2136 );
2137 assert!(self.active_workspace_idx < self.workspaces.len());
2138
2139 if let Some(WorkspaceSwitch::Animation(anim)) = &self.workspace_switch {
2140 let before_idx = anim.from() as usize;
2141 let after_idx = anim.to() as usize;
2142
2143 assert!(before_idx < self.workspaces.len());
2144 assert!(after_idx < self.workspaces.len());
2145 }
2146
2147 assert!(
2148 !self.workspaces.last().unwrap().has_windows(),
2149 "monitor must have an empty workspace in the end"
2150 );
2151 if self.options.layout.empty_workspace_above_first {
2152 assert!(
2153 !self.workspaces.first().unwrap().has_windows(),
2154 "first workspace must be empty when empty_workspace_above_first is set"
2155 )
2156 }
2157
2158 assert!(
2159 self.workspaces.last().unwrap().name.is_none(),
2160 "monitor must have an unnamed workspace in the end"
2161 );
2162 if self.options.layout.empty_workspace_above_first {
2163 assert!(
2164 self.workspaces.first().unwrap().name.is_none(),
2165 "first workspace must be unnamed when empty_workspace_above_first is set"
2166 )
2167 }
2168
2169 if self.options.layout.empty_workspace_above_first {
2170 assert!(
2171 self.workspaces.len() != 2,
2172 "if empty_workspace_above_first is set there must be just 1 or 3+ workspaces"
2173 )
2174 }
2175
2176 // If there's no workspace switch in progress, there can't be any non-last non-active
2177 // empty workspaces. If empty_workspace_above_first is set then the first workspace
2178 // will be empty too.
2179 let pre_skip = if self.options.layout.empty_workspace_above_first {
2180 1
2181 } else {
2182 0
2183 };
2184 if self.workspace_switch.is_none() {
2185 for (idx, ws) in self
2186 .workspaces
2187 .iter()
2188 .enumerate()
2189 .skip(pre_skip)
2190 .rev()
2191 // skip last
2192 .skip(1)
2193 {
2194 if idx != self.active_workspace_idx {
2195 assert!(
2196 ws.has_windows_or_name(),
2197 "non-active workspace can't be empty and unnamed except the last one"
2198 );
2199 }
2200 }
2201 }
2202
2203 for workspace in &self.workspaces {
2204 assert_eq!(self.clock, workspace.clock);
2205
2206 assert_eq!(
2207 self.scale().integer_scale(),
2208 workspace.scale().integer_scale()
2209 );
2210 assert_eq!(
2211 self.scale().fractional_scale(),
2212 workspace.scale().fractional_scale()
2213 );
2214 assert_eq!(self.view_size, workspace.view_size());
2215 assert_eq!(self.working_area, workspace.working_area());
2216
2217 assert_eq!(
2218 workspace.base_options, self.options,
2219 "workspace options must be synchronized with monitor"
2220 );
2221 }
2222
2223 let scale = self.scale().fractional_scale();
2224 let iter = self.workspaces_with_render_geo();
2225 for (_ws, ws_geo) in iter {
2226 let pos = ws_geo.loc;
2227 let rounded_pos = pos.to_physical_precise_round(scale).to_logical(scale);
2228
2229 // Workspace positions must be rounded to physical pixels.
2230 assert_abs_diff_eq!(pos.x, rounded_pos.x, epsilon = 1e-5);
2231 assert_abs_diff_eq!(pos.y, rounded_pos.y, epsilon = 1e-5);
2232 }
2233 }
2234}