forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB90ef202Ivan Molodetskikh1 year ago2349 commits

monitor.rs1882 lines, 64.7 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.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.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.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.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.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 true
600 }
601
602 pub fn move_down_or_to_workspace_down(&mut self) {
603 if !self.active_workspace().move_down() {
604 self.move_to_workspace_down(true);
605 }
606 }
607
608 pub fn move_up_or_to_workspace_up(&mut self) {
609 if !self.active_workspace().move_up() {
610 self.move_to_workspace_up(true);
611 }
612 }
613
614 pub fn focus_window_or_workspace_down(&mut self) {
615 if !self.active_workspace().focus_down() {
616 self.switch_workspace_down();
617 }
618 }
619
620 pub fn focus_window_or_workspace_up(&mut self) {
621 if !self.active_workspace().focus_up() {
622 self.switch_workspace_up();
623 }
624 }
625
626 pub fn move_to_workspace_up(&mut self, focus: bool) {
627 let source_workspace_idx = self.active_workspace_idx;
628
629 let new_idx = source_workspace_idx.saturating_sub(1);
630 if new_idx == source_workspace_idx {
631 return;
632 }
633 let new_id = self.workspaces[new_idx].id();
634
635 let workspace = &mut self.workspaces[source_workspace_idx];
636 let Some(removed) = workspace.remove_active_tile(Transaction::new()) else {
637 return;
638 };
639
640 let activate = if focus {
641 ActivateWindow::Yes
642 } else {
643 ActivateWindow::Smart
644 };
645
646 self.add_tile(
647 removed.tile,
648 MonitorAddWindowTarget::Workspace {
649 id: new_id,
650 column_idx: None,
651 },
652 activate,
653 true,
654 removed.width,
655 removed.is_full_width,
656 removed.is_floating,
657 );
658 }
659
660 pub fn move_to_workspace_down(&mut self, focus: bool) {
661 let source_workspace_idx = self.active_workspace_idx;
662
663 let new_idx = min(source_workspace_idx + 1, self.workspaces.len() - 1);
664 if new_idx == source_workspace_idx {
665 return;
666 }
667 let new_id = self.workspaces[new_idx].id();
668
669 let workspace = &mut self.workspaces[source_workspace_idx];
670 let Some(removed) = workspace.remove_active_tile(Transaction::new()) else {
671 return;
672 };
673
674 let activate = if focus {
675 ActivateWindow::Yes
676 } else {
677 ActivateWindow::Smart
678 };
679
680 self.add_tile(
681 removed.tile,
682 MonitorAddWindowTarget::Workspace {
683 id: new_id,
684 column_idx: None,
685 },
686 activate,
687 true,
688 removed.width,
689 removed.is_full_width,
690 removed.is_floating,
691 );
692 }
693
694 pub fn move_to_workspace(
695 &mut self,
696 window: Option<&W::Id>,
697 idx: usize,
698 activate: ActivateWindow,
699 ) {
700 let source_workspace_idx = if let Some(window) = window {
701 self.workspaces
702 .iter()
703 .position(|ws| ws.has_window(window))
704 .unwrap()
705 } else {
706 self.active_workspace_idx
707 };
708
709 let new_idx = min(idx, self.workspaces.len() - 1);
710 if new_idx == source_workspace_idx {
711 return;
712 }
713 let new_id = self.workspaces[new_idx].id();
714
715 let activate = activate.map_smart(|| {
716 window.map_or(true, |win| {
717 self.active_window().map(|win| win.id()) == Some(win)
718 })
719 });
720
721 let workspace = &mut self.workspaces[source_workspace_idx];
722 let transaction = Transaction::new();
723 let removed = if let Some(window) = window {
724 workspace.remove_tile(window, transaction)
725 } else if let Some(removed) = workspace.remove_active_tile(transaction) {
726 removed
727 } else {
728 return;
729 };
730
731 self.add_tile(
732 removed.tile,
733 MonitorAddWindowTarget::Workspace {
734 id: new_id,
735 column_idx: None,
736 },
737 if activate {
738 ActivateWindow::Yes
739 } else {
740 ActivateWindow::No
741 },
742 true,
743 removed.width,
744 removed.is_full_width,
745 removed.is_floating,
746 );
747
748 if self.workspace_switch.is_none() {
749 self.clean_up_workspaces();
750 }
751 }
752
753 pub fn move_column_to_workspace_up(&mut self, activate: bool) {
754 let source_workspace_idx = self.active_workspace_idx;
755
756 let new_idx = source_workspace_idx.saturating_sub(1);
757 if new_idx == source_workspace_idx {
758 return;
759 }
760
761 let workspace = &mut self.workspaces[source_workspace_idx];
762 if workspace.floating_is_active() {
763 self.move_to_workspace_up(activate);
764 return;
765 }
766
767 let Some(column) = workspace.remove_active_column() else {
768 return;
769 };
770
771 self.add_column(new_idx, column, activate);
772 }
773
774 pub fn move_column_to_workspace_down(&mut self, activate: bool) {
775 let source_workspace_idx = self.active_workspace_idx;
776
777 let new_idx = min(source_workspace_idx + 1, self.workspaces.len() - 1);
778 if new_idx == source_workspace_idx {
779 return;
780 }
781
782 let workspace = &mut self.workspaces[source_workspace_idx];
783 if workspace.floating_is_active() {
784 self.move_to_workspace_down(activate);
785 return;
786 }
787
788 let Some(column) = workspace.remove_active_column() else {
789 return;
790 };
791
792 self.add_column(new_idx, column, activate);
793 }
794
795 pub fn move_column_to_workspace(&mut self, idx: usize, activate: bool) {
796 let source_workspace_idx = self.active_workspace_idx;
797
798 let new_idx = min(idx, self.workspaces.len() - 1);
799 if new_idx == source_workspace_idx {
800 return;
801 }
802
803 let workspace = &mut self.workspaces[source_workspace_idx];
804 if workspace.floating_is_active() {
805 let activate = if activate {
806 ActivateWindow::Smart
807 } else {
808 ActivateWindow::No
809 };
810 self.move_to_workspace(None, idx, activate);
811 return;
812 }
813
814 let Some(column) = workspace.remove_active_column() else {
815 return;
816 };
817
818 self.add_column(new_idx, column, activate);
819 }
820
821 pub fn switch_workspace_up(&mut self) {
822 let new_idx = match &self.workspace_switch {
823 // During a DnD scroll, select the prev apparent workspace.
824 Some(WorkspaceSwitch::Gesture(gesture)) if gesture.dnd_last_event_time.is_some() => {
825 let current = gesture.current_idx;
826 let new = current.ceil() - 1.;
827 new.clamp(0., (self.workspaces.len() - 1) as f64) as usize
828 }
829 _ => self.active_workspace_idx.saturating_sub(1),
830 };
831
832 self.activate_workspace(new_idx);
833 }
834
835 pub fn switch_workspace_down(&mut self) {
836 let new_idx = match &self.workspace_switch {
837 // During a DnD scroll, select the next apparent workspace.
838 Some(WorkspaceSwitch::Gesture(gesture)) if gesture.dnd_last_event_time.is_some() => {
839 let current = gesture.current_idx;
840 let new = current.floor() + 1.;
841 new.clamp(0., (self.workspaces.len() - 1) as f64) as usize
842 }
843 _ => min(self.active_workspace_idx + 1, self.workspaces.len() - 1),
844 };
845
846 self.activate_workspace(new_idx);
847 }
848
849 fn previous_workspace_idx(&self) -> Option<usize> {
850 let id = self.previous_workspace_id?;
851 self.workspaces.iter().position(|w| w.id() == id)
852 }
853
854 pub fn switch_workspace(&mut self, idx: usize) {
855 self.activate_workspace(min(idx, self.workspaces.len() - 1));
856 }
857
858 pub fn switch_workspace_auto_back_and_forth(&mut self, idx: usize) {
859 let idx = min(idx, self.workspaces.len() - 1);
860
861 if idx == self.active_workspace_idx {
862 if let Some(prev_idx) = self.previous_workspace_idx() {
863 self.switch_workspace(prev_idx);
864 }
865 } else {
866 self.switch_workspace(idx);
867 }
868 }
869
870 pub fn switch_workspace_previous(&mut self) {
871 if let Some(idx) = self.previous_workspace_idx() {
872 self.switch_workspace(idx);
873 }
874 }
875
876 pub fn active_window(&self) -> Option<&W> {
877 self.active_workspace_ref().active_window()
878 }
879
880 pub fn advance_animations(&mut self) {
881 match &mut self.workspace_switch {
882 Some(WorkspaceSwitch::Animation(anim)) => {
883 if anim.is_done() {
884 self.workspace_switch = None;
885 self.clean_up_workspaces();
886 }
887 }
888 Some(WorkspaceSwitch::Gesture(gesture)) => {
889 // Make sure the last event time doesn't go too much out of date (for
890 // monitors not under cursor), causing sudden jumps.
891 //
892 // This happens after any dnd_scroll_gesture_scroll() calls (in
893 // Layout::advance_animations()), so it doesn't mess up the time delta there.
894 if let Some(last_time) = &mut gesture.dnd_last_event_time {
895 let now = self.clock.now_unadjusted();
896 if *last_time != now {
897 *last_time = now;
898
899 // If last_time was already == now, then dnd_scroll_gesture_scroll() must've
900 // updated the gesture already. Therefore, when this code runs, the pointer
901 // must be outside the DnD scrolling zone.
902 gesture.dnd_nonzero_start_time = None;
903 }
904 }
905
906 if let Some(anim) = &mut gesture.animation {
907 if anim.is_done() {
908 gesture.animation = None;
909 }
910 }
911 }
912 None => (),
913 }
914
915 for ws in &mut self.workspaces {
916 ws.advance_animations();
917 }
918 }
919
920 pub(super) fn are_animations_ongoing(&self) -> bool {
921 self.workspace_switch
922 .as_ref()
923 .is_some_and(|s| s.is_animation_ongoing())
924 || self.workspaces.iter().any(|ws| ws.are_animations_ongoing())
925 }
926
927 pub fn are_transitions_ongoing(&self) -> bool {
928 self.workspace_switch.is_some()
929 || self
930 .workspaces
931 .iter()
932 .any(|ws| ws.are_transitions_ongoing())
933 }
934
935 pub fn update_render_elements(&mut self, is_active: bool) {
936 let mut insert_hint_ws_geo = None;
937 let insert_hint_ws_id = self
938 .insert_hint
939 .as_ref()
940 .and_then(|hint| hint.workspace.existing_id());
941
942 for (ws, geo) in self.workspaces_with_render_geo_mut(true) {
943 ws.update_render_elements(is_active);
944
945 if Some(ws.id()) == insert_hint_ws_id {
946 insert_hint_ws_geo = Some(geo);
947 }
948 }
949
950 self.insert_hint_render_loc = None;
951 if let Some(hint) = &self.insert_hint {
952 match hint.workspace {
953 InsertWorkspace::Existing(ws_id) => {
954 if let Some(ws) = self.workspaces.iter().find(|ws| ws.id() == ws_id) {
955 if let Some(mut area) = ws.insert_hint_area(hint.position) {
956 let scale = ws.scale().fractional_scale();
957 let view_size = ws.view_size();
958
959 // Make sure the hint is at least partially visible.
960 if matches!(hint.position, InsertPosition::NewColumn(_)) {
961 let zoom = self.overview_zoom();
962 let geo = insert_hint_ws_geo.unwrap();
963 let geo = geo.downscale(zoom);
964
965 area.loc.x = area.loc.x.max(-geo.loc.x - area.size.w / 2.);
966 area.loc.x =
967 area.loc.x.min(geo.loc.x + geo.size.w - area.size.w / 2.);
968 }
969
970 // Round to physical pixels.
971 area = area.to_physical_precise_round(scale).to_logical(scale);
972
973 let view_rect = Rectangle::new(area.loc.upscale(-1.), view_size);
974 self.insert_hint_element.update_render_elements(
975 area.size,
976 view_rect,
977 hint.corner_radius,
978 scale,
979 );
980 self.insert_hint_render_loc = Some(InsertHintRenderLoc {
981 workspace: hint.workspace,
982 location: area.loc,
983 });
984 }
985 } else {
986 error!("insert hint workspace missing from monitor");
987 }
988 }
989 InsertWorkspace::NewAt(ws_idx) => {
990 let scale = self.scale.fractional_scale();
991 let zoom = self.overview_zoom();
992 let gap = self.workspace_gap(zoom);
993
994 let hint_gap = round_logical_in_physical(scale, gap * 0.1);
995 let hint_height = gap - hint_gap * 2.;
996
997 let next_ws_geo = self.workspaces_render_geo().nth(ws_idx).unwrap();
998 let hint_loc_diff = Point::from((0., hint_height + hint_gap));
999 let hint_loc = next_ws_geo.loc - hint_loc_diff;
1000 let hint_size = Size::from((next_ws_geo.size.w, hint_height));
1001
1002 // FIXME: sometimes the hint ends up 1 px wider than necessary and/or 1 px
1003 // narrower than necessary. The values here seem correct. Might have to do with
1004 // how zooming out currently doesn't round to output scale properly.
1005
1006 // Compute view rect as if we're above the next workspace (rather than below
1007 // the previous one).
1008 let view_rect = Rectangle::new(hint_loc_diff, next_ws_geo.size);
1009
1010 self.insert_hint_element.update_render_elements(
1011 hint_size,
1012 view_rect,
1013 CornerRadius::default(),
1014 scale,
1015 );
1016 self.insert_hint_render_loc = Some(InsertHintRenderLoc {
1017 workspace: hint.workspace,
1018 location: hint_loc,
1019 });
1020 }
1021 }
1022 }
1023 }
1024
1025 pub fn update_config(&mut self, options: Rc<Options>) {
1026 if self.options.empty_workspace_above_first != options.empty_workspace_above_first
1027 && self.workspaces.len() > 1
1028 {
1029 if options.empty_workspace_above_first {
1030 self.add_workspace_top();
1031 } else if self.workspace_switch.is_none() && self.active_workspace_idx != 0 {
1032 self.workspaces.remove(0);
1033 self.active_workspace_idx = self.active_workspace_idx.saturating_sub(1);
1034 }
1035 }
1036
1037 for ws in &mut self.workspaces {
1038 ws.update_config(options.clone());
1039 }
1040
1041 self.insert_hint_element.update_config(options.insert_hint);
1042
1043 self.options = options;
1044 }
1045
1046 pub fn update_shaders(&mut self) {
1047 for ws in &mut self.workspaces {
1048 ws.update_shaders();
1049 }
1050
1051 self.insert_hint_element.update_shaders();
1052 }
1053
1054 pub fn update_output_size(&mut self) {
1055 self.scale = self.output.current_scale();
1056 self.view_size = output_size(&self.output);
1057 self.working_area = compute_working_area(&self.output);
1058
1059 for ws in &mut self.workspaces {
1060 ws.update_output_size();
1061 }
1062 }
1063
1064 pub fn move_workspace_down(&mut self) {
1065 let mut new_idx = min(self.active_workspace_idx + 1, self.workspaces.len() - 1);
1066 if new_idx == self.active_workspace_idx {
1067 return;
1068 }
1069
1070 self.workspaces.swap(self.active_workspace_idx, new_idx);
1071
1072 if new_idx == self.workspaces.len() - 1 {
1073 // Insert a new empty workspace.
1074 self.add_workspace_bottom();
1075 }
1076
1077 if self.options.empty_workspace_above_first && self.active_workspace_idx == 0 {
1078 self.add_workspace_top();
1079 new_idx += 1;
1080 }
1081
1082 let previous_workspace_id = self.previous_workspace_id;
1083 self.activate_workspace(new_idx);
1084 self.workspace_switch = None;
1085 self.previous_workspace_id = previous_workspace_id;
1086
1087 self.clean_up_workspaces();
1088 }
1089
1090 pub fn move_workspace_up(&mut self) {
1091 let mut new_idx = self.active_workspace_idx.saturating_sub(1);
1092 if new_idx == self.active_workspace_idx {
1093 return;
1094 }
1095
1096 self.workspaces.swap(self.active_workspace_idx, new_idx);
1097
1098 if self.active_workspace_idx == self.workspaces.len() - 1 {
1099 // Insert a new empty workspace.
1100 self.add_workspace_bottom();
1101 }
1102
1103 if self.options.empty_workspace_above_first && new_idx == 0 {
1104 self.add_workspace_top();
1105 new_idx += 1;
1106 }
1107
1108 let previous_workspace_id = self.previous_workspace_id;
1109 self.activate_workspace(new_idx);
1110 self.workspace_switch = None;
1111 self.previous_workspace_id = previous_workspace_id;
1112
1113 self.clean_up_workspaces();
1114 }
1115
1116 pub fn move_workspace_to_idx(&mut self, old_idx: usize, new_idx: usize) {
1117 if self.workspaces.len() <= old_idx {
1118 return;
1119 }
1120
1121 let mut new_idx = new_idx.clamp(0, self.workspaces.len() - 1);
1122 if old_idx == new_idx {
1123 return;
1124 }
1125
1126 let ws = self.workspaces.remove(old_idx);
1127 self.workspaces.insert(new_idx, ws);
1128
1129 if new_idx > old_idx {
1130 if new_idx == self.workspaces.len() - 1 {
1131 // Insert a new empty workspace.
1132 self.add_workspace_bottom();
1133 }
1134
1135 if self.options.empty_workspace_above_first && old_idx == 0 {
1136 self.add_workspace_top();
1137 new_idx += 1;
1138 }
1139 } else {
1140 if old_idx == self.workspaces.len() - 1 {
1141 // Insert a new empty workspace.
1142 self.add_workspace_bottom();
1143 }
1144
1145 if self.options.empty_workspace_above_first && new_idx == 0 {
1146 self.add_workspace_top();
1147 new_idx += 1;
1148 }
1149 }
1150
1151 // Only refocus the workspace if it was already focused
1152 if self.active_workspace_idx == old_idx {
1153 self.active_workspace_idx = new_idx;
1154 // If the workspace order was switched so that the current workspace moved down the
1155 // workspace stack, focus correctly
1156 } else if new_idx <= self.active_workspace_idx && old_idx > self.active_workspace_idx {
1157 self.active_workspace_idx += 1;
1158 } else if new_idx >= self.active_workspace_idx && old_idx < self.active_workspace_idx {
1159 self.active_workspace_idx = self.active_workspace_idx.saturating_sub(1);
1160 }
1161
1162 self.workspace_switch = None;
1163
1164 self.clean_up_workspaces();
1165 }
1166
1167 /// Returns the geometry of the active tile relative to and clamped to the output.
1168 ///
1169 /// During animations, assumes the final view position.
1170 pub fn active_tile_visual_rectangle(&self) -> Option<Rectangle<f64, Logical>> {
1171 if self.overview_open {
1172 return None;
1173 }
1174
1175 self.active_workspace_ref().active_tile_visual_rectangle()
1176 }
1177
1178 fn workspace_size(&self, zoom: f64) -> Size<f64, Logical> {
1179 let ws_size = self.view_size.upscale(zoom);
1180 let scale = self.scale.fractional_scale();
1181 ws_size.to_physical_precise_ceil(scale).to_logical(scale)
1182 }
1183
1184 fn workspace_gap(&self, zoom: f64) -> f64 {
1185 let scale = self.scale.fractional_scale();
1186 let gap = self.view_size.h * 0.1 * zoom;
1187 round_logical_in_physical_max1(scale, gap)
1188 }
1189
1190 fn workspace_size_with_gap(&self, zoom: f64) -> Size<f64, Logical> {
1191 let gap = self.workspace_gap(zoom);
1192 self.workspace_size(zoom) + Size::from((0., gap))
1193 }
1194
1195 pub fn overview_zoom(&self) -> f64 {
1196 let progress = self.overview_progress.as_ref().map(|p| p.value());
1197 compute_overview_zoom(&self.options, progress)
1198 }
1199
1200 pub(super) fn set_overview_progress(&mut self, progress: Option<&super::OverviewProgress>) {
1201 let prev_render_idx = self.workspace_render_idx();
1202 self.overview_progress = progress.map(OverviewProgress::from);
1203 let new_render_idx = self.workspace_render_idx();
1204
1205 // If the view jumped (can happen when going from corrected to uncorrected render_idx, for
1206 // example when toggling the overview in the middle of an overview animation), then restart
1207 // the workspace switch to avoid jumps.
1208 if prev_render_idx != new_render_idx {
1209 if let Some(WorkspaceSwitch::Animation(anim)) = &mut self.workspace_switch {
1210 // FIXME: maintain velocity.
1211 *anim = anim.restarted(prev_render_idx, anim.to(), 0.);
1212 }
1213 }
1214 }
1215
1216 #[cfg(test)]
1217 pub(super) fn overview_progress_value(&self) -> Option<f64> {
1218 self.overview_progress.as_ref().map(|p| p.value())
1219 }
1220
1221 pub fn workspace_render_idx(&self) -> f64 {
1222 // If workspace switch and overview progress are matching animations, then compute a
1223 // correction term to make the movement appear monotonic.
1224 if let (
1225 Some(WorkspaceSwitch::Animation(switch_anim)),
1226 Some(OverviewProgress::Animation(progress_anim)),
1227 ) = (&self.workspace_switch, &self.overview_progress)
1228 {
1229 if switch_anim.start_time() == progress_anim.start_time()
1230 && (switch_anim.duration().as_secs_f64() - progress_anim.duration().as_secs_f64())
1231 .abs()
1232 <= 0.001
1233 {
1234 #[rustfmt::skip]
1235 // How this was derived:
1236 //
1237 // - Assume we're animating a zoom + switch. Consider switch "from" and "to".
1238 // These are render_idx values, so first workspace to second would have switch
1239 // from = 0. and to = 1. regardless of the zoom level.
1240 //
1241 // - At the start, the point at "from" is at Y = 0. We're moving the point at "to"
1242 // to Y = 0. We want this to be a monotonic motion in apparent coordinates (after
1243 // zoom).
1244 //
1245 // - Height at the start:
1246 // from_height = (size.h + gap) * from_zoom.
1247 //
1248 // - Current height:
1249 // current_height = (size.h + gap) * zoom.
1250 //
1251 // - We're moving the "to" point to Y = 0:
1252 // to_y = 0.
1253 //
1254 // - The initial position of the point we're moving:
1255 // from_y = (to - from) * from_height.
1256 //
1257 // - We want this point to travel monotonically in apparent coordinates:
1258 // current_y = from_y + (to_y - from_y) * progress,
1259 // where progress is from 0 to 1, equals to the animation progress (switch and
1260 // zoom are the same since they are synchronized).
1261 //
1262 // - Derive the Y of the first workspace from this:
1263 // first_y = current_y - to * current_height.
1264 //
1265 // Now, let's substitute and rearrange the terms.
1266 //
1267 // - current_y = from_y + (0 - (to - from) * from_height) * progress
1268 // - progress = (switch_anim.value() - from) / (to - from)
1269 // - current_y = from_y - (to - from) * from_height * (switch_anim.value() - from) / (to - from)
1270 // - current_y = from_y - from_height * (switch_anim.value() - from)
1271 // - first_y = from_y - from_height * (switch_anim.value() - from) - to * current_height
1272 // - first_y = (to - from) * from_height - from_height * (switch_anim.value() - from) - to * current_height
1273 // - first_y = to * from_height - switch_anim.value() * from_height - to * current_height
1274 // - first_y = -switch_anim.value() * from_height + to * (from_height - current_height)
1275 let from = progress_anim.from();
1276 let from_zoom = compute_overview_zoom(&self.options, Some(from));
1277 let from_ws_height_with_gap = self.workspace_size_with_gap(from_zoom).h;
1278
1279 let zoom = self.overview_zoom();
1280 let ws_height_with_gap = self.workspace_size_with_gap(zoom).h;
1281
1282 let first_ws_y = -switch_anim.value() * from_ws_height_with_gap
1283 + switch_anim.to() * (from_ws_height_with_gap - ws_height_with_gap);
1284
1285 return -first_ws_y / ws_height_with_gap;
1286 }
1287 };
1288
1289 if let Some(switch) = &self.workspace_switch {
1290 switch.current_idx()
1291 } else {
1292 self.active_workspace_idx as f64
1293 }
1294 }
1295
1296 pub fn workspaces_render_geo(&self) -> impl Iterator<Item = Rectangle<f64, Logical>> {
1297 let scale = self.scale.fractional_scale();
1298 let zoom = self.overview_zoom();
1299
1300 let ws_size = self.workspace_size(zoom);
1301 let gap = self.workspace_gap(zoom);
1302 let ws_height_with_gap = ws_size.h + gap;
1303
1304 let static_offset = (self.view_size.to_point() - ws_size.to_point()).downscale(2.);
1305 let static_offset = static_offset
1306 .to_physical_precise_round(scale)
1307 .to_logical(scale);
1308
1309 let first_ws_y = -self.workspace_render_idx() * ws_height_with_gap;
1310 let first_ws_y = round_logical_in_physical(scale, first_ws_y);
1311
1312 // Return position for one-past-last workspace too.
1313 (0..=self.workspaces.len()).map(move |idx| {
1314 let y = first_ws_y + idx as f64 * ws_height_with_gap;
1315 let loc = Point::from((0., y)) + static_offset;
1316 Rectangle::new(loc, ws_size)
1317 })
1318 }
1319
1320 pub fn workspaces_with_render_geo(
1321 &self,
1322 ) -> impl Iterator<Item = (&Workspace<W>, Rectangle<f64, Logical>)> {
1323 let output_geo = Rectangle::from_size(self.view_size);
1324
1325 let geo = self.workspaces_render_geo();
1326 zip(self.workspaces.iter(), geo)
1327 // Cull out workspaces outside the output.
1328 .filter(move |(_ws, geo)| geo.intersection(output_geo).is_some())
1329 }
1330
1331 pub fn workspaces_with_render_geo_idx(
1332 &self,
1333 ) -> impl Iterator<Item = ((usize, &Workspace<W>), Rectangle<f64, Logical>)> {
1334 let output_geo = Rectangle::from_size(self.view_size);
1335
1336 let geo = self.workspaces_render_geo();
1337 zip(self.workspaces.iter().enumerate(), geo)
1338 // Cull out workspaces outside the output.
1339 .filter(move |(_ws, geo)| geo.intersection(output_geo).is_some())
1340 }
1341
1342 pub fn workspaces_with_render_geo_mut(
1343 &mut self,
1344 cull: bool,
1345 ) -> impl Iterator<Item = (&mut Workspace<W>, Rectangle<f64, Logical>)> {
1346 let output_geo = Rectangle::from_size(self.view_size);
1347
1348 let geo = self.workspaces_render_geo();
1349 zip(self.workspaces.iter_mut(), geo)
1350 // Cull out workspaces outside the output.
1351 .filter(move |(_ws, geo)| !cull || geo.intersection(output_geo).is_some())
1352 }
1353
1354 pub fn workspace_under(
1355 &self,
1356 pos_within_output: Point<f64, Logical>,
1357 ) -> Option<(&Workspace<W>, Rectangle<f64, Logical>)> {
1358 let (ws, geo) = self.workspaces_with_render_geo().find_map(|(ws, geo)| {
1359 // Extend width to entire output.
1360 let loc = Point::from((0., geo.loc.y));
1361 let size = Size::from((self.view_size.w, geo.size.h));
1362 let bounds = Rectangle::new(loc, size);
1363
1364 bounds.contains(pos_within_output).then_some((ws, geo))
1365 })?;
1366 Some((ws, geo))
1367 }
1368
1369 pub fn workspace_under_narrow(
1370 &self,
1371 pos_within_output: Point<f64, Logical>,
1372 ) -> Option<&Workspace<W>> {
1373 self.workspaces_with_render_geo()
1374 .find_map(|(ws, geo)| geo.contains(pos_within_output).then_some(ws))
1375 }
1376
1377 pub fn window_under(&self, pos_within_output: Point<f64, Logical>) -> Option<(&W, HitType)> {
1378 let (ws, geo) = self.workspace_under(pos_within_output)?;
1379
1380 if self.overview_progress.is_some() {
1381 let zoom = self.overview_zoom();
1382 let pos_within_workspace = (pos_within_output - geo.loc).downscale(zoom);
1383 let (win, hit) = ws.window_under(pos_within_workspace)?;
1384 // During the overview animation, we cannot do input hits because we cannot really
1385 // represent scaled windows properly.
1386 Some((win, hit.to_activate()))
1387 } else {
1388 let (win, hit) = ws.window_under(pos_within_output - geo.loc)?;
1389 Some((win, hit.offset_win_pos(geo.loc)))
1390 }
1391 }
1392
1393 pub fn resize_edges_under(&self, pos_within_output: Point<f64, Logical>) -> Option<ResizeEdge> {
1394 if self.overview_progress.is_some() {
1395 return None;
1396 }
1397
1398 let (ws, geo) = self.workspace_under(pos_within_output)?;
1399 ws.resize_edges_under(pos_within_output - geo.loc)
1400 }
1401
1402 pub(super) fn insert_position(
1403 &self,
1404 pos_within_output: Point<f64, Logical>,
1405 ) -> (InsertWorkspace, Rectangle<f64, Logical>) {
1406 let mut iter = self.workspaces_with_render_geo_idx();
1407
1408 let dummy = Rectangle::default();
1409
1410 // Monitors always have at least one workspace.
1411 let ((idx, ws), geo) = iter.next().unwrap();
1412
1413 // Check if above first.
1414 if pos_within_output.y < geo.loc.y {
1415 return (InsertWorkspace::NewAt(idx), dummy);
1416 }
1417
1418 let contains = move |geo: Rectangle<f64, Logical>| {
1419 geo.loc.y <= pos_within_output.y && pos_within_output.y < geo.loc.y + geo.size.h
1420 };
1421
1422 // Check first.
1423 if contains(geo) {
1424 return (InsertWorkspace::Existing(ws.id()), geo);
1425 }
1426
1427 let mut last_geo = geo;
1428 let mut last_idx = idx;
1429 for ((idx, ws), geo) in iter {
1430 // Check gap above.
1431 let gap_loc = Point::from((last_geo.loc.x, last_geo.loc.y + last_geo.size.h));
1432 let gap_size = Size::from((geo.size.w, geo.loc.y - gap_loc.y));
1433 let gap_geo = Rectangle::new(gap_loc, gap_size);
1434 if contains(gap_geo) {
1435 return (InsertWorkspace::NewAt(idx), dummy);
1436 }
1437
1438 // Check workspace itself.
1439 if contains(geo) {
1440 return (InsertWorkspace::Existing(ws.id()), geo);
1441 }
1442
1443 last_geo = geo;
1444 last_idx = idx;
1445 }
1446
1447 // Anything below.
1448 (InsertWorkspace::NewAt(last_idx + 1), dummy)
1449 }
1450
1451 pub fn render_above_top_layer(&self) -> bool {
1452 // Render above the top layer only if the view is stationary.
1453 if self.workspace_switch.is_some() || self.overview_progress.is_some() {
1454 return false;
1455 }
1456
1457 let ws = &self.workspaces[self.active_workspace_idx];
1458 ws.render_above_top_layer()
1459 }
1460
1461 pub fn render_insert_hint_between_workspaces<R: NiriRenderer>(
1462 &self,
1463 renderer: &mut R,
1464 ) -> impl Iterator<Item = MonitorRenderElement<R>> {
1465 let mut rv = None;
1466
1467 if !self.options.insert_hint.off {
1468 if let Some(render_loc) = self.insert_hint_render_loc {
1469 if let InsertWorkspace::NewAt(_) = render_loc.workspace {
1470 let iter = self
1471 .insert_hint_element
1472 .render(renderer, render_loc.location)
1473 .map(MonitorInnerRenderElement::UncroppedInsertHint);
1474 rv = Some(iter);
1475 }
1476 }
1477 }
1478
1479 rv.into_iter().flatten().map(|elem| {
1480 let elem = RescaleRenderElement::from_element(elem, Point::default(), 1.);
1481 RelocateRenderElement::from_element(elem, Point::default(), Relocate::Relative)
1482 })
1483 }
1484
1485 pub fn render_elements<'a, R: NiriRenderer>(
1486 &'a self,
1487 renderer: &'a mut R,
1488 target: RenderTarget,
1489 focus_ring: bool,
1490 ) -> impl Iterator<
1491 Item = (
1492 Rectangle<f64, Logical>,
1493 impl Iterator<Item = MonitorRenderElement<R>> + 'a,
1494 ),
1495 > {
1496 let _span = tracy_client::span!("Monitor::render_elements");
1497
1498 let scale = self.scale.fractional_scale();
1499 // Ceil the height in physical pixels.
1500 let height = (self.view_size.h * scale).ceil() as i32;
1501
1502 // Crop the elements to prevent them overflowing, currently visible during a workspace
1503 // switch.
1504 //
1505 // HACK: crop to infinite bounds at least horizontally where we
1506 // know there's no workspace joining or monitor bounds, otherwise
1507 // it will cut pixel shaders and mess up the coordinate space.
1508 // There's also a damage tracking bug which causes glitched
1509 // rendering for maximized GTK windows.
1510 //
1511 // FIXME: use proper bounds after fixing the Crop element.
1512 let crop_bounds = if self.workspace_switch.is_some() || self.overview_progress.is_some() {
1513 Rectangle::new(
1514 Point::from((-i32::MAX / 2, 0)),
1515 Size::from((i32::MAX, height)),
1516 )
1517 } else {
1518 Rectangle::new(
1519 Point::from((-i32::MAX / 2, -i32::MAX / 2)),
1520 Size::from((i32::MAX, i32::MAX)),
1521 )
1522 };
1523
1524 let zoom = self.overview_zoom();
1525
1526 // Draw the insert hint.
1527 let mut insert_hint = None;
1528 if !self.options.insert_hint.off {
1529 if let Some(render_loc) = self.insert_hint_render_loc {
1530 if let InsertWorkspace::Existing(workspace_id) = render_loc.workspace {
1531 insert_hint = Some((
1532 workspace_id,
1533 self.insert_hint_element
1534 .render(renderer, render_loc.location),
1535 ));
1536 }
1537 }
1538 }
1539
1540 self.workspaces_with_render_geo().map(move |(ws, geo)| {
1541 let map_ws_contents = move |elem: WorkspaceRenderElement<R>| {
1542 let elem = CropRenderElement::from_element(elem, scale, crop_bounds)?;
1543 let elem = MonitorInnerRenderElement::Workspace(elem);
1544 Some(elem)
1545 };
1546
1547 let (floating, scrolling) = ws.render_elements(renderer, target, focus_ring);
1548 let floating = floating.filter_map(map_ws_contents);
1549 let scrolling = scrolling.filter_map(map_ws_contents);
1550
1551 let hint = if matches!(insert_hint, Some((hint_ws_id, _)) if hint_ws_id == ws.id()) {
1552 let iter = insert_hint.take().unwrap().1;
1553 let iter = iter.filter_map(move |elem| {
1554 let elem = CropRenderElement::from_element(elem, scale, crop_bounds)?;
1555 let elem = MonitorInnerRenderElement::InsertHint(elem);
1556 Some(elem)
1557 });
1558 Some(iter)
1559 } else {
1560 None
1561 };
1562 let hint = hint.into_iter().flatten();
1563
1564 let iter = floating.chain(hint).chain(scrolling);
1565
1566 let iter = iter.map(move |elem| {
1567 let elem = RescaleRenderElement::from_element(elem, Point::from((0, 0)), zoom);
1568 RelocateRenderElement::from_element(
1569 elem,
1570 // The offset we get from workspaces_with_render_positions() is already
1571 // rounded to physical pixels, but it's in the logical coordinate
1572 // space, so we need to convert it to physical.
1573 geo.loc.to_physical_precise_round(scale),
1574 Relocate::Relative,
1575 )
1576 });
1577
1578 (geo, iter)
1579 })
1580 }
1581
1582 pub fn render_workspace_shadows<'a, R: NiriRenderer>(
1583 &'a self,
1584 renderer: &'a mut R,
1585 ) -> impl Iterator<Item = MonitorRenderElement<R>> + 'a {
1586 let _span = tracy_client::span!("Monitor::render_workspace_shadows");
1587
1588 let scale = self.scale.fractional_scale();
1589 let zoom = self.overview_zoom();
1590 let overview_clamped_progress = self.overview_progress.as_ref().map(|p| p.clamped_value());
1591
1592 self.workspaces_with_render_geo()
1593 .flat_map(move |(ws, geo)| {
1594 let shadow = overview_clamped_progress.map(|value| {
1595 ws.render_shadow(renderer)
1596 .map(move |elem| elem.with_alpha(value.clamp(0., 1.) as f32))
1597 .map(MonitorInnerRenderElement::Shadow)
1598 });
1599 let iter = shadow.into_iter().flatten();
1600
1601 iter.map(move |elem| {
1602 let elem = RescaleRenderElement::from_element(elem, Point::from((0, 0)), zoom);
1603 RelocateRenderElement::from_element(
1604 elem,
1605 geo.loc.to_physical_precise_round(scale),
1606 Relocate::Relative,
1607 )
1608 })
1609 })
1610 }
1611
1612 pub fn workspace_switch_gesture_begin(&mut self, is_touchpad: bool) {
1613 let center_idx = self.active_workspace_idx;
1614 let current_idx = self.workspace_render_idx();
1615
1616 let gesture = WorkspaceSwitchGesture {
1617 center_idx,
1618 start_idx: current_idx,
1619 current_idx,
1620 animation: None,
1621 tracker: SwipeTracker::new(),
1622 is_touchpad,
1623 is_clamped: !self.overview_open,
1624 dnd_last_event_time: None,
1625 dnd_nonzero_start_time: None,
1626 };
1627 self.workspace_switch = Some(WorkspaceSwitch::Gesture(gesture));
1628 }
1629
1630 pub fn dnd_scroll_gesture_begin(&mut self) {
1631 if let Some(WorkspaceSwitch::Gesture(WorkspaceSwitchGesture {
1632 dnd_last_event_time: Some(_),
1633 ..
1634 })) = &self.workspace_switch
1635 {
1636 // Already active.
1637 return;
1638 }
1639
1640 if !self.overview_open {
1641 // This gesture is only for the overview.
1642 return;
1643 }
1644
1645 let center_idx = self.active_workspace_idx;
1646 let current_idx = self.workspace_render_idx();
1647
1648 let gesture = WorkspaceSwitchGesture {
1649 center_idx,
1650 start_idx: current_idx,
1651 current_idx,
1652 animation: None,
1653 tracker: SwipeTracker::new(),
1654 is_touchpad: false,
1655 is_clamped: false,
1656 dnd_last_event_time: Some(self.clock.now_unadjusted()),
1657 dnd_nonzero_start_time: None,
1658 };
1659 self.workspace_switch = Some(WorkspaceSwitch::Gesture(gesture));
1660 }
1661
1662 pub fn workspace_switch_gesture_update(
1663 &mut self,
1664 delta_y: f64,
1665 timestamp: Duration,
1666 is_touchpad: bool,
1667 ) -> Option<bool> {
1668 let Some(WorkspaceSwitch::Gesture(gesture)) = &self.workspace_switch else {
1669 return None;
1670 };
1671
1672 if gesture.is_touchpad != is_touchpad || gesture.dnd_last_event_time.is_some() {
1673 return None;
1674 }
1675
1676 let zoom = self.overview_zoom();
1677 let total_height = if gesture.is_touchpad {
1678 WORKSPACE_GESTURE_MOVEMENT
1679 } else {
1680 self.workspace_size_with_gap(1.).h
1681 };
1682
1683 let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
1684 return None;
1685 };
1686
1687 // Reduce the effect of zoom on the touchpad somewhat.
1688 let delta_scale = if gesture.is_touchpad {
1689 (zoom - 1.) / 2.5 + 1.
1690 } else {
1691 zoom
1692 };
1693
1694 let delta_y = delta_y / delta_scale;
1695 let mut rubber_band = WORKSPACE_GESTURE_RUBBER_BAND;
1696 rubber_band.limit /= zoom;
1697
1698 gesture.tracker.push(delta_y, timestamp);
1699
1700 let pos = gesture.tracker.pos() / total_height;
1701
1702 let (min, max) = gesture.min_max(self.workspaces.len());
1703 let new_idx = gesture.start_idx + pos;
1704 let new_idx = rubber_band.clamp(min, max, new_idx);
1705
1706 if gesture.current_idx == new_idx {
1707 return Some(false);
1708 }
1709
1710 gesture.current_idx = new_idx;
1711 Some(true)
1712 }
1713
1714 pub fn dnd_scroll_gesture_scroll(&mut self, pos: Point<f64, Logical>, speed: f64) -> bool {
1715 let zoom = self.overview_zoom();
1716
1717 let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
1718 return false;
1719 };
1720
1721 let Some(last_time) = gesture.dnd_last_event_time else {
1722 // Not a DnD scroll.
1723 return false;
1724 };
1725
1726 let config = &self.options.gestures.dnd_edge_workspace_switch;
1727 let trigger_height = config.trigger_height.0;
1728
1729 // Restrict the scrolling horizontally to the strip of workspaces to avoid unwanted trigger
1730 // after using the hot corner or during horizontal scroll.
1731 let width = self.view_size.w * zoom;
1732 let x = pos.x - (self.view_size.w - width) / 2.;
1733
1734 // Consider the working area so layer-shell docks and such don't prevent scrolling.
1735 let y = pos.y - self.working_area.loc.y;
1736 let height = self.working_area.size.h;
1737
1738 let y = y.clamp(0., height);
1739 let trigger_height = trigger_height.clamp(0., height / 2.);
1740
1741 let delta = if x < 0. || width <= x {
1742 // Outside the bounds horizontally.
1743 0.
1744 } else if y < trigger_height {
1745 -(trigger_height - y)
1746 } else if height - y < trigger_height {
1747 trigger_height - (height - y)
1748 } else {
1749 0.
1750 };
1751
1752 let delta = if trigger_height < 0.01 {
1753 // Sanity check for trigger-height 0 or small window sizes.
1754 0.
1755 } else {
1756 // Normalize to [0, 1].
1757 delta / trigger_height
1758 };
1759 let delta = delta * speed;
1760
1761 let now = self.clock.now_unadjusted();
1762 gesture.dnd_last_event_time = Some(now);
1763
1764 if delta == 0. {
1765 // We're outside the scrolling zone.
1766 gesture.dnd_nonzero_start_time = None;
1767 return false;
1768 }
1769
1770 let nonzero_start = *gesture.dnd_nonzero_start_time.get_or_insert(now);
1771
1772 // Delay starting the gesture a bit to avoid unwanted movement when dragging across
1773 // monitors.
1774 let delay = Duration::from_millis(u64::from(config.delay_ms));
1775 if now.saturating_sub(nonzero_start) < delay {
1776 return true;
1777 }
1778
1779 let time_delta = now.saturating_sub(last_time).as_secs_f64();
1780
1781 let delta = delta * time_delta * config.max_speed.0;
1782
1783 gesture.tracker.push(delta, now);
1784
1785 let total_height = WORKSPACE_DND_EDGE_SCROLL_MOVEMENT;
1786 let pos = gesture.tracker.pos() / total_height;
1787 let unclamped = gesture.start_idx + pos;
1788
1789 let (min, max) = gesture.min_max(self.workspaces.len());
1790 let clamped = unclamped.clamp(min, max);
1791
1792 // Make sure that DnD scrolling too much outside the min/max does not "build up".
1793 gesture.start_idx += clamped - unclamped;
1794 gesture.current_idx = clamped;
1795
1796 true
1797 }
1798
1799 pub fn workspace_switch_gesture_end(&mut self, is_touchpad: Option<bool>) -> bool {
1800 let Some(WorkspaceSwitch::Gesture(gesture)) = &self.workspace_switch else {
1801 return false;
1802 };
1803
1804 if is_touchpad.is_some_and(|x| gesture.is_touchpad != x) {
1805 return false;
1806 }
1807
1808 let zoom = self.overview_zoom();
1809 let total_height = if gesture.dnd_last_event_time.is_some() {
1810 WORKSPACE_DND_EDGE_SCROLL_MOVEMENT
1811 } else if gesture.is_touchpad {
1812 WORKSPACE_GESTURE_MOVEMENT
1813 } else {
1814 self.workspace_size_with_gap(1.).h
1815 };
1816
1817 let Some(WorkspaceSwitch::Gesture(gesture)) = &mut self.workspace_switch else {
1818 return false;
1819 };
1820
1821 // Take into account any idle time between the last event and now.
1822 let now = self.clock.now_unadjusted();
1823 gesture.tracker.push(0., now);
1824
1825 let mut rubber_band = WORKSPACE_GESTURE_RUBBER_BAND;
1826 rubber_band.limit /= zoom;
1827
1828 let mut velocity = gesture.tracker.velocity() / total_height;
1829 let current_pos = gesture.tracker.pos() / total_height;
1830 let pos = gesture.tracker.projected_end_pos() / total_height;
1831
1832 let (min, max) = gesture.min_max(self.workspaces.len());
1833 let new_idx = gesture.start_idx + pos;
1834
1835 let new_idx = new_idx.clamp(min, max);
1836 let new_idx = new_idx.round() as usize;
1837
1838 velocity *= rubber_band.clamp_derivative(min, max, gesture.start_idx + current_pos);
1839
1840 if self.active_workspace_idx != new_idx {
1841 self.previous_workspace_id = Some(self.workspaces[self.active_workspace_idx].id());
1842 }
1843
1844 self.active_workspace_idx = new_idx;
1845 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
1846 self.clock.clone(),
1847 gesture.current_idx,
1848 new_idx as f64,
1849 velocity,
1850 self.options.animations.workspace_switch.0,
1851 )));
1852
1853 true
1854 }
1855
1856 pub fn dnd_scroll_gesture_end(&mut self) {
1857 if !matches!(
1858 self.workspace_switch,
1859 Some(WorkspaceSwitch::Gesture(WorkspaceSwitchGesture {
1860 dnd_last_event_time: Some(_),
1861 ..
1862 }))
1863 ) {
1864 // Not a DnD scroll.
1865 return;
1866 };
1867
1868 self.workspace_switch_gesture_end(None);
1869 }
1870
1871 pub fn scale(&self) -> smithay::output::Scale {
1872 self.scale
1873 }
1874
1875 pub fn view_size(&self) -> Size<f64, Logical> {
1876 self.view_size
1877 }
1878
1879 pub fn working_area(&self) -> Rectangle<f64, Logical> {
1880 self.working_area
1881 }
1882}