forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBce9dd33sodiboo1 year ago2737 commits

monitor.rs2166 lines, 74.3 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::xray::XrayPos;
28use crate::render_helpers::RenderCtx;
29use crate::rubber_band::RubberBand;
30use crate::utils::transaction::Transaction;
31use crate::utils::{
32 output_size, round_logical_in_physical, round_logical_in_physical_max1, ResizeEdge,
33};
34
35/// Amount of touchpad movement to scroll the height of one workspace.
36const WORKSPACE_GESTURE_MOVEMENT: f64 = 300.;
37
38const WORKSPACE_GESTURE_RUBBER_BAND: RubberBand = RubberBand {
39 stiffness: 0.5,
40 limit: 0.05,
41};
42
43/// Amount of DnD edge scrolling to scroll the height of one workspace.
44///
45/// This constant is tied to the default dnd-edge-workspace-switch max-speed setting.
46const WORKSPACE_DND_EDGE_SCROLL_MOVEMENT: f64 = 1500.;
47
48#[derive(Debug)]
49pub struct Monitor<W: LayoutElement> {
50 /// Output for this monitor.
51 pub(super) output: Output,
52 /// Cached name of the output.
53 output_name: String,
54 /// Latest known scale for this output.
55 scale: smithay::output::Scale,
56 /// Latest known size for this output.
57 view_size: Size<f64, Logical>,
58 /// Latest known working area for this output.
59 ///
60 /// Not rounded to physical pixels.
61 // FIXME: since this is used for things like DnD scrolling edges in the overview, ideally this
62 // should only consider overlay and top layer-shell surfaces. However, Smithay doesn't easily
63 // let you do this at the moment.
64 working_area: Rectangle<f64, Logical>,
65 // Must always contain at least one.
66 pub(super) workspaces: Vec<Workspace<W>>,
67 /// Index of the currently active workspace.
68 pub(super) active_workspace_idx: usize,
69 /// ID of the previously active workspace.
70 pub(super) previous_workspace_id: Option<WorkspaceId>,
71 /// In-progress switch between workspaces.
72 pub(super) workspace_switch: Option<WorkspaceSwitch>,
73 /// Indication where an interactively-moved window is about to be placed.
74 pub(super) insert_hint: Option<InsertHint>,
75 /// Insert hint element for rendering.
76 insert_hint_element: InsertHintElement,
77 /// Location to render the insert hint element.
78 insert_hint_render_loc: Option<InsertHintRenderLoc>,
79 /// Whether the overview is open.
80 pub(super) overview_open: bool,
81 /// Progress of the overview zoom animation, 1 is fully in overview.
82 overview_progress: Option<OverviewProgress>,
83 /// Clock for driving animations.
84 pub(super) clock: Clock,
85 /// Configurable properties of the layout as received from the parent layout.
86 pub(super) base_options: Rc<Options>,
87 /// Configurable properties of the layout.
88 pub(super) options: Rc<Options>,
89 /// Layout config overrides for this monitor.
90 layout_config: Option<niri_config::LayoutPart>,
91}
92
93#[derive(Debug)]
94pub enum WorkspaceSwitch {
95 Animation(Animation),
96 Gesture(WorkspaceSwitchGesture),
97}
98
99#[derive(Debug)]
100pub struct WorkspaceSwitchGesture {
101 /// Index of the workspace where the gesture was started.
102 center_idx: usize,
103 /// Fractional workspace index where the gesture was started.
104 ///
105 /// Can differ from center_idx when starting a gesture in the middle between workspaces, for
106 /// example by "catching" an animation.
107 start_idx: f64,
108 /// Current, fractional workspace index.
109 pub(super) current_idx: f64,
110 /// Animation for the extra offset to the current position.
111 ///
112 /// For example, if there's a workspace switch during a DnD scroll.
113 animation: Option<Animation>,
114 tracker: SwipeTracker,
115 /// Whether the gesture is controlled by the touchpad.
116 is_touchpad: bool,
117 /// Whether the gesture is clamped to +-1 workspace around the center.
118 is_clamped: bool,
119
120 // If this gesture is for drag-and-drop scrolling, this is the last event's unadjusted
121 // timestamp.
122 dnd_last_event_time: Option<Duration>,
123 // Time when the drag-and-drop scroll delta became non-zero, used for debouncing.
124 //
125 // If `None` then the scroll delta is currently zero.
126 dnd_nonzero_start_time: Option<Duration>,
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub(super) enum InsertPosition {
131 NewColumn(usize),
132 InColumn(usize, usize),
133 Floating,
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub(super) enum InsertWorkspace {
138 Existing(WorkspaceId),
139 NewAt(usize),
140}
141
142#[derive(Debug)]
143pub(super) struct InsertHint {
144 pub workspace: InsertWorkspace,
145 pub position: InsertPosition,
146 pub corner_radius: CornerRadius,
147}
148
149#[derive(Debug, Clone, Copy)]
150struct InsertHintRenderLoc {
151 workspace: InsertWorkspace,
152 location: Point<f64, Logical>,
153}
154
155#[derive(Debug)]
156pub(super) enum OverviewProgress {
157 Animation(Animation),
158 Value(f64),
159}
160
161/// Where to put a newly added window.
162#[derive(Debug, Default, PartialEq, Eq)]
163pub enum MonitorAddWindowTarget<'a, W: LayoutElement> {
164 /// No particular preference.
165 #[default]
166 Auto,
167 /// On this workspace.
168 Workspace {
169 /// Id of the target workspace.
170 id: WorkspaceId,
171 /// Override where the window will open as a new column.
172 column_idx: Option<usize>,
173 },
174 /// Next to this existing window.
175 NextTo(&'a W::Id),
176}
177
178impl<'a, W: LayoutElement> Copy for MonitorAddWindowTarget<'a, W> {}
179
180impl<'a, W: LayoutElement> Clone for MonitorAddWindowTarget<'a, W> {
181 fn clone(&self) -> Self {
182 *self
183 }
184}
185
186niri_render_elements! {
187 MonitorInnerRenderElement<R> => {
188 Workspace = CropRenderElement<WorkspaceRenderElement<R>>,
189 InsertHint = CropRenderElement<InsertHintRenderElement>,
190 UncroppedInsertHint = InsertHintRenderElement,
191 Shadow = ShadowRenderElement,
192 SolidColor = SolidColorRenderElement,
193 }
194}
195
196pub type MonitorRenderElement<R> =
197 RelocateRenderElement<RescaleRenderElement<MonitorInnerRenderElement<R>>>;
198
199impl WorkspaceSwitch {
200 pub fn current_idx(&self) -> f64 {
201 match self {
202 WorkspaceSwitch::Animation(anim) => anim.value(),
203 WorkspaceSwitch::Gesture(gesture) => {
204 gesture.current_idx + gesture.animation.as_ref().map_or(0., |anim| anim.value())
205 }
206 }
207 }
208
209 pub fn target_idx(&self) -> f64 {
210 match self {
211 WorkspaceSwitch::Animation(anim) => anim.to(),
212 WorkspaceSwitch::Gesture(gesture) => gesture.current_idx,
213 }
214 }
215
216 pub fn offset(&mut self, delta: isize) {
217 match self {
218 WorkspaceSwitch::Animation(anim) => anim.offset(delta as f64),
219 WorkspaceSwitch::Gesture(gesture) => {
220 if delta >= 0 {
221 gesture.center_idx += delta as usize;
222 } else {
223 gesture.center_idx -= (-delta) as usize;
224 }
225 gesture.start_idx += delta as f64;
226 gesture.current_idx += delta as f64;
227 }
228 }
229 }
230
231 fn is_animation_ongoing(&self) -> bool {
232 match self {
233 WorkspaceSwitch::Animation(_) => true,
234 WorkspaceSwitch::Gesture(gesture) => gesture.animation.is_some(),
235 }
236 }
237}
238
239impl WorkspaceSwitchGesture {
240 fn min_max(&self, workspace_count: usize) -> (f64, f64) {
241 if self.is_clamped {
242 let min = self.center_idx.saturating_sub(1) as f64;
243 let max = (self.center_idx + 1).min(workspace_count - 1) as f64;
244 (min, max)
245 } else {
246 (0., (workspace_count - 1) as f64)
247 }
248 }
249
250 fn animate_from(&mut self, from: f64, clock: Clock, config: niri_config::Animation) {
251 let current = self.animation.as_ref().map_or(0., Animation::value);
252 self.animation = Some(Animation::new(clock, from + current, 0., 0., config));
253 }
254}
255
256impl InsertWorkspace {
257 fn existing_id(self) -> Option<WorkspaceId> {
258 match self {
259 InsertWorkspace::Existing(id) => Some(id),
260 InsertWorkspace::NewAt(_) => None,
261 }
262 }
263}
264
265impl OverviewProgress {
266 pub fn value(&self) -> f64 {
267 match self {
268 OverviewProgress::Animation(anim) => anim.value(),
269 OverviewProgress::Value(v) => *v,
270 }
271 }
272
273 pub fn clamped_value(&self) -> f64 {
274 match self {
275 OverviewProgress::Animation(anim) => anim.clamped_value(),
276 OverviewProgress::Value(v) => *v,
277 }
278 }
279}
280
281impl From<&super::OverviewProgress> for OverviewProgress {
282 fn from(value: &super::OverviewProgress) -> Self {
283 match value {
284 super::OverviewProgress::Animation(anim) => Self::Animation(anim.clone()),
285 super::OverviewProgress::Gesture(gesture) => Self::Value(gesture.value),
286 super::OverviewProgress::Open => Self::Value(1.),
287 }
288 }
289}
290
291impl<W: LayoutElement> Monitor<W> {
292 pub fn new(
293 output: Output,
294 mut workspaces: Vec<Workspace<W>>,
295 ws_id_to_activate: Option<WorkspaceId>,
296 clock: Clock,
297 base_options: Rc<Options>,
298 layout_config: Option<LayoutPart>,
299 ) -> Self {
300 let options =
301 Rc::new(Options::clone(&base_options).with_merged_layout(layout_config.as_ref()));
302
303 let scale = output.current_scale();
304 let view_size = output_size(&output);
305 let working_area = compute_working_area(&output);
306
307 // Prepare the workspaces: set output, empty first, empty last.
308 let mut active_workspace_idx = 0;
309
310 for (idx, ws) in workspaces.iter_mut().enumerate() {
311 assert!(ws.has_windows_or_name());
312
313 ws.set_output(Some(output.clone()));
314 ws.update_config(options.clone());
315
316 if ws_id_to_activate.is_some_and(|id| ws.id() == id) {
317 active_workspace_idx = idx;
318 }
319 }
320
321 if options.layout.empty_workspace_above_first && !workspaces.is_empty() {
322 let ws = Workspace::new(output.clone(), clock.clone(), options.clone());
323 workspaces.insert(0, ws);
324 active_workspace_idx += 1;
325 }
326
327 let ws = Workspace::new(output.clone(), clock.clone(), options.clone());
328 workspaces.push(ws);
329
330 Self {
331 output_name: output.name(),
332 output,
333 scale,
334 view_size,
335 working_area,
336 workspaces,
337 active_workspace_idx,
338 previous_workspace_id: None,
339 insert_hint: None,
340 insert_hint_element: InsertHintElement::new(options.layout.insert_hint),
341 insert_hint_render_loc: None,
342 overview_open: false,
343 overview_progress: None,
344 workspace_switch: None,
345 clock,
346 base_options,
347 options,
348 layout_config,
349 }
350 }
351
352 pub fn into_workspaces(mut self) -> Vec<Workspace<W>> {
353 self.workspaces.retain(|ws| ws.has_windows_or_name());
354
355 for ws in &mut self.workspaces {
356 ws.set_output(None);
357 }
358
359 self.workspaces
360 }
361
362 pub fn output(&self) -> &Output {
363 &self.output
364 }
365
366 pub fn output_name(&self) -> &String {
367 &self.output_name
368 }
369
370 pub fn active_workspace_idx(&self) -> usize {
371 self.active_workspace_idx
372 }
373
374 pub fn active_workspace_ref(&self) -> &Workspace<W> {
375 &self.workspaces[self.active_workspace_idx]
376 }
377
378 pub fn find_named_workspace(&self, workspace_name: &str) -> Option<&Workspace<W>> {
379 self.workspaces.iter().find(|ws| {
380 ws.name
381 .as_ref()
382 .is_some_and(|name| name.eq_ignore_ascii_case(workspace_name))
383 })
384 }
385
386 pub fn find_named_workspace_index(&self, workspace_name: &str) -> Option<usize> {
387 self.workspaces.iter().position(|ws| {
388 ws.name
389 .as_ref()
390 .is_some_and(|name| name.eq_ignore_ascii_case(workspace_name))
391 })
392 }
393
394 pub fn active_workspace(&mut self) -> &mut Workspace<W> {
395 &mut self.workspaces[self.active_workspace_idx]
396 }
397
398 pub fn windows(&self) -> impl Iterator<Item = &W> {
399 self.workspaces.iter().flat_map(|ws| ws.windows())
400 }
401
402 pub fn has_window(&self, window: &W::Id) -> bool {
403 self.windows().any(|win| win.id() == window)
404 }
405
406 pub fn add_workspace_at(&mut self, idx: usize) {
407 let ws = Workspace::new(
408 self.output.clone(),
409 self.clock.clone(),
410 self.options.clone(),
411 );
412
413 self.workspaces.insert(idx, ws);
414 if idx <= self.active_workspace_idx {
415 self.active_workspace_idx += 1;
416 }
417
418 if let Some(switch) = &mut self.workspace_switch {
419 if idx as f64 <= switch.target_idx() {
420 switch.offset(1);
421 }
422 }
423 }
424
425 pub fn add_workspace_top(&mut self) {
426 self.add_workspace_at(0);
427 }
428
429 pub fn add_workspace_bottom(&mut self) {
430 self.add_workspace_at(self.workspaces.len());
431 }
432
433 pub fn activate_workspace(&mut self, idx: usize) {
434 self.activate_workspace_with_anim_config(idx, None);
435 }
436
437 pub fn activate_workspace_with_anim_config(
438 &mut self,
439 idx: usize,
440 config: Option<niri_config::Animation>,
441 ) {
442 // FIXME: also compute and use current velocity.
443 let current_idx = self.workspace_render_idx();
444
445 if self.active_workspace_idx != idx {
446 self.previous_workspace_id = Some(self.workspaces[self.active_workspace_idx].id());
447 }
448
449 let prev_active_idx = self.active_workspace_idx;
450 self.active_workspace_idx = idx;
451
452 let config = config.unwrap_or(self.options.animations.workspace_switch.0);
453
454 match &mut self.workspace_switch {
455 // During a DnD scroll, we want to visually animate even if idx matches the active idx.
456 Some(WorkspaceSwitch::Gesture(gesture)) if gesture.dnd_last_event_time.is_some() => {
457 gesture.center_idx = idx;
458
459 // Adjust start_idx to make current_idx point at idx.
460 let current_pos = gesture.current_idx - gesture.start_idx;
461 gesture.start_idx = idx as f64 - current_pos;
462 let prev_current_idx = gesture.current_idx;
463 gesture.current_idx = idx as f64;
464
465 let current_idx_delta = gesture.current_idx - prev_current_idx;
466 gesture.animate_from(-current_idx_delta, self.clock.clone(), config);
467 }
468 _ => {
469 // Don't animate if nothing changed.
470 if prev_active_idx == idx {
471 return;
472 }
473
474 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
475 self.clock.clone(),
476 current_idx,
477 idx as f64,
478 0.,
479 config,
480 )));
481 }
482 }
483 }
484
485 pub(super) fn resolve_add_window_target<'a>(
486 &mut self,
487 target: MonitorAddWindowTarget<'a, W>,
488 ) -> (usize, WorkspaceAddWindowTarget<'a, W>) {
489 match target {
490 MonitorAddWindowTarget::Auto => {
491 (self.active_workspace_idx, WorkspaceAddWindowTarget::Auto)
492 }
493 MonitorAddWindowTarget::Workspace { id, column_idx } => {
494 let idx = self.workspaces.iter().position(|ws| ws.id() == id).unwrap();
495 let target = if let Some(column_idx) = column_idx {
496 WorkspaceAddWindowTarget::NewColumnAt(column_idx)
497 } else {
498 WorkspaceAddWindowTarget::Auto
499 };
500 (idx, target)
501 }
502 MonitorAddWindowTarget::NextTo(win_id) => {
503 let idx = self
504 .workspaces
505 .iter_mut()
506 .position(|ws| ws.has_window(win_id))
507 .unwrap();
508 (idx, WorkspaceAddWindowTarget::NextTo(win_id))
509 }
510 }
511 }
512
513 pub fn add_window(
514 &mut self,
515 window: W,
516 target: MonitorAddWindowTarget<W>,
517 activate: ActivateWindow,
518 width: ColumnWidth,
519 is_full_width: bool,
520 is_floating: bool,
521 ) {
522 // Currently, everything a workspace sets on a Tile is the same across all workspaces of a
523 // monitor. So we can use any workspace, not necessarily the exact target workspace.
524 let tile = self.workspaces[0].make_tile(window);
525
526 self.add_tile(
527 tile,
528 target,
529 activate,
530 true,
531 width,
532 is_full_width,
533 is_floating,
534 );
535 }
536
537 pub fn add_column(&mut self, mut workspace_idx: usize, column: Column<W>, activate: bool) {
538 let workspace = &mut self.workspaces[workspace_idx];
539
540 workspace.add_column(column, activate);
541
542 // After adding a new window, workspace becomes this output's own.
543 if workspace.name().is_none() {
544 workspace.original_output = OutputId::new(&self.output);
545 }
546
547 if workspace_idx == self.workspaces.len() - 1 {
548 self.add_workspace_bottom();
549 }
550 if self.options.layout.empty_workspace_above_first && workspace_idx == 0 {
551 self.add_workspace_top();
552 workspace_idx += 1;
553 }
554
555 if activate {
556 self.activate_workspace(workspace_idx);
557 }
558 }
559
560 #[allow(clippy::too_many_arguments)]
561 pub fn add_tile(
562 &mut self,
563 tile: Tile<W>,
564 target: MonitorAddWindowTarget<W>,
565 activate: ActivateWindow,
566 // FIXME: Refactor ActivateWindow enum to make this better.
567 allow_to_activate_workspace: bool,
568 width: ColumnWidth,
569 is_full_width: bool,
570 is_floating: bool,
571 ) {
572 let (mut workspace_idx, target) = self.resolve_add_window_target(target);
573
574 let workspace = &mut self.workspaces[workspace_idx];
575
576 workspace.add_tile(tile, target, activate, width, is_full_width, is_floating);
577
578 // After adding a new window, workspace becomes this output's own.
579 if workspace.name().is_none() {
580 workspace.original_output = OutputId::new(&self.output);
581 }
582
583 if workspace_idx == self.workspaces.len() - 1 {
584 // Insert a new empty workspace.
585 self.add_workspace_bottom();
586 }
587
588 if self.options.layout.empty_workspace_above_first && workspace_idx == 0 {
589 self.add_workspace_top();
590 workspace_idx += 1;
591 }
592
593 if allow_to_activate_workspace && activate.map_smart(|| false) {
594 self.activate_workspace(workspace_idx);
595 }
596 }
597
598 pub fn add_tile_to_column(
599 &mut self,
600 workspace_idx: usize,
601 column_idx: usize,
602 tile_idx: Option<usize>,
603 tile: Tile<W>,
604 activate: bool,
605 // FIXME: Refactor ActivateWindow enum to make this better.
606 allow_to_activate_workspace: bool,
607 ) {
608 let workspace = &mut self.workspaces[workspace_idx];
609
610 workspace.add_tile_to_column(column_idx, tile_idx, tile, activate);
611
612 // After adding a new window, workspace becomes this output's own.
613 if workspace.name().is_none() {
614 workspace.original_output = OutputId::new(&self.output);
615 }
616
617 // Since we're adding window to an existing column, the workspace isn't empty, and
618 // therefore cannot be the last one, so we never need to insert a new empty workspace.
619
620 if allow_to_activate_workspace && activate {
621 self.activate_workspace(workspace_idx);
622 }
623 }
624
625 pub fn clean_up_workspaces(&mut self) {
626 assert!(self.workspace_switch.is_none());
627
628 let range_start = if self.options.layout.empty_workspace_above_first {
629 1
630 } else {
631 0
632 };
633 for idx in (range_start..self.workspaces.len() - 1).rev() {
634 if self.active_workspace_idx == idx {
635 continue;
636 }
637
638 if !self.workspaces[idx].has_windows_or_name() {
639 self.workspaces.remove(idx);
640 if self.active_workspace_idx > idx {
641 self.active_workspace_idx -= 1;
642 }
643 }
644 }
645
646 // Special case handling when empty_workspace_above_first is set and all workspaces
647 // are empty.
648 if self.options.layout.empty_workspace_above_first && self.workspaces.len() == 2 {
649 assert!(!self.workspaces[0].has_windows_or_name());
650 assert!(!self.workspaces[1].has_windows_or_name());
651 self.workspaces.remove(1);
652 self.active_workspace_idx = 0;
653 }
654 }
655
656 pub fn unname_workspace(&mut self, id: WorkspaceId) -> bool {
657 let Some(ws) = self.workspaces.iter_mut().find(|ws| ws.id() == id) else {
658 return false;
659 };
660
661 ws.unname();
662
663 if self.workspace_switch.is_none() {
664 self.clean_up_workspaces();
665 }
666
667 true
668 }
669
670 pub fn remove_workspace_by_idx(&mut self, mut idx: usize) -> Workspace<W> {
671 if idx == self.workspaces.len() - 1 {
672 self.add_workspace_bottom();
673 }
674 if self.options.layout.empty_workspace_above_first && idx == 0 {
675 self.add_workspace_top();
676 idx += 1;
677 }
678
679 let mut ws = self.workspaces.remove(idx);
680 ws.set_output(None);
681
682 // For monitor current workspace removal, we focus previous rather than next (<= rather
683 // than <). This is different from columns and tiles, but it lets move-workspace-to-monitor
684 // back and forth to preserve position.
685 if idx <= self.active_workspace_idx && self.active_workspace_idx > 0 {
686 self.active_workspace_idx -= 1;
687 }
688
689 self.workspace_switch = None;
690 self.clean_up_workspaces();
691
692 ws
693 }
694
695 pub fn insert_workspace(&mut self, mut ws: Workspace<W>, mut idx: usize, activate: bool) {
696 ws.set_output(Some(self.output.clone()));
697 ws.update_config(self.options.clone());
698
699 // Don't insert past the last empty workspace.
700 if idx == self.workspaces.len() {
701 idx -= 1;
702 }
703 if idx == 0 && self.options.layout.empty_workspace_above_first {
704 // Insert a new empty workspace on top to prepare for insertion of new workspace.
705 self.add_workspace_top();
706 idx += 1;
707 }
708
709 self.workspaces.insert(idx, ws);
710
711 if idx <= self.active_workspace_idx {
712 self.active_workspace_idx += 1;
713 }
714
715 if activate {
716 self.workspace_switch = None;
717 self.activate_workspace(idx);
718 }
719
720 self.workspace_switch = None;
721 self.clean_up_workspaces();
722 }
723
724 pub fn append_workspaces(&mut self, mut workspaces: Vec<Workspace<W>>) {
725 if workspaces.is_empty() {
726 return;
727 }
728
729 for ws in &mut workspaces {
730 ws.set_output(Some(self.output.clone()));
731 ws.update_config(self.options.clone());
732 }
733
734 let empty_was_focused = self.active_workspace_idx == self.workspaces.len() - 1;
735
736 // Push the workspaces from the removed monitor in the end, right before the
737 // last, empty, workspace.
738 let empty = self.workspaces.remove(self.workspaces.len() - 1);
739 self.workspaces.extend(workspaces);
740 self.workspaces.push(empty);
741
742 // If empty_workspace_above_first is set and the first workspace is now no longer empty,
743 // add a new empty workspace on top.
744 if self.options.layout.empty_workspace_above_first
745 && self.workspaces[0].has_windows_or_name()
746 {
747 self.add_workspace_top();
748 }
749
750 // If the empty workspace was focused on the primary monitor, keep it focused.
751 if empty_was_focused {
752 self.active_workspace_idx = self.workspaces.len() - 1;
753 }
754
755 // FIXME: if we're adding workspaces to currently invisible positions
756 // (outside the workspace switch), we don't need to cancel it.
757 self.workspace_switch = None;
758 self.clean_up_workspaces();
759 }
760
761 pub fn move_down_or_to_workspace_down(&mut self) {
762 if !self.active_workspace().move_down() {
763 self.move_to_workspace_down(true);
764 }
765 }
766
767 pub fn move_up_or_to_workspace_up(&mut self) {
768 if !self.active_workspace().move_up() {
769 self.move_to_workspace_up(true);
770 }
771 }
772
773 pub fn focus_window_or_workspace_down(&mut self) {
774 if !self.active_workspace().focus_down() {
775 self.switch_workspace_down();
776 }
777 }
778
779 pub fn focus_window_or_workspace_up(&mut self) {
780 if !self.active_workspace().focus_up() {
781 self.switch_workspace_up();
782 }
783 }
784
785 pub fn move_to_workspace_up(&mut self, focus: bool) {
786 let source_workspace_idx = self.active_workspace_idx;
787
788 let new_idx = source_workspace_idx.saturating_sub(1);
789 if new_idx == source_workspace_idx {
790 return;
791 }
792 let new_id = self.workspaces[new_idx].id();
793
794 let workspace = &mut self.workspaces[source_workspace_idx];
795 let Some(removed) = workspace.remove_active_tile(Transaction::new()) else {
796 return;
797 };
798
799 let activate = if focus {
800 ActivateWindow::Yes
801 } else {
802 ActivateWindow::Smart
803 };
804
805 self.add_tile(
806 removed.tile,
807 MonitorAddWindowTarget::Workspace {
808 id: new_id,
809 column_idx: None,
810 },
811 activate,
812 true,
813 removed.width,
814 removed.is_full_width,
815 removed.is_floating,
816 );
817 }
818
819 pub fn move_to_workspace_down(&mut self, focus: bool) {
820 let source_workspace_idx = self.active_workspace_idx;
821
822 let new_idx = min(source_workspace_idx + 1, self.workspaces.len() - 1);
823 if new_idx == source_workspace_idx {
824 return;
825 }
826 let new_id = self.workspaces[new_idx].id();
827
828 let workspace = &mut self.workspaces[source_workspace_idx];
829 let Some(removed) = workspace.remove_active_tile(Transaction::new()) else {
830 return;
831 };
832
833 let activate = if focus {
834 ActivateWindow::Yes
835 } else {
836 ActivateWindow::Smart
837 };
838
839 self.add_tile(
840 removed.tile,
841 MonitorAddWindowTarget::Workspace {
842 id: new_id,
843 column_idx: None,
844 },
845 activate,
846 true,
847 removed.width,
848 removed.is_full_width,
849 removed.is_floating,
850 );
851 }
852
853 pub fn move_to_workspace(
854 &mut self,
855 window: Option<&W::Id>,
856 idx: usize,
857 activate: ActivateWindow,
858 ) {
859 let source_workspace_idx = if let Some(window) = window {
860 self.workspaces
861 .iter()
862 .position(|ws| ws.has_window(window))
863 .unwrap()
864 } else {
865 self.active_workspace_idx
866 };
867
868 let new_idx = min(idx, self.workspaces.len() - 1);
869 if new_idx == source_workspace_idx {
870 return;
871 }
872 let new_id = self.workspaces[new_idx].id();
873
874 let activate = activate.map_smart(|| {
875 window.is_none_or(|win| self.active_window().map(|win| win.id()) == Some(win))
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
1495 // Even though all components that go into loc are rounded to physical pixels, the
1496 // floating point addition may lose precision. This can result for example in the
1497 // current workspace having y = 0.0000000000002 and thus missing pointer hits at the
1498 // monitor edge with y = 0. So, post-round the location too.
1499 let loc = loc.to_physical_precise_round(scale).to_logical(scale);
1500
1501 Rectangle::new(loc, ws_size)
1502 })
1503 }
1504
1505 pub fn workspaces_with_render_geo(
1506 &self,
1507 ) -> impl Iterator<Item = (&Workspace<W>, Rectangle<f64, Logical>)> {
1508 let output_geo = Rectangle::from_size(self.view_size);
1509
1510 let geo = self.workspaces_render_geo();
1511 zip(self.workspaces.iter(), geo)
1512 // Cull out workspaces outside the output.
1513 .filter(move |(_ws, geo)| geo.intersection(output_geo).is_some())
1514 }
1515
1516 pub fn workspaces_with_render_geo_idx(
1517 &self,
1518 ) -> impl Iterator<Item = ((usize, &Workspace<W>), Rectangle<f64, Logical>)> {
1519 let output_geo = Rectangle::from_size(self.view_size);
1520
1521 let geo = self.workspaces_render_geo();
1522 zip(self.workspaces.iter().enumerate(), geo)
1523 // Cull out workspaces outside the output.
1524 .filter(move |(_ws, geo)| geo.intersection(output_geo).is_some())
1525 }
1526
1527 pub fn workspaces_with_render_geo_mut(
1528 &mut self,
1529 cull: bool,
1530 ) -> impl Iterator<Item = (&mut Workspace<W>, Rectangle<f64, Logical>)> {
1531 let output_geo = Rectangle::from_size(self.view_size);
1532
1533 let geo = self.workspaces_render_geo();
1534 zip(self.workspaces.iter_mut(), geo)
1535 // Cull out workspaces outside the output.
1536 .filter(move |(_ws, geo)| !cull || geo.intersection(output_geo).is_some())
1537 }
1538
1539 pub fn workspace_under(
1540 &self,
1541 pos_within_output: Point<f64, Logical>,
1542 ) -> Option<(&Workspace<W>, Rectangle<f64, Logical>)> {
1543 let (ws, geo) = self.workspaces_with_render_geo().find_map(|(ws, geo)| {
1544 // Extend width to entire output.
1545 let loc = Point::from((0., geo.loc.y));
1546 let size = Size::from((self.view_size.w, geo.size.h));
1547 let bounds = Rectangle::new(loc, size);
1548
1549 bounds.contains(pos_within_output).then_some((ws, geo))
1550 })?;
1551 Some((ws, geo))
1552 }
1553
1554 pub fn workspace_under_narrow(
1555 &self,
1556 pos_within_output: Point<f64, Logical>,
1557 ) -> Option<&Workspace<W>> {
1558 self.workspaces_with_render_geo()
1559 .find_map(|(ws, geo)| geo.contains(pos_within_output).then_some(ws))
1560 }
1561
1562 pub fn window_under(&self, pos_within_output: Point<f64, Logical>) -> Option<(&W, HitType)> {
1563 let (ws, geo) = self.workspace_under(pos_within_output)?;
1564
1565 if self.overview_progress.is_some() {
1566 let zoom = self.overview_zoom();
1567 let pos_within_workspace = (pos_within_output - geo.loc).downscale(zoom);
1568 let (win, hit) = ws.window_under(pos_within_workspace)?;
1569 // During the overview animation, we cannot do input hits because we cannot really
1570 // represent scaled windows properly.
1571 Some((win, hit.to_activate()))
1572 } else {
1573 let (win, hit) = ws.window_under(pos_within_output - geo.loc)?;
1574 Some((win, hit.offset_win_pos(geo.loc)))
1575 }
1576 }
1577
1578 pub fn resize_edges_under(&self, pos_within_output: Point<f64, Logical>) -> Option<ResizeEdge> {
1579 if self.overview_progress.is_some() {
1580 return None;
1581 }
1582
1583 let (ws, geo) = self.workspace_under(pos_within_output)?;
1584 ws.resize_edges_under(pos_within_output - geo.loc)
1585 }
1586
1587 pub(super) fn insert_position(
1588 &self,
1589 pos_within_output: Point<f64, Logical>,
1590 ) -> (InsertWorkspace, Rectangle<f64, Logical>) {
1591 let mut iter = self.workspaces_with_render_geo_idx();
1592
1593 let dummy = Rectangle::default();
1594
1595 // Monitors always have at least one workspace.
1596 let ((idx, ws), geo) = iter.next().unwrap();
1597
1598 // Check if above first.
1599 if pos_within_output.y < geo.loc.y {
1600 return (InsertWorkspace::NewAt(idx), dummy);
1601 }
1602
1603 let contains = move |geo: Rectangle<f64, Logical>| {
1604 geo.loc.y <= pos_within_output.y && pos_within_output.y < geo.loc.y + geo.size.h
1605 };
1606
1607 // Check first.
1608 if contains(geo) {
1609 return (InsertWorkspace::Existing(ws.id()), geo);
1610 }
1611
1612 let mut last_geo = geo;
1613 let mut last_idx = idx;
1614 for ((idx, ws), geo) in iter {
1615 // Check gap above.
1616 let gap_loc = Point::from((last_geo.loc.x, last_geo.loc.y + last_geo.size.h));
1617 let gap_size = Size::from((geo.size.w, geo.loc.y - gap_loc.y));
1618 let gap_geo = Rectangle::new(gap_loc, gap_size);
1619 if contains(gap_geo) {
1620 return (InsertWorkspace::NewAt(idx), dummy);
1621 }
1622
1623 // Check workspace itself.
1624 if contains(geo) {
1625 return (InsertWorkspace::Existing(ws.id()), geo);
1626 }
1627
1628 last_geo = geo;
1629 last_idx = idx;
1630 }
1631
1632 // Anything below.
1633 (InsertWorkspace::NewAt(last_idx + 1), dummy)
1634 }
1635
1636 pub fn render_above_top_layer(&self) -> bool {
1637 // Render above the top layer only if the view is stationary.
1638 if self.workspace_switch.is_some() || self.overview_progress.is_some() {
1639 return false;
1640 }
1641
1642 let ws = &self.workspaces[self.active_workspace_idx];
1643 ws.render_above_top_layer()
1644 }
1645
1646 pub fn render_insert_hint_between_workspaces<R: NiriRenderer>(
1647 &self,
1648 renderer: &mut R,
1649 push: &mut dyn FnMut(MonitorRenderElement<R>),
1650 ) {
1651 if self.options.layout.insert_hint.off {
1652 return;
1653 }
1654 let Some(render_loc) = self.insert_hint_render_loc else {
1655 return;
1656 };
1657 let InsertWorkspace::NewAt(_) = render_loc.workspace else {
1658 return;
1659 };
1660
1661 self.insert_hint_element
1662 .render(renderer, render_loc.location, &mut |elem| {
1663 let elem = MonitorInnerRenderElement::UncroppedInsertHint(elem);
1664 let elem = RescaleRenderElement::from_element(elem, Point::default(), 1.);
1665 let elem =
1666 RelocateRenderElement::from_element(elem, Point::default(), Relocate::Relative);
1667 push(elem);
1668 });
1669 }
1670
1671 pub fn render_workspaces<R: NiriRenderer>(
1672 &self,
1673 mut ctx: RenderCtx<R>,
1674 focus_ring: bool,
1675 push: &mut dyn FnMut(MonitorRenderElement<R>),
1676 ) {
1677 let _span = tracy_client::span!("Monitor::render_workspaces");
1678
1679 let scale = self.scale.fractional_scale();
1680 // Ceil the height in physical pixels.
1681 let height = (self.view_size.h * scale).ceil() as i32;
1682
1683 // Crop the elements to prevent them overflowing, currently visible during a workspace
1684 // switch.
1685 //
1686 // HACK: crop to infinite bounds at least horizontally where we
1687 // know there's no workspace joining or monitor bounds, otherwise
1688 // it will cut pixel shaders and mess up the coordinate space.
1689 // There's also a damage tracking bug which causes glitched
1690 // rendering for maximized GTK windows.
1691 //
1692 // FIXME: use proper bounds after fixing the Crop element.
1693 let crop_bounds = if self.workspace_switch.is_some() || self.overview_progress.is_some() {
1694 Rectangle::new(
1695 Point::from((-i32::MAX / 2, 0)),
1696 Size::from((i32::MAX, height)),
1697 )
1698 } else {
1699 Rectangle::new(
1700 Point::from((-i32::MAX / 2, -i32::MAX / 2)),
1701 Size::from((i32::MAX, i32::MAX)),
1702 )
1703 };
1704
1705 let zoom = self.overview_zoom();
1706
1707 let insert_hint_render_loc = self
1708 .insert_hint_render_loc
1709 .filter(|_| !self.options.layout.insert_hint.off);
1710
1711 let scale_relocate = move |geo: Rectangle<f64, Logical>, elem| {
1712 let elem = RescaleRenderElement::from_element(elem, Point::from((0, 0)), zoom);
1713 RelocateRenderElement::from_element(
1714 elem,
1715 // The offset we get from workspaces_with_render_geo() is already
1716 // rounded to physical pixels, but it's in the logical coordinate
1717 // space, so we need to convert it to physical.
1718 geo.loc.to_physical_precise_round(scale),
1719 Relocate::Relative,
1720 )
1721 };
1722
1723 for (ws, geo) in self.workspaces_with_render_geo() {
1724 // Macro instead of closure because ws and insert hint have different elem types.
1725 macro_rules! push {
1726 () => {{
1727 &mut |elem| {
1728 let elem = CropRenderElement::from_element(elem, scale, crop_bounds);
1729 if let Some(elem) = elem {
1730 let elem = MonitorInnerRenderElement::from(elem);
1731 push(scale_relocate(geo, elem));
1732 }
1733 }
1734 }};
1735 }
1736
1737 let xray_pos = XrayPos::new(geo.loc, zoom);
1738
1739 ws.render_floating(ctx.r(), xray_pos, focus_ring, push!());
1740
1741 if let Some(loc) = insert_hint_render_loc {
1742 if loc.workspace == InsertWorkspace::Existing(ws.id()) {
1743 self.insert_hint_element
1744 .render(ctx.renderer, loc.location, push!());
1745 }
1746 }
1747
1748 ws.render_scrolling(ctx.r(), xray_pos, focus_ring, push!());
1749 }
1750 }
1751
1752 pub fn render_workspace_shadows<R: NiriRenderer>(
1753 &self,
1754 renderer: &mut R,
1755 push: &mut dyn FnMut(MonitorRenderElement<R>),
1756 ) {
1757 let Some(progress) = self.overview_progress.as_ref().map(|p| p.clamped_value()) else {
1758 return;
1759 };
1760 let alpha = progress.clamp(0., 1.) as f32;
1761
1762 let _span = tracy_client::span!("Monitor::render_workspace_shadows");
1763
1764 let scale = self.scale.fractional_scale();
1765 let zoom = self.overview_zoom();
1766
1767 for (ws, geo) in self.workspaces_with_render_geo() {
1768 ws.render_shadow(renderer, &mut |elem| {
1769 let elem = elem.with_alpha(alpha);
1770 let elem = MonitorInnerRenderElement::Shadow(elem);
1771 let elem = RescaleRenderElement::from_element(elem, Point::from((0, 0)), zoom);
1772 let elem = RelocateRenderElement::from_element(
1773 elem,
1774 geo.loc.to_physical_precise_round(scale),
1775 Relocate::Relative,
1776 );
1777 push(elem);
1778 });
1779 }
1780 }
1781
1782 pub fn workspace_switch_gesture_begin(&mut self, is_touchpad: bool) {
1783 let center_idx = self.active_workspace_idx;
1784 let current_idx = self.workspace_render_idx();
1785
1786 let gesture = WorkspaceSwitchGesture {
1787 center_idx,
1788 start_idx: current_idx,
1789 current_idx,
1790 animation: None,
1791 tracker: SwipeTracker::new(),
1792 is_touchpad,
1793 is_clamped: !self.overview_open,
1794 dnd_last_event_time: None,
1795 dnd_nonzero_start_time: None,
1796 };
1797 self.workspace_switch = Some(WorkspaceSwitch::Gesture(gesture));
1798 }
1799
1800 pub fn dnd_scroll_gesture_begin(&mut self) {
1801 if let Some(WorkspaceSwitch::Gesture(WorkspaceSwitchGesture {
1802 dnd_last_event_time: Some(_),
1803 ..
1804 })) = &self.workspace_switch
1805 {
1806 // Already active.
1807 return;
1808 }
1809
1810 if !self.overview_open {
1811 // This gesture is only for the overview.
1812 return;
1813 }
1814
1815 let center_idx = self.active_workspace_idx;
1816 let current_idx = self.workspace_render_idx();
1817
1818 let gesture = WorkspaceSwitchGesture {
1819 center_idx,
1820 start_idx: current_idx,
1821 current_idx,
1822 animation: None,
1823 tracker: SwipeTracker::new(),
1824 is_touchpad: false,
1825 is_clamped: false,
1826 dnd_last_event_time: Some(self.clock.now_unadjusted()),
1827 dnd_nonzero_start_time: None,
1828 };
1829 self.workspace_switch = Some(WorkspaceSwitch::Gesture(gesture));
1830 }
1831
1832 pub fn workspace_switch_gesture_update(
1833 &mut self,
1834 delta_y: f64,
1835 timestamp: Duration,
1836 is_touchpad: bool,
1837 ) -> Option<bool> {
1838 let Some(WorkspaceSwitch::Gesture(gesture)) = &self.workspace_switch else {
1839 return None;
1840 };
1841
1842 if gesture.is_touchpad != is_touchpad || gesture.dnd_last_event_time.is_some() {
1843 return None;
1844 }
1845
1846 let zoom = self.overview_zoom();
1847 let total_height = if gesture.is_touchpad {
1848 WORKSPACE_GESTURE_MOVEMENT
1849 } else {
1850 self.workspace_size_with_gap(1.).h
1851 };
1852
1853 let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
1854 return None;
1855 };
1856
1857 // Reduce the effect of zoom on the touchpad somewhat.
1858 let delta_scale = if gesture.is_touchpad {
1859 (zoom - 1.) / 2.5 + 1.
1860 } else {
1861 zoom
1862 };
1863
1864 let delta_y = delta_y / delta_scale;
1865 let mut rubber_band = WORKSPACE_GESTURE_RUBBER_BAND;
1866 rubber_band.limit /= zoom;
1867
1868 gesture.tracker.push(delta_y, timestamp);
1869
1870 let pos = gesture.tracker.pos() / total_height;
1871
1872 let (min, max) = gesture.min_max(self.workspaces.len());
1873 let new_idx = gesture.start_idx + pos;
1874 let new_idx = rubber_band.clamp(min, max, new_idx);
1875
1876 if gesture.current_idx == new_idx {
1877 return Some(false);
1878 }
1879
1880 gesture.current_idx = new_idx;
1881 Some(true)
1882 }
1883
1884 pub fn dnd_scroll_gesture_scroll(&mut self, pos: Point<f64, Logical>, speed: f64) -> bool {
1885 let zoom = self.overview_zoom();
1886
1887 let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
1888 return false;
1889 };
1890
1891 let Some(last_time) = gesture.dnd_last_event_time else {
1892 // Not a DnD scroll.
1893 return false;
1894 };
1895
1896 let config = &self.options.gestures.dnd_edge_workspace_switch;
1897 let trigger_height = config.trigger_height;
1898
1899 // Restrict the scrolling horizontally to the strip of workspaces to avoid unwanted trigger
1900 // after using the hot corner or during horizontal scroll.
1901 let width = self.view_size.w * zoom;
1902 let x = pos.x - (self.view_size.w - width) / 2.;
1903
1904 // Consider the working area so layer-shell docks and such don't prevent scrolling.
1905 let y = pos.y - self.working_area.loc.y;
1906 let height = self.working_area.size.h;
1907
1908 let y = y.clamp(0., height);
1909 let trigger_height = trigger_height.clamp(0., height / 2.);
1910
1911 let delta = if x < 0. || width <= x {
1912 // Outside the bounds horizontally.
1913 0.
1914 } else if y < trigger_height {
1915 -(trigger_height - y)
1916 } else if height - y < trigger_height {
1917 trigger_height - (height - y)
1918 } else {
1919 0.
1920 };
1921
1922 let delta = if trigger_height < 0.01 {
1923 // Sanity check for trigger-height 0 or small window sizes.
1924 0.
1925 } else {
1926 // Normalize to [0, 1].
1927 delta / trigger_height
1928 };
1929 let delta = delta * speed;
1930
1931 let now = self.clock.now_unadjusted();
1932 gesture.dnd_last_event_time = Some(now);
1933
1934 if delta == 0. {
1935 // We're outside the scrolling zone.
1936 gesture.dnd_nonzero_start_time = None;
1937 return false;
1938 }
1939
1940 let nonzero_start = *gesture.dnd_nonzero_start_time.get_or_insert(now);
1941
1942 // Delay starting the gesture a bit to avoid unwanted movement when dragging across
1943 // monitors.
1944 let delay = Duration::from_millis(u64::from(config.delay_ms));
1945 if now.saturating_sub(nonzero_start) < delay {
1946 return true;
1947 }
1948
1949 let time_delta = now.saturating_sub(last_time).as_secs_f64();
1950
1951 let delta = delta * time_delta * config.max_speed;
1952
1953 gesture.tracker.push(delta, now);
1954
1955 let total_height = WORKSPACE_DND_EDGE_SCROLL_MOVEMENT;
1956 let pos = gesture.tracker.pos() / total_height;
1957 let unclamped = gesture.start_idx + pos;
1958
1959 let (min, max) = gesture.min_max(self.workspaces.len());
1960 let clamped = unclamped.clamp(min, max);
1961
1962 // Make sure that DnD scrolling too much outside the min/max does not "build up".
1963 gesture.start_idx += clamped - unclamped;
1964 gesture.current_idx = clamped;
1965
1966 true
1967 }
1968
1969 pub fn workspace_switch_gesture_end(&mut self, is_touchpad: Option<bool>) -> bool {
1970 let Some(WorkspaceSwitch::Gesture(gesture)) = &self.workspace_switch else {
1971 return false;
1972 };
1973
1974 if is_touchpad.is_some_and(|x| gesture.is_touchpad != x) {
1975 return false;
1976 }
1977
1978 let zoom = self.overview_zoom();
1979 let total_height = if gesture.dnd_last_event_time.is_some() {
1980 WORKSPACE_DND_EDGE_SCROLL_MOVEMENT
1981 } else if gesture.is_touchpad {
1982 WORKSPACE_GESTURE_MOVEMENT
1983 } else {
1984 self.workspace_size_with_gap(1.).h
1985 };
1986
1987 let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
1988 return false;
1989 };
1990
1991 // Take into account any idle time between the last event and now.
1992 let now = self.clock.now_unadjusted();
1993 gesture.tracker.push(0., now);
1994
1995 let mut rubber_band = WORKSPACE_GESTURE_RUBBER_BAND;
1996 rubber_band.limit /= zoom;
1997
1998 let mut velocity = gesture.tracker.velocity() / total_height;
1999 let current_pos = gesture.tracker.pos() / total_height;
2000 let pos = gesture.tracker.projected_end_pos() / total_height;
2001
2002 let (min, max) = gesture.min_max(self.workspaces.len());
2003 let new_idx = gesture.start_idx + pos;
2004
2005 let new_idx = new_idx.clamp(min, max);
2006 let new_idx = new_idx.round() as usize;
2007
2008 velocity *= rubber_band.clamp_derivative(min, max, gesture.start_idx + current_pos);
2009
2010 if self.active_workspace_idx != new_idx {
2011 self.previous_workspace_id = Some(self.workspaces[self.active_workspace_idx].id());
2012 }
2013
2014 self.active_workspace_idx = new_idx;
2015 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
2016 self.clock.clone(),
2017 gesture.current_idx,
2018 new_idx as f64,
2019 velocity,
2020 self.options.animations.workspace_switch.0,
2021 )));
2022
2023 true
2024 }
2025
2026 pub fn dnd_scroll_gesture_end(&mut self) {
2027 if !matches!(
2028 self.workspace_switch,
2029 Some(WorkspaceSwitch::Gesture(WorkspaceSwitchGesture {
2030 dnd_last_event_time: Some(_),
2031 ..
2032 }))
2033 ) {
2034 // Not a DnD scroll.
2035 return;
2036 };
2037
2038 self.workspace_switch_gesture_end(None);
2039 }
2040
2041 pub fn scale(&self) -> smithay::output::Scale {
2042 self.scale
2043 }
2044
2045 pub fn view_size(&self) -> Size<f64, Logical> {
2046 self.view_size
2047 }
2048
2049 pub fn working_area(&self) -> Rectangle<f64, Logical> {
2050 self.working_area
2051 }
2052
2053 pub fn layout_config(&self) -> Option<&niri_config::LayoutPart> {
2054 self.layout_config.as_ref()
2055 }
2056
2057 #[cfg(test)]
2058 pub(super) fn verify_invariants(&self) {
2059 use approx::assert_abs_diff_eq;
2060
2061 let options =
2062 Options::clone(&self.base_options).with_merged_layout(self.layout_config.as_ref());
2063 assert_eq!(&*self.options, &options);
2064
2065 assert!(
2066 !self.workspaces.is_empty(),
2067 "monitor must have at least one workspace"
2068 );
2069 assert!(self.active_workspace_idx < self.workspaces.len());
2070
2071 if let Some(WorkspaceSwitch::Animation(anim)) = &self.workspace_switch {
2072 let before_idx = anim.from() as usize;
2073 let after_idx = anim.to() as usize;
2074
2075 assert!(before_idx < self.workspaces.len());
2076 assert!(after_idx < self.workspaces.len());
2077 }
2078
2079 assert!(
2080 !self.workspaces.last().unwrap().has_windows(),
2081 "monitor must have an empty workspace in the end"
2082 );
2083 if self.options.layout.empty_workspace_above_first {
2084 assert!(
2085 !self.workspaces.first().unwrap().has_windows(),
2086 "first workspace must be empty when empty_workspace_above_first is set"
2087 )
2088 }
2089
2090 assert!(
2091 self.workspaces.last().unwrap().name.is_none(),
2092 "monitor must have an unnamed workspace in the end"
2093 );
2094 if self.options.layout.empty_workspace_above_first {
2095 assert!(
2096 self.workspaces.first().unwrap().name.is_none(),
2097 "first workspace must be unnamed when empty_workspace_above_first is set"
2098 )
2099 }
2100
2101 if self.options.layout.empty_workspace_above_first {
2102 assert!(
2103 self.workspaces.len() != 2,
2104 "if empty_workspace_above_first is set there must be just 1 or 3+ workspaces"
2105 )
2106 }
2107
2108 // If there's no workspace switch in progress, there can't be any non-last non-active
2109 // empty workspaces. If empty_workspace_above_first is set then the first workspace
2110 // will be empty too.
2111 let pre_skip = if self.options.layout.empty_workspace_above_first {
2112 1
2113 } else {
2114 0
2115 };
2116 if self.workspace_switch.is_none() {
2117 for (idx, ws) in self
2118 .workspaces
2119 .iter()
2120 .enumerate()
2121 .skip(pre_skip)
2122 .rev()
2123 // skip last
2124 .skip(1)
2125 {
2126 if idx != self.active_workspace_idx {
2127 assert!(
2128 ws.has_windows_or_name(),
2129 "non-active workspace can't be empty and unnamed except the last one"
2130 );
2131 }
2132 }
2133 }
2134
2135 for workspace in &self.workspaces {
2136 assert_eq!(self.clock, workspace.clock);
2137
2138 assert_eq!(
2139 self.scale().integer_scale(),
2140 workspace.scale().integer_scale()
2141 );
2142 assert_eq!(
2143 self.scale().fractional_scale(),
2144 workspace.scale().fractional_scale()
2145 );
2146 assert_eq!(self.view_size, workspace.view_size());
2147 assert_eq!(self.working_area, workspace.working_area());
2148
2149 assert_eq!(
2150 workspace.base_options, self.options,
2151 "workspace options must be synchronized with monitor"
2152 );
2153 }
2154
2155 let scale = self.scale().fractional_scale();
2156 let iter = self.workspaces_with_render_geo();
2157 for (_ws, ws_geo) in iter {
2158 let pos = ws_geo.loc;
2159 let rounded_pos = pos.to_physical_precise_round(scale).to_logical(scale);
2160
2161 // Workspace positions must be rounded to physical pixels.
2162 assert_abs_diff_eq!(pos.x, rounded_pos.x, epsilon = 1e-5);
2163 assert_abs_diff_eq!(pos.y, rounded_pos.y, epsilon = 1e-5);
2164 }
2165 }
2166}