forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBad3847fIvan Molodetskikh1 year ago2457 commits

monitor.rs2176 lines, 74.7 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_loc_diff = Point::from((0., hint_height + hint_gap));
1156 let hint_loc = next_ws_geo.loc - hint_loc_diff;
1157 let hint_size = Size::from((next_ws_geo.size.w, hint_height));
1158
1159 // FIXME: sometimes the hint ends up 1 px wider than necessary and/or 1 px
1160 // narrower than necessary. The values here seem correct. Might have to do with
1161 // how zooming out currently doesn't round to output scale properly.
1162
1163 // Compute view rect as if we're above the next workspace (rather than below
1164 // the previous one).
1165 let view_rect = Rectangle::new(hint_loc_diff, next_ws_geo.size);
1166
1167 self.insert_hint_element.update_render_elements(
1168 hint_size,
1169 view_rect,
1170 CornerRadius::default(),
1171 scale,
1172 );
1173 self.insert_hint_render_loc = Some(InsertHintRenderLoc {
1174 workspace: hint.workspace,
1175 location: hint_loc,
1176 });
1177 }
1178 }
1179 }
1180 }
1181
1182 pub fn update_config(&mut self, base_options: Rc<Options>) {
1183 let options =
1184 Rc::new(Options::clone(&base_options).with_merged_layout(self.layout_config.as_ref()));
1185
1186 if self.options.layout.empty_workspace_above_first
1187 != options.layout.empty_workspace_above_first
1188 && self.workspaces.len() > 1
1189 {
1190 if options.layout.empty_workspace_above_first {
1191 self.add_workspace_top();
1192 } else if self.workspace_switch.is_none() && self.active_workspace_idx != 0 {
1193 self.workspaces.remove(0);
1194 self.active_workspace_idx = self.active_workspace_idx.saturating_sub(1);
1195 }
1196 }
1197
1198 for ws in &mut self.workspaces {
1199 ws.update_config(options.clone());
1200 }
1201
1202 self.insert_hint_element
1203 .update_config(options.layout.insert_hint);
1204
1205 self.base_options = base_options;
1206 self.options = options;
1207 }
1208
1209 pub fn update_layout_config(&mut self, layout_config: Option<niri_config::LayoutPart>) -> bool {
1210 if self.layout_config == layout_config {
1211 return false;
1212 }
1213
1214 self.layout_config = layout_config;
1215 self.update_config(self.base_options.clone());
1216
1217 true
1218 }
1219
1220 pub fn update_shaders(&mut self) {
1221 for ws in &mut self.workspaces {
1222 ws.update_shaders();
1223 }
1224
1225 self.insert_hint_element.update_shaders();
1226 }
1227
1228 pub fn update_output_size(&mut self) {
1229 self.scale = self.output.current_scale();
1230 self.view_size = output_size(&self.output);
1231 self.working_area = compute_working_area(&self.output);
1232
1233 for ws in &mut self.workspaces {
1234 ws.update_output_size();
1235 }
1236 }
1237
1238 pub fn move_workspace_down(&mut self) {
1239 let mut new_idx = min(self.active_workspace_idx + 1, self.workspaces.len() - 1);
1240 if new_idx == self.active_workspace_idx {
1241 return;
1242 }
1243
1244 self.workspaces.swap(self.active_workspace_idx, new_idx);
1245
1246 if new_idx == self.workspaces.len() - 1 {
1247 // Insert a new empty workspace.
1248 self.add_workspace_bottom();
1249 }
1250
1251 if self.options.layout.empty_workspace_above_first && self.active_workspace_idx == 0 {
1252 self.add_workspace_top();
1253 new_idx += 1;
1254 }
1255
1256 let previous_workspace_id = self.previous_workspace_id;
1257 self.activate_workspace(new_idx);
1258 self.workspace_switch = None;
1259 self.previous_workspace_id = previous_workspace_id;
1260
1261 self.clean_up_workspaces();
1262 }
1263
1264 pub fn move_workspace_up(&mut self) {
1265 let mut new_idx = self.active_workspace_idx.saturating_sub(1);
1266 if new_idx == self.active_workspace_idx {
1267 return;
1268 }
1269
1270 self.workspaces.swap(self.active_workspace_idx, new_idx);
1271
1272 if self.active_workspace_idx == self.workspaces.len() - 1 {
1273 // Insert a new empty workspace.
1274 self.add_workspace_bottom();
1275 }
1276
1277 if self.options.layout.empty_workspace_above_first && new_idx == 0 {
1278 self.add_workspace_top();
1279 new_idx += 1;
1280 }
1281
1282 let previous_workspace_id = self.previous_workspace_id;
1283 self.activate_workspace(new_idx);
1284 self.workspace_switch = None;
1285 self.previous_workspace_id = previous_workspace_id;
1286
1287 self.clean_up_workspaces();
1288 }
1289
1290 pub fn move_workspace_to_idx(&mut self, old_idx: usize, new_idx: usize) {
1291 if self.workspaces.len() <= old_idx {
1292 return;
1293 }
1294
1295 let mut new_idx = new_idx.clamp(0, self.workspaces.len() - 1);
1296 if old_idx == new_idx {
1297 return;
1298 }
1299
1300 let ws = self.workspaces.remove(old_idx);
1301 self.workspaces.insert(new_idx, ws);
1302
1303 if new_idx > old_idx {
1304 if new_idx == self.workspaces.len() - 1 {
1305 // Insert a new empty workspace.
1306 self.add_workspace_bottom();
1307 }
1308
1309 if self.options.layout.empty_workspace_above_first && old_idx == 0 {
1310 self.add_workspace_top();
1311 new_idx += 1;
1312 }
1313 } else {
1314 if old_idx == self.workspaces.len() - 1 {
1315 // Insert a new empty workspace.
1316 self.add_workspace_bottom();
1317 }
1318
1319 if self.options.layout.empty_workspace_above_first && new_idx == 0 {
1320 self.add_workspace_top();
1321 new_idx += 1;
1322 }
1323 }
1324
1325 // Only refocus the workspace if it was already focused
1326 if self.active_workspace_idx == old_idx {
1327 self.active_workspace_idx = new_idx;
1328 // If the workspace order was switched so that the current workspace moved down the
1329 // workspace stack, focus correctly
1330 } else if new_idx <= self.active_workspace_idx && old_idx > self.active_workspace_idx {
1331 self.active_workspace_idx += 1;
1332 } else if new_idx >= self.active_workspace_idx && old_idx < self.active_workspace_idx {
1333 self.active_workspace_idx = self.active_workspace_idx.saturating_sub(1);
1334 }
1335
1336 self.workspace_switch = None;
1337
1338 self.clean_up_workspaces();
1339 }
1340
1341 /// Returns the geometry of the active tile relative to and clamped to the output.
1342 ///
1343 /// During animations, assumes the final view position.
1344 pub fn active_tile_visual_rectangle(&self) -> Option<Rectangle<f64, Logical>> {
1345 if self.overview_open {
1346 return None;
1347 }
1348
1349 self.active_workspace_ref().active_tile_visual_rectangle()
1350 }
1351
1352 fn workspace_size(&self, zoom: f64) -> Size<f64, Logical> {
1353 let ws_size = self.view_size.upscale(zoom);
1354 let scale = self.scale.fractional_scale();
1355 ws_size.to_physical_precise_ceil(scale).to_logical(scale)
1356 }
1357
1358 fn workspace_gap(&self, zoom: f64) -> f64 {
1359 let scale = self.scale.fractional_scale();
1360 let gap = self.view_size.h * 0.1 * zoom;
1361 round_logical_in_physical_max1(scale, gap)
1362 }
1363
1364 fn workspace_size_with_gap(&self, zoom: f64) -> Size<f64, Logical> {
1365 let gap = self.workspace_gap(zoom);
1366 self.workspace_size(zoom) + Size::from((0., gap))
1367 }
1368
1369 pub fn overview_zoom(&self) -> f64 {
1370 let progress = self.overview_progress.as_ref().map(|p| p.value());
1371 compute_overview_zoom(&self.options, progress)
1372 }
1373
1374 pub(super) fn set_overview_progress(&mut self, progress: Option<&super::OverviewProgress>) {
1375 let prev_render_idx = self.workspace_render_idx();
1376 self.overview_progress = progress.map(OverviewProgress::from);
1377 let new_render_idx = self.workspace_render_idx();
1378
1379 // If the view jumped (can happen when going from corrected to uncorrected render_idx, for
1380 // example when toggling the overview in the middle of an overview animation), then restart
1381 // the workspace switch to avoid jumps.
1382 if prev_render_idx != new_render_idx {
1383 if let Some(WorkspaceSwitch::Animation(anim)) = &mut self.workspace_switch {
1384 // FIXME: maintain velocity.
1385 *anim = anim.restarted(prev_render_idx, anim.to(), 0.);
1386 }
1387 }
1388 }
1389
1390 #[cfg(test)]
1391 pub(super) fn overview_progress_value(&self) -> Option<f64> {
1392 self.overview_progress.as_ref().map(|p| p.value())
1393 }
1394
1395 pub fn workspace_render_idx(&self) -> f64 {
1396 // If workspace switch and overview progress are matching animations, then compute a
1397 // correction term to make the movement appear monotonic.
1398 if let (
1399 Some(WorkspaceSwitch::Animation(switch_anim)),
1400 Some(OverviewProgress::Animation(progress_anim)),
1401 ) = (&self.workspace_switch, &self.overview_progress)
1402 {
1403 if switch_anim.start_time() == progress_anim.start_time()
1404 && (switch_anim.duration().as_secs_f64() - progress_anim.duration().as_secs_f64())
1405 .abs()
1406 <= 0.001
1407 {
1408 #[rustfmt::skip]
1409 // How this was derived:
1410 //
1411 // - Assume we're animating a zoom + switch. Consider switch "from" and "to".
1412 // These are render_idx values, so first workspace to second would have switch
1413 // from = 0. and to = 1. regardless of the zoom level.
1414 //
1415 // - At the start, the point at "from" is at Y = 0. We're moving the point at "to"
1416 // to Y = 0. We want this to be a monotonic motion in apparent coordinates (after
1417 // zoom).
1418 //
1419 // - Height at the start:
1420 // from_height = (size.h + gap) * from_zoom.
1421 //
1422 // - Current height:
1423 // current_height = (size.h + gap) * zoom.
1424 //
1425 // - We're moving the "to" point to Y = 0:
1426 // to_y = 0.
1427 //
1428 // - The initial position of the point we're moving:
1429 // from_y = (to - from) * from_height.
1430 //
1431 // - We want this point to travel monotonically in apparent coordinates:
1432 // current_y = from_y + (to_y - from_y) * progress,
1433 // where progress is from 0 to 1, equals to the animation progress (switch and
1434 // zoom are the same since they are synchronized).
1435 //
1436 // - Derive the Y of the first workspace from this:
1437 // first_y = current_y - to * current_height.
1438 //
1439 // Now, let's substitute and rearrange the terms.
1440 //
1441 // - current_y = from_y + (0 - (to - from) * from_height) * progress
1442 // - progress = (switch_anim.value() - from) / (to - from)
1443 // - current_y = from_y - (to - from) * from_height * (switch_anim.value() - from) / (to - from)
1444 // - current_y = from_y - from_height * (switch_anim.value() - from)
1445 // - first_y = from_y - from_height * (switch_anim.value() - from) - to * current_height
1446 // - first_y = (to - from) * from_height - from_height * (switch_anim.value() - from) - to * current_height
1447 // - first_y = to * from_height - switch_anim.value() * from_height - to * current_height
1448 // - first_y = -switch_anim.value() * from_height + to * (from_height - current_height)
1449 let from = progress_anim.from();
1450 let from_zoom = compute_overview_zoom(&self.options, Some(from));
1451 let from_ws_height_with_gap = self.workspace_size_with_gap(from_zoom).h;
1452
1453 let zoom = self.overview_zoom();
1454 let ws_height_with_gap = self.workspace_size_with_gap(zoom).h;
1455
1456 let first_ws_y = -switch_anim.value() * from_ws_height_with_gap
1457 + switch_anim.to() * (from_ws_height_with_gap - ws_height_with_gap);
1458
1459 return -first_ws_y / ws_height_with_gap;
1460 }
1461 };
1462
1463 if let Some(switch) = &self.workspace_switch {
1464 switch.current_idx()
1465 } else {
1466 self.active_workspace_idx as f64
1467 }
1468 }
1469
1470 pub fn workspaces_render_geo(&self) -> impl Iterator<Item = Rectangle<f64, Logical>> {
1471 let scale = self.scale.fractional_scale();
1472 let zoom = self.overview_zoom();
1473
1474 let ws_size = self.workspace_size(zoom);
1475 let gap = self.workspace_gap(zoom);
1476 let ws_height_with_gap = ws_size.h + gap;
1477
1478 let static_offset = (self.view_size.to_point() - ws_size.to_point()).downscale(2.);
1479 let static_offset = static_offset
1480 .to_physical_precise_round(scale)
1481 .to_logical(scale);
1482
1483 let first_ws_y = -self.workspace_render_idx() * ws_height_with_gap;
1484 let first_ws_y = round_logical_in_physical(scale, first_ws_y);
1485
1486 // Return position for one-past-last workspace too.
1487 (0..=self.workspaces.len()).map(move |idx| {
1488 let y = first_ws_y + idx as f64 * ws_height_with_gap;
1489 let loc = Point::from((0., y)) + static_offset;
1490 Rectangle::new(loc, ws_size)
1491 })
1492 }
1493
1494 pub fn workspaces_with_render_geo(
1495 &self,
1496 ) -> impl Iterator<Item = (&Workspace<W>, Rectangle<f64, Logical>)> {
1497 let output_geo = Rectangle::from_size(self.view_size);
1498
1499 let geo = self.workspaces_render_geo();
1500 zip(self.workspaces.iter(), geo)
1501 // Cull out workspaces outside the output.
1502 .filter(move |(_ws, geo)| geo.intersection(output_geo).is_some())
1503 }
1504
1505 pub fn workspaces_with_render_geo_idx(
1506 &self,
1507 ) -> impl Iterator<Item = ((usize, &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().enumerate(), 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_mut(
1517 &mut self,
1518 cull: bool,
1519 ) -> impl Iterator<Item = (&mut Workspace<W>, Rectangle<f64, Logical>)> {
1520 let output_geo = Rectangle::from_size(self.view_size);
1521
1522 let geo = self.workspaces_render_geo();
1523 zip(self.workspaces.iter_mut(), geo)
1524 // Cull out workspaces outside the output.
1525 .filter(move |(_ws, geo)| !cull || geo.intersection(output_geo).is_some())
1526 }
1527
1528 pub fn workspace_under(
1529 &self,
1530 pos_within_output: Point<f64, Logical>,
1531 ) -> Option<(&Workspace<W>, Rectangle<f64, Logical>)> {
1532 let (ws, geo) = self.workspaces_with_render_geo().find_map(|(ws, geo)| {
1533 // Extend width to entire output.
1534 let loc = Point::from((0., geo.loc.y));
1535 let size = Size::from((self.view_size.w, geo.size.h));
1536 let bounds = Rectangle::new(loc, size);
1537
1538 bounds.contains(pos_within_output).then_some((ws, geo))
1539 })?;
1540 Some((ws, geo))
1541 }
1542
1543 pub fn workspace_under_narrow(
1544 &self,
1545 pos_within_output: Point<f64, Logical>,
1546 ) -> Option<&Workspace<W>> {
1547 self.workspaces_with_render_geo()
1548 .find_map(|(ws, geo)| geo.contains(pos_within_output).then_some(ws))
1549 }
1550
1551 pub fn window_under(&self, pos_within_output: Point<f64, Logical>) -> Option<(&W, HitType)> {
1552 let (ws, geo) = self.workspace_under(pos_within_output)?;
1553
1554 if self.overview_progress.is_some() {
1555 let zoom = self.overview_zoom();
1556 let pos_within_workspace = (pos_within_output - geo.loc).downscale(zoom);
1557 let (win, hit) = ws.window_under(pos_within_workspace)?;
1558 // During the overview animation, we cannot do input hits because we cannot really
1559 // represent scaled windows properly.
1560 Some((win, hit.to_activate()))
1561 } else {
1562 let (win, hit) = ws.window_under(pos_within_output - geo.loc)?;
1563 Some((win, hit.offset_win_pos(geo.loc)))
1564 }
1565 }
1566
1567 pub fn resize_edges_under(&self, pos_within_output: Point<f64, Logical>) -> Option<ResizeEdge> {
1568 if self.overview_progress.is_some() {
1569 return None;
1570 }
1571
1572 let (ws, geo) = self.workspace_under(pos_within_output)?;
1573 ws.resize_edges_under(pos_within_output - geo.loc)
1574 }
1575
1576 pub(super) fn insert_position(
1577 &self,
1578 pos_within_output: Point<f64, Logical>,
1579 ) -> (InsertWorkspace, Rectangle<f64, Logical>) {
1580 let mut iter = self.workspaces_with_render_geo_idx();
1581
1582 let dummy = Rectangle::default();
1583
1584 // Monitors always have at least one workspace.
1585 let ((idx, ws), geo) = iter.next().unwrap();
1586
1587 // Check if above first.
1588 if pos_within_output.y < geo.loc.y {
1589 return (InsertWorkspace::NewAt(idx), dummy);
1590 }
1591
1592 let contains = move |geo: Rectangle<f64, Logical>| {
1593 geo.loc.y <= pos_within_output.y && pos_within_output.y < geo.loc.y + geo.size.h
1594 };
1595
1596 // Check first.
1597 if contains(geo) {
1598 return (InsertWorkspace::Existing(ws.id()), geo);
1599 }
1600
1601 let mut last_geo = geo;
1602 let mut last_idx = idx;
1603 for ((idx, ws), geo) in iter {
1604 // Check gap above.
1605 let gap_loc = Point::from((last_geo.loc.x, last_geo.loc.y + last_geo.size.h));
1606 let gap_size = Size::from((geo.size.w, geo.loc.y - gap_loc.y));
1607 let gap_geo = Rectangle::new(gap_loc, gap_size);
1608 if contains(gap_geo) {
1609 return (InsertWorkspace::NewAt(idx), dummy);
1610 }
1611
1612 // Check workspace itself.
1613 if contains(geo) {
1614 return (InsertWorkspace::Existing(ws.id()), geo);
1615 }
1616
1617 last_geo = geo;
1618 last_idx = idx;
1619 }
1620
1621 // Anything below.
1622 (InsertWorkspace::NewAt(last_idx + 1), dummy)
1623 }
1624
1625 pub fn render_above_top_layer(&self) -> bool {
1626 // Render above the top layer only if the view is stationary.
1627 if self.workspace_switch.is_some() || self.overview_progress.is_some() {
1628 return false;
1629 }
1630
1631 let ws = &self.workspaces[self.active_workspace_idx];
1632 ws.render_above_top_layer()
1633 }
1634
1635 pub fn render_insert_hint_between_workspaces<R: NiriRenderer>(
1636 &self,
1637 renderer: &mut R,
1638 ) -> impl Iterator<Item = MonitorRenderElement<R>> {
1639 let mut rv = None;
1640
1641 if !self.options.layout.insert_hint.off {
1642 if let Some(render_loc) = self.insert_hint_render_loc {
1643 if let InsertWorkspace::NewAt(_) = render_loc.workspace {
1644 let iter = self
1645 .insert_hint_element
1646 .render(renderer, render_loc.location)
1647 .map(MonitorInnerRenderElement::UncroppedInsertHint);
1648 rv = Some(iter);
1649 }
1650 }
1651 }
1652
1653 rv.into_iter().flatten().map(|elem| {
1654 let elem = RescaleRenderElement::from_element(elem, Point::default(), 1.);
1655 RelocateRenderElement::from_element(elem, Point::default(), Relocate::Relative)
1656 })
1657 }
1658
1659 pub fn render_elements<'a, R: NiriRenderer>(
1660 &'a self,
1661 renderer: &'a mut R,
1662 target: RenderTarget,
1663 focus_ring: bool,
1664 ) -> impl Iterator<
1665 Item = (
1666 Rectangle<f64, Logical>,
1667 MonitorRenderElement<R>,
1668 impl Iterator<Item = MonitorRenderElement<R>> + 'a,
1669 ),
1670 > {
1671 let _span = tracy_client::span!("Monitor::render_elements");
1672
1673 let scale = self.scale.fractional_scale();
1674 // Ceil the height in physical pixels.
1675 let height = (self.view_size.h * scale).ceil() as i32;
1676
1677 // Crop the elements to prevent them overflowing, currently visible during a workspace
1678 // switch.
1679 //
1680 // HACK: crop to infinite bounds at least horizontally where we
1681 // know there's no workspace joining or monitor bounds, otherwise
1682 // it will cut pixel shaders and mess up the coordinate space.
1683 // There's also a damage tracking bug which causes glitched
1684 // rendering for maximized GTK windows.
1685 //
1686 // FIXME: use proper bounds after fixing the Crop element.
1687 let crop_bounds = if self.workspace_switch.is_some() || self.overview_progress.is_some() {
1688 Rectangle::new(
1689 Point::from((-i32::MAX / 2, 0)),
1690 Size::from((i32::MAX, height)),
1691 )
1692 } else {
1693 Rectangle::new(
1694 Point::from((-i32::MAX / 2, -i32::MAX / 2)),
1695 Size::from((i32::MAX, i32::MAX)),
1696 )
1697 };
1698
1699 let zoom = self.overview_zoom();
1700
1701 // Draw the insert hint.
1702 let mut insert_hint = None;
1703 if !self.options.layout.insert_hint.off {
1704 if let Some(render_loc) = self.insert_hint_render_loc {
1705 if let InsertWorkspace::Existing(workspace_id) = render_loc.workspace {
1706 insert_hint = Some((
1707 workspace_id,
1708 self.insert_hint_element
1709 .render(renderer, render_loc.location),
1710 ));
1711 }
1712 }
1713 }
1714
1715 self.workspaces_with_render_geo().map(move |(ws, geo)| {
1716 let map_ws_contents = move |elem: WorkspaceRenderElement<R>| {
1717 let elem = CropRenderElement::from_element(elem, scale, crop_bounds)?;
1718 let elem = MonitorInnerRenderElement::Workspace(elem);
1719 Some(elem)
1720 };
1721
1722 let (floating, scrolling) = ws.render_elements(renderer, target, focus_ring);
1723 let floating = floating.filter_map(map_ws_contents);
1724 let scrolling = scrolling.filter_map(map_ws_contents);
1725
1726 let hint = if matches!(insert_hint, Some((hint_ws_id, _)) if hint_ws_id == ws.id()) {
1727 let iter = insert_hint.take().unwrap().1;
1728 let iter = iter.filter_map(move |elem| {
1729 let elem = CropRenderElement::from_element(elem, scale, crop_bounds)?;
1730 let elem = MonitorInnerRenderElement::InsertHint(elem);
1731 Some(elem)
1732 });
1733 Some(iter)
1734 } else {
1735 None
1736 };
1737 let hint = hint.into_iter().flatten();
1738
1739 let iter = floating.chain(hint).chain(scrolling);
1740
1741 let scale_relocate = move |elem| {
1742 let elem = RescaleRenderElement::from_element(elem, Point::from((0, 0)), zoom);
1743 RelocateRenderElement::from_element(
1744 elem,
1745 // The offset we get from workspaces_with_render_positions() is already
1746 // rounded to physical pixels, but it's in the logical coordinate
1747 // space, so we need to convert it to physical.
1748 geo.loc.to_physical_precise_round(scale),
1749 Relocate::Relative,
1750 )
1751 };
1752
1753 let iter = iter.map(scale_relocate);
1754
1755 let background = ws.render_background();
1756 let background = scale_relocate(MonitorInnerRenderElement::SolidColor(background));
1757
1758 (geo, background, iter)
1759 })
1760 }
1761
1762 pub fn render_workspace_shadows<'a, R: NiriRenderer>(
1763 &'a self,
1764 renderer: &'a mut R,
1765 ) -> impl Iterator<Item = MonitorRenderElement<R>> + 'a {
1766 let _span = tracy_client::span!("Monitor::render_workspace_shadows");
1767
1768 let scale = self.scale.fractional_scale();
1769 let zoom = self.overview_zoom();
1770 let overview_clamped_progress = self.overview_progress.as_ref().map(|p| p.clamped_value());
1771
1772 self.workspaces_with_render_geo()
1773 .flat_map(move |(ws, geo)| {
1774 let shadow = overview_clamped_progress.map(|value| {
1775 ws.render_shadow(renderer)
1776 .map(move |elem| elem.with_alpha(value.clamp(0., 1.) as f32))
1777 .map(MonitorInnerRenderElement::Shadow)
1778 });
1779 let iter = shadow.into_iter().flatten();
1780
1781 iter.map(move |elem| {
1782 let elem = RescaleRenderElement::from_element(elem, Point::from((0, 0)), zoom);
1783 RelocateRenderElement::from_element(
1784 elem,
1785 geo.loc.to_physical_precise_round(scale),
1786 Relocate::Relative,
1787 )
1788 })
1789 })
1790 }
1791
1792 pub fn workspace_switch_gesture_begin(&mut self, is_touchpad: bool) {
1793 let center_idx = self.active_workspace_idx;
1794 let current_idx = self.workspace_render_idx();
1795
1796 let gesture = WorkspaceSwitchGesture {
1797 center_idx,
1798 start_idx: current_idx,
1799 current_idx,
1800 animation: None,
1801 tracker: SwipeTracker::new(),
1802 is_touchpad,
1803 is_clamped: !self.overview_open,
1804 dnd_last_event_time: None,
1805 dnd_nonzero_start_time: None,
1806 };
1807 self.workspace_switch = Some(WorkspaceSwitch::Gesture(gesture));
1808 }
1809
1810 pub fn dnd_scroll_gesture_begin(&mut self) {
1811 if let Some(WorkspaceSwitch::Gesture(WorkspaceSwitchGesture {
1812 dnd_last_event_time: Some(_),
1813 ..
1814 })) = &self.workspace_switch
1815 {
1816 // Already active.
1817 return;
1818 }
1819
1820 if !self.overview_open {
1821 // This gesture is only for the overview.
1822 return;
1823 }
1824
1825 let center_idx = self.active_workspace_idx;
1826 let current_idx = self.workspace_render_idx();
1827
1828 let gesture = WorkspaceSwitchGesture {
1829 center_idx,
1830 start_idx: current_idx,
1831 current_idx,
1832 animation: None,
1833 tracker: SwipeTracker::new(),
1834 is_touchpad: false,
1835 is_clamped: false,
1836 dnd_last_event_time: Some(self.clock.now_unadjusted()),
1837 dnd_nonzero_start_time: None,
1838 };
1839 self.workspace_switch = Some(WorkspaceSwitch::Gesture(gesture));
1840 }
1841
1842 pub fn workspace_switch_gesture_update(
1843 &mut self,
1844 delta_y: f64,
1845 timestamp: Duration,
1846 is_touchpad: bool,
1847 ) -> Option<bool> {
1848 let Some(WorkspaceSwitch::Gesture(gesture)) = &self.workspace_switch else {
1849 return None;
1850 };
1851
1852 if gesture.is_touchpad != is_touchpad || gesture.dnd_last_event_time.is_some() {
1853 return None;
1854 }
1855
1856 let zoom = self.overview_zoom();
1857 let total_height = if gesture.is_touchpad {
1858 WORKSPACE_GESTURE_MOVEMENT
1859 } else {
1860 self.workspace_size_with_gap(1.).h
1861 };
1862
1863 let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
1864 return None;
1865 };
1866
1867 // Reduce the effect of zoom on the touchpad somewhat.
1868 let delta_scale = if gesture.is_touchpad {
1869 (zoom - 1.) / 2.5 + 1.
1870 } else {
1871 zoom
1872 };
1873
1874 let delta_y = delta_y / delta_scale;
1875 let mut rubber_band = WORKSPACE_GESTURE_RUBBER_BAND;
1876 rubber_band.limit /= zoom;
1877
1878 gesture.tracker.push(delta_y, timestamp);
1879
1880 let pos = gesture.tracker.pos() / total_height;
1881
1882 let (min, max) = gesture.min_max(self.workspaces.len());
1883 let new_idx = gesture.start_idx + pos;
1884 let new_idx = rubber_band.clamp(min, max, new_idx);
1885
1886 if gesture.current_idx == new_idx {
1887 return Some(false);
1888 }
1889
1890 gesture.current_idx = new_idx;
1891 Some(true)
1892 }
1893
1894 pub fn dnd_scroll_gesture_scroll(&mut self, pos: Point<f64, Logical>, speed: f64) -> bool {
1895 let zoom = self.overview_zoom();
1896
1897 let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
1898 return false;
1899 };
1900
1901 let Some(last_time) = gesture.dnd_last_event_time else {
1902 // Not a DnD scroll.
1903 return false;
1904 };
1905
1906 let config = &self.options.gestures.dnd_edge_workspace_switch;
1907 let trigger_height = config.trigger_height;
1908
1909 // Restrict the scrolling horizontally to the strip of workspaces to avoid unwanted trigger
1910 // after using the hot corner or during horizontal scroll.
1911 let width = self.view_size.w * zoom;
1912 let x = pos.x - (self.view_size.w - width) / 2.;
1913
1914 // Consider the working area so layer-shell docks and such don't prevent scrolling.
1915 let y = pos.y - self.working_area.loc.y;
1916 let height = self.working_area.size.h;
1917
1918 let y = y.clamp(0., height);
1919 let trigger_height = trigger_height.clamp(0., height / 2.);
1920
1921 let delta = if x < 0. || width <= x {
1922 // Outside the bounds horizontally.
1923 0.
1924 } else if y < trigger_height {
1925 -(trigger_height - y)
1926 } else if height - y < trigger_height {
1927 trigger_height - (height - y)
1928 } else {
1929 0.
1930 };
1931
1932 let delta = if trigger_height < 0.01 {
1933 // Sanity check for trigger-height 0 or small window sizes.
1934 0.
1935 } else {
1936 // Normalize to [0, 1].
1937 delta / trigger_height
1938 };
1939 let delta = delta * speed;
1940
1941 let now = self.clock.now_unadjusted();
1942 gesture.dnd_last_event_time = Some(now);
1943
1944 if delta == 0. {
1945 // We're outside the scrolling zone.
1946 gesture.dnd_nonzero_start_time = None;
1947 return false;
1948 }
1949
1950 let nonzero_start = *gesture.dnd_nonzero_start_time.get_or_insert(now);
1951
1952 // Delay starting the gesture a bit to avoid unwanted movement when dragging across
1953 // monitors.
1954 let delay = Duration::from_millis(u64::from(config.delay_ms));
1955 if now.saturating_sub(nonzero_start) < delay {
1956 return true;
1957 }
1958
1959 let time_delta = now.saturating_sub(last_time).as_secs_f64();
1960
1961 let delta = delta * time_delta * config.max_speed;
1962
1963 gesture.tracker.push(delta, now);
1964
1965 let total_height = WORKSPACE_DND_EDGE_SCROLL_MOVEMENT;
1966 let pos = gesture.tracker.pos() / total_height;
1967 let unclamped = gesture.start_idx + pos;
1968
1969 let (min, max) = gesture.min_max(self.workspaces.len());
1970 let clamped = unclamped.clamp(min, max);
1971
1972 // Make sure that DnD scrolling too much outside the min/max does not "build up".
1973 gesture.start_idx += clamped - unclamped;
1974 gesture.current_idx = clamped;
1975
1976 true
1977 }
1978
1979 pub fn workspace_switch_gesture_end(&mut self, is_touchpad: Option<bool>) -> bool {
1980 let Some(WorkspaceSwitch::Gesture(gesture)) = &self.workspace_switch else {
1981 return false;
1982 };
1983
1984 if is_touchpad.is_some_and(|x| gesture.is_touchpad != x) {
1985 return false;
1986 }
1987
1988 let zoom = self.overview_zoom();
1989 let total_height = if gesture.dnd_last_event_time.is_some() {
1990 WORKSPACE_DND_EDGE_SCROLL_MOVEMENT
1991 } else if gesture.is_touchpad {
1992 WORKSPACE_GESTURE_MOVEMENT
1993 } else {
1994 self.workspace_size_with_gap(1.).h
1995 };
1996
1997 let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
1998 return false;
1999 };
2000
2001 // Take into account any idle time between the last event and now.
2002 let now = self.clock.now_unadjusted();
2003 gesture.tracker.push(0., now);
2004
2005 let mut rubber_band = WORKSPACE_GESTURE_RUBBER_BAND;
2006 rubber_band.limit /= zoom;
2007
2008 let mut velocity = gesture.tracker.velocity() / total_height;
2009 let current_pos = gesture.tracker.pos() / total_height;
2010 let pos = gesture.tracker.projected_end_pos() / total_height;
2011
2012 let (min, max) = gesture.min_max(self.workspaces.len());
2013 let new_idx = gesture.start_idx + pos;
2014
2015 let new_idx = new_idx.clamp(min, max);
2016 let new_idx = new_idx.round() as usize;
2017
2018 velocity *= rubber_band.clamp_derivative(min, max, gesture.start_idx + current_pos);
2019
2020 if self.active_workspace_idx != new_idx {
2021 self.previous_workspace_id = Some(self.workspaces[self.active_workspace_idx].id());
2022 }
2023
2024 self.active_workspace_idx = new_idx;
2025 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
2026 self.clock.clone(),
2027 gesture.current_idx,
2028 new_idx as f64,
2029 velocity,
2030 self.options.animations.workspace_switch.0,
2031 )));
2032
2033 true
2034 }
2035
2036 pub fn dnd_scroll_gesture_end(&mut self) {
2037 if !matches!(
2038 self.workspace_switch,
2039 Some(WorkspaceSwitch::Gesture(WorkspaceSwitchGesture {
2040 dnd_last_event_time: Some(_),
2041 ..
2042 }))
2043 ) {
2044 // Not a DnD scroll.
2045 return;
2046 };
2047
2048 self.workspace_switch_gesture_end(None);
2049 }
2050
2051 pub fn scale(&self) -> smithay::output::Scale {
2052 self.scale
2053 }
2054
2055 pub fn view_size(&self) -> Size<f64, Logical> {
2056 self.view_size
2057 }
2058
2059 pub fn working_area(&self) -> Rectangle<f64, Logical> {
2060 self.working_area
2061 }
2062
2063 pub fn layout_config(&self) -> Option<&niri_config::LayoutPart> {
2064 self.layout_config.as_ref()
2065 }
2066
2067 #[cfg(test)]
2068 pub(super) fn verify_invariants(&self) {
2069 use approx::assert_abs_diff_eq;
2070
2071 let options =
2072 Options::clone(&self.base_options).with_merged_layout(self.layout_config.as_ref());
2073 assert_eq!(&*self.options, &options);
2074
2075 assert!(
2076 !self.workspaces.is_empty(),
2077 "monitor must have at least one workspace"
2078 );
2079 assert!(self.active_workspace_idx < self.workspaces.len());
2080
2081 if let Some(WorkspaceSwitch::Animation(anim)) = &self.workspace_switch {
2082 let before_idx = anim.from() as usize;
2083 let after_idx = anim.to() as usize;
2084
2085 assert!(before_idx < self.workspaces.len());
2086 assert!(after_idx < self.workspaces.len());
2087 }
2088
2089 assert!(
2090 !self.workspaces.last().unwrap().has_windows(),
2091 "monitor must have an empty workspace in the end"
2092 );
2093 if self.options.layout.empty_workspace_above_first {
2094 assert!(
2095 !self.workspaces.first().unwrap().has_windows(),
2096 "first workspace must be empty when empty_workspace_above_first is set"
2097 )
2098 }
2099
2100 assert!(
2101 self.workspaces.last().unwrap().name.is_none(),
2102 "monitor must have an unnamed workspace in the end"
2103 );
2104 if self.options.layout.empty_workspace_above_first {
2105 assert!(
2106 self.workspaces.first().unwrap().name.is_none(),
2107 "first workspace must be unnamed when empty_workspace_above_first is set"
2108 )
2109 }
2110
2111 if self.options.layout.empty_workspace_above_first {
2112 assert!(
2113 self.workspaces.len() != 2,
2114 "if empty_workspace_above_first is set there must be just 1 or 3+ workspaces"
2115 )
2116 }
2117
2118 // If there's no workspace switch in progress, there can't be any non-last non-active
2119 // empty workspaces. If empty_workspace_above_first is set then the first workspace
2120 // will be empty too.
2121 let pre_skip = if self.options.layout.empty_workspace_above_first {
2122 1
2123 } else {
2124 0
2125 };
2126 if self.workspace_switch.is_none() {
2127 for (idx, ws) in self
2128 .workspaces
2129 .iter()
2130 .enumerate()
2131 .skip(pre_skip)
2132 .rev()
2133 // skip last
2134 .skip(1)
2135 {
2136 if idx != self.active_workspace_idx {
2137 assert!(
2138 ws.has_windows_or_name(),
2139 "non-active workspace can't be empty and unnamed except the last one"
2140 );
2141 }
2142 }
2143 }
2144
2145 for workspace in &self.workspaces {
2146 assert_eq!(self.clock, workspace.clock);
2147
2148 assert_eq!(
2149 self.scale().integer_scale(),
2150 workspace.scale().integer_scale()
2151 );
2152 assert_eq!(
2153 self.scale().fractional_scale(),
2154 workspace.scale().fractional_scale()
2155 );
2156 assert_eq!(self.view_size, workspace.view_size());
2157 assert_eq!(self.working_area, workspace.working_area());
2158
2159 assert_eq!(
2160 workspace.base_options, self.options,
2161 "workspace options must be synchronized with monitor"
2162 );
2163 }
2164
2165 let scale = self.scale().fractional_scale();
2166 let iter = self.workspaces_with_render_geo();
2167 for (_ws, ws_geo) in iter {
2168 let pos = ws_geo.loc;
2169 let rounded_pos = pos.to_physical_precise_round(scale).to_logical(scale);
2170
2171 // Workspace positions must be rounded to physical pixels.
2172 assert_abs_diff_eq!(pos.x, rounded_pos.x, epsilon = 1e-5);
2173 assert_abs_diff_eq!(pos.y, rounded_pos.y, epsilon = 1e-5);
2174 }
2175 }
2176}