forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBea3bbeaIvan Molodetskikh1 year ago2422 commits

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