forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB66583cdIvan Molodetskikh1 year ago2489 commits

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