paneru 0.4.2

A sliding, tiling window manager for MacOS.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
use bevy::app::{App, Plugin, PreUpdate, Update};
use bevy::ecs::component::Component;
use bevy::ecs::entity::Entity;
use bevy::ecs::hierarchy::ChildOf;
use bevy::ecs::lifecycle::Add;
use bevy::ecs::message::MessageReader;
use bevy::ecs::observer::On;
use bevy::ecs::query::{Added, Has, With, Without};
use bevy::ecs::schedule::IntoScheduleConfigs as _;
use bevy::ecs::schedule::common_conditions::{not, resource_exists};
use bevy::ecs::system::{Commands, Local, Populated, Query, Res, Single};
use bevy::time::common_conditions::on_timer;
use std::collections::HashSet;
use std::time::Duration;
use tracing::{Level, debug, error, instrument, warn};

use super::{ActiveDisplayMarker, SpawnWindowTrigger, WMEventTrigger};
use crate::commands::{Direction, MoveFocus, Operation, filter_window_operations};
use crate::ecs::layout::LayoutStrip;
use crate::ecs::params::{ActiveDisplay, Windows};
use crate::ecs::{
    ActiveWorkspaceMarker, Bounds, Initializing, NativeFullscreenMarker, Position,
    RefreshWindowSizes, SelectedVirtualMarker, Timeout, Unmanaged, flash_message, focus_entity,
    reposition_entity, reshuffle_around,
};
use crate::errors::Result;
use crate::events::Event;
use crate::manager::{Application, Display, Origin, Window, WindowManager};
use crate::platform::{WinID, WorkspaceId};

pub struct WorkspaceEventsPlugin;

impl Plugin for WorkspaceEventsPlugin {
    fn build(&self, app: &mut App) {
        const REFRESH_WINDOW_CHECK_FREQ_MS: u64 = 1000;
        const DISPLAY_CHANGE_CHECK_FREQ_MS: u64 = 1000;

        app.add_systems(
            PreUpdate,
            (switch_virtual_workspace_bind, move_virtual_workspace_bind),
        );
        app.add_systems(
            Update,
            (
                show_active_workspace,
                handle_virtual_window_moves,
                detect_moved_windows.run_if(not(resource_exists::<Initializing>)),
                refresh_workspace_window_sizes.run_if(on_timer(Duration::from_millis(
                    REFRESH_WINDOW_CHECK_FREQ_MS,
                ))),
                find_orphaned_workspaces
                    .after(crate::ecs::display::displays_rearranged)
                    .run_if(on_timer(Duration::from_millis(
                        DISPLAY_CHANGE_CHECK_FREQ_MS,
                    ))),
            ),
        );

        app.add_observer(cleanup_active_workspace_marker)
            .add_observer(cleanup_selected_space_marker)
            .add_observer(workspace_change_trigger)
            .add_observer(workspace_created_trigger)
            .add_observer(workspace_destroyed_trigger);
    }
}

/// Marker component to move a window to a specific virtual index on its current workspace.
#[derive(Component)]
struct VirtualMoveMarker {
    pub target_virtual_index: u32,
    pub move_focus: MoveFocus,
}

#[derive(Component, Debug)]
pub(crate) struct PreviousStripPosition {
    pub origin: Origin,
    pub focus: Option<Entity>,
}

#[allow(clippy::needless_pass_by_value)]
#[instrument(level = Level::DEBUG, skip_all, fields(trigger))]
fn workspace_change_trigger(
    trigger: On<WMEventTrigger>,
    windows: Windows,
    mut workspaces: Query<(
        &mut LayoutStrip,
        Entity,
        Has<ActiveWorkspaceMarker>,
        Has<SelectedVirtualMarker>,
    )>,
    active_display: Single<(&Display, Entity), With<ActiveDisplayMarker>>,
    window_manager: Res<WindowManager>,
    mut commands: Commands,
) {
    let Event::SpaceChanged = trigger.event().0 else {
        return;
    };
    let (active_display, display_entity) = *active_display;

    let Ok(workspace_id) = window_manager.active_display_space(active_display.id()) else {
        error!("Unable to get active workspace id!");
        return;
    };

    let mut remove_from = None;
    let mut insert_into = None;
    for (strip, entity, active, selected) in &workspaces {
        if active && strip.id() == workspace_id {
            debug!("Workspace id {} already active", strip.id());
            return;
        }
        if active && strip.id() != workspace_id {
            debug!("Workspace id {} no longer active", strip.id());
            remove_from = Some(entity);
        }
        if !active && strip.id() == workspace_id && selected {
            debug!("Workspace id {} is active", strip.id());
            insert_into = Some(entity);
        }
    }

    if insert_into.is_none() {
        // Fallback: find any strip for this workspace, preferably the one with virtual_index 0.
        insert_into = workspaces
            .iter()
            .filter(|(strip, _, _, _)| strip.id() == workspace_id)
            .min_by_key(|(strip, _, _, _)| strip.virtual_index)
            .map(|(_, entity, _, _)| entity);
    }

    if insert_into.is_none()
        && let Some(old_space) = remove_from
        && window_manager.is_fullscreen_space(active_display.id())
        && let Some((_, focused)) = windows.focused()
        && let Ok((mut old_strip, _, _, _)) = workspaces.get_mut(old_space)
    {
        debug!("workspace_change: space={workspace_id} fullscreen");

        let fullscreen_marker = NativeFullscreenMarker {
            previous_strip: old_strip.id(),
            previous_index: old_strip.index_of(focused).unwrap_or(0),
        };
        old_strip.remove(focused);

        let fullscreen_strip = LayoutStrip::fullscreen(workspace_id, focused);
        let entity = commands
            .spawn((
                Position(active_display.bounds().min),
                fullscreen_marker,
                fullscreen_strip,
                ChildOf(display_entity),
            ))
            .id();
        insert_into = Some(entity);
    }

    if let Some(into) = insert_into
        && let Ok(mut entity_commands) = commands.get_entity(into)
    {
        entity_commands
            .try_insert(ActiveWorkspaceMarker)
            .try_insert(SelectedVirtualMarker);
    }
}

#[allow(clippy::needless_pass_by_value)]
#[instrument(level = Level::DEBUG, skip_all, fields(trigger))]
fn detect_moved_windows(
    activated_workspace: Single<Entity, Added<ActiveWorkspaceMarker>>,
    windows: Windows,
    mut workspaces: Query<(&mut LayoutStrip, Entity, Has<NativeFullscreenMarker>)>,
    apps: Query<&mut Application>,
    window_manager: Res<WindowManager>,
    mut ignored_windows: Local<HashSet<WinID>>,
    mut commands: Commands,
) {
    let Ok(workspace_id) = workspaces
        .get(*activated_workspace)
        .map(|strip| strip.0.id())
    else {
        return;
    };
    debug!("workspace {workspace_id}");

    let strips = workspaces
        .iter()
        .filter_map(|strip| (strip.0.id() == workspace_id).then_some(strip.0))
        .collect::<Vec<_>>();
    let find_window = |window_id| windows.find_managed(window_id).map(|(_, entity)| entity);
    let Ok((moved_windows, mut unresolved)) =
        windows_not_in_strips(workspace_id, find_window, &strips, &window_manager).inspect_err(
            |err| {
                warn!("unable to get windows in the current workspace: {err}");
            },
        )
    else {
        return;
    };
    // Skip known, but unmanaged windows.
    unresolved.retain(|window_id| {
        !ignored_windows.contains(window_id) && windows.find(*window_id).is_none()
    });

    if !unresolved.is_empty() {
        // Retry unresolved window IDs: during startup bruteforce, windows on
        // inactive workspaces may have stale AX attributes (e.g. AXGroup instead
        // of AXWindow).  Now that this workspace is active, re-query each app's
        // window list — the AX data should be correct.
        let retry_windows = apps
            .into_iter()
            .flat_map(|app| {
                app.window_list()
                    .into_iter()
                    .filter(|window| unresolved.contains(&window.id()))
            })
            .collect::<Vec<_>>();
        if retry_windows.is_empty() {
            for id in unresolved {
                ignored_windows.insert(id);
            }
        } else {
            debug!(
                "retrying unresolved windows: {}",
                retry_windows
                    .iter()
                    .map(|window| format!("{}", window.id()))
                    .collect::<Vec<_>>()
                    .join(" ")
            );
            commands.trigger(SpawnWindowTrigger(retry_windows));
        }
    }

    for entity in moved_windows {
        if workspaces
            .iter()
            .any(|(strip, _, fullscreen)| fullscreen && strip.contains(entity))
        {
            // Do not relocate fullscreen windows, this will happen
            // during the destructino of their workspace.
            continue;
        }

        debug!("Window {entity} moved to workspace {workspace_id}.");
        for (mut strip, strip_entity, _) in &mut workspaces {
            if strip_entity == *activated_workspace {
                strip.append(entity);
            } else {
                strip.remove(entity);
            }
        }
    }
}

#[allow(clippy::needless_pass_by_value)]
#[instrument(level = Level::DEBUG, skip_all, fields(trigger))]
fn workspace_destroyed_trigger(
    trigger: On<WMEventTrigger>,
    mut workspaces: Populated<(&mut LayoutStrip, Entity, Option<&NativeFullscreenMarker>)>,
    mut commands: Commands,
) {
    let Event::SpaceDestroyed { space_id } = trigger.event().0 else {
        return;
    };

    let Some((entity, fullscreen)) = workspaces.iter().find_map(|(strip, entity, fullscreen)| {
        let window = strip.first().ok().and_then(|col| col.top());
        (strip.id() == space_id).then_some((entity, window.zip(fullscreen.cloned())))
    }) else {
        return;
    };

    if let Some((
        window,
        NativeFullscreenMarker {
            previous_strip,
            previous_index,
        },
    )) = fullscreen
        && let Some((mut strip, _, _)) = workspaces
            .iter_mut()
            .find(|(strip, _, _)| strip.id() == previous_strip)
    {
        debug!(
            "previously fullscreened window {entity} inserted at {}",
            previous_index
        );
        strip.insert_at(previous_index, window);
        reshuffle_around(window, &mut commands);
    }

    if let Ok(mut entity_commands) = commands.get_entity(entity) {
        debug!("Workspace destroyed {space_id} {entity}");
        entity_commands.try_despawn();
    }
}

#[allow(clippy::needless_pass_by_value)]
#[instrument(level = Level::DEBUG, skip_all, fields(trigger))]
fn workspace_created_trigger(
    trigger: On<WMEventTrigger>,
    active_display: Single<(&Display, Entity), With<ActiveDisplayMarker>>,
    workspaces: Query<&LayoutStrip>,
    mut commands: Commands,
) {
    let Event::SpaceCreated { space_id } = trigger.event().0 else {
        return;
    };

    if workspaces.into_iter().any(|strip| strip.id() == space_id) {
        warn!("Workspace {space_id} already exists!");
        return;
    }
    debug!("Workspace create {space_id}");
    let (active_display, display_entity) = *active_display;
    let strip = LayoutStrip::new(space_id, 0);
    let origin = Position(active_display.bounds().min);
    commands.spawn((
        strip,
        origin,
        SelectedVirtualMarker,
        ChildOf(display_entity),
    ));
}

fn windows_not_in_strips<F: Fn(WinID) -> Option<Entity>>(
    workspace_id: WorkspaceId,
    find_window: F,
    strips: &[&LayoutStrip],
    window_manager: &WindowManager,
) -> Result<(Vec<Entity>, Vec<WinID>)> {
    window_manager
        .windows_in_workspace(workspace_id)
        .map(|ids| {
            let mut moved = Vec::new();
            let mut unresolved = Vec::new();
            for id in ids {
                if let Some(entity) = find_window(id) {
                    // If window exists in any of the active workspace rows.
                    if strips.iter().any(|strip| strip.contains(entity)) {
                        continue;
                    }
                    moved.push(entity);
                } else {
                    unresolved.push(id);
                }
            }
            (moved, unresolved)
        })
}

#[allow(clippy::needless_pass_by_value)]
#[instrument(level = Level::DEBUG, skip_all)]
fn find_orphaned_workspaces(
    orphans: Populated<(&LayoutStrip, Entity, &Timeout, Option<&ChildOf>), With<Timeout>>,
    displays: Query<(&Display, Entity)>,
    window_manager: Res<WindowManager>,
    mut commands: Commands,
) {
    let present = window_manager.present_displays();

    for (orphan, orphan_entity, timeout, child) in orphans {
        if orphan.len() == 0 {
            if let Ok(mut cmd) = commands.get_entity(orphan_entity) {
                cmd.try_despawn();
            }
            debug!("despawning empty orphan workspace {}", orphan.id());
            continue;
        }
        if child.is_some() {
            // Was reparented, remove timer.
            if let Ok(mut cmd) = commands.get_entity(orphan_entity) {
                cmd.try_remove::<Timeout>();
                cmd.insert(RefreshWindowSizes::default());
            }
            debug!(
                "layout strip {} was re-parented, removing timeout.",
                orphan.id()
            );
            continue;
        }

        if timeout.timer.is_finished() {
            // Rescue windows from orphaned strips before despawning by floating them.
            debug!("Rescue windows from timed out orphan {}.", orphan.id());
            for lost_window in orphan.all_windows() {
                if let Ok(mut cmd) = commands.get_entity(lost_window) {
                    cmd.try_insert(Unmanaged::Floating);
                }
            }
            continue;
        }

        // Find which display now owns this space ID.
        let target = present.iter().find_map(|(present_display, spaces)| {
            if spaces.iter().any(|&id| id == orphan.id()) {
                displays
                    .iter()
                    .find(|(d, _)| d.id() == present_display.id())
            } else {
                None
            }
        });
        let Some((target_display, target_entity)) = target else {
            continue; // No display owns this space yet; wait for next tick.
        };

        debug!(
            "Re-parenting orphaned strip {} to display {}",
            orphan.id(),
            target_display.id(),
        );

        if let Ok(mut cmd) = commands.get_entity(orphan_entity) {
            cmd.try_remove::<Timeout>()
                .insert(ChildOf(target_entity))
                .insert(RefreshWindowSizes::default());
        }
    }
}

#[allow(clippy::needless_pass_by_value)]
fn refresh_workspace_window_sizes(
    layout_strip: Single<(&LayoutStrip, Entity, &RefreshWindowSizes), With<ActiveWorkspaceMarker>>,
    mut windows: Query<(Entity, &mut Window, &mut Bounds, Option<&Unmanaged>)>,
    active_display: ActiveDisplay,
    window_manager: Res<WindowManager>,
    mut commands: Commands,
) {
    let (strip, strip_entity, marker) = *layout_strip;
    if !marker.ready() {
        return;
    }

    debug!("refreshing workspace {} sizes", strip.id());
    let mut in_workspace = window_manager
        .windows_in_workspace(strip.id())
        .inspect_err(|err| {
            warn!("getting windows in workspace: {err}");
        })
        .unwrap_or_default();

    // Resize windows for the new display dimensions.
    for entity in strip.all_windows() {
        let Ok((_, ref mut window, ref mut bounds, _)) = windows.get_mut(entity) else {
            continue;
        };
        let Ok(frame) = window.update_frame() else {
            continue;
        };
        bounds.0 = frame.size();
        debug!("refreshing window {} frame {:?}", window.id(), frame);

        in_workspace.retain(|window_id| *window_id != window.id());
    }

    // Find remaining windows which are outside of the strip.                                                  ...
    let floating = in_workspace
        .into_iter()
        .filter_map(|window_id| {
            windows
                .iter()
                .find_map(|(entity, window, _, unmanaged)| {
                    (window_id == window.id()).then_some(unmanaged.zip(Some(entity)))
                })
                .flatten()
        })
        .filter_map(|(unmanaged, entity)| {
            matches!(unmanaged, Unmanaged::Floating).then_some(entity)
        });
    for window_entity in floating {
        debug!("repositioning floating window {window_entity}");
        reposition_entity(window_entity, active_display.bounds().min, &mut commands);
    }

    if let Ok(mut cmds) = commands.get_entity(strip_entity) {
        cmds.try_remove::<RefreshWindowSizes>();
    }
}

/// Periodically checks for changes in the active workspace (space) on the active display.
/// This system acts as a workaround for inconsistent workspace change notifications on some macOS versions.
/// If a change is detected, it triggers an `Event::SpaceChanged` event.
///
/// # Arguments
///
/// * `active_display` - An `ActiveDisplay` system parameter providing immutable access to the active display.
/// * `window_manager` - The `WindowManager` resource for querying active space information.
/// * `throttle` - A `ThrottledSystem` to control the execution rate of this system.
/// * `current_space` - A `Local` resource storing the ID of the currently observed space.
/// * `commands` - Bevy commands to trigger `WMEventTrigger` events for space changes.
#[allow(clippy::needless_pass_by_value)]
pub(crate) fn workspace_change_watcher(
    active_display: ActiveDisplay,
    window_manager: Res<WindowManager>,
    mut current_space: Local<WorkspaceId>,
    mut commands: Commands,
) {
    let Ok(space_id) = window_manager
        .0
        .active_display_space(active_display.id())
        .inspect_err(|err| warn!("{err}"))
    else {
        return;
    };

    if *current_space != space_id {
        *current_space = space_id;
        debug!("workspace changed to {space_id}");
        commands.trigger(WMEventTrigger(Event::SpaceChanged));
    }
}

/// Removes previuos `ActiveWorkspaceMarker`'s when a new one is inserted.
#[allow(clippy::needless_pass_by_value)]
#[instrument(level = Level::DEBUG, skip_all, fields(trigger))]
fn cleanup_active_workspace_marker(
    trigger: On<Add, ActiveWorkspaceMarker>,
    workspaces: Query<(Entity, Has<ActiveWorkspaceMarker>), With<LayoutStrip>>,
    mut commands: Commands,
) {
    workspaces.iter().for_each(|(entity, marker)| {
        if marker
            && entity != trigger.entity
            && let Ok(mut entity_commands) = commands.get_entity(entity)
        {
            entity_commands.try_remove::<ActiveWorkspaceMarker>();
        }
    });
}

/// Removes previuos `SelectedVirtualMarker`'s when a new one is inserted.
#[allow(clippy::needless_pass_by_value)]
#[instrument(level = Level::DEBUG, skip_all, fields(trigger))]
fn cleanup_selected_space_marker(
    trigger: On<Add, SelectedVirtualMarker>,
    workspaces: Query<(Entity, &LayoutStrip, Has<SelectedVirtualMarker>)>,
    mut commands: Commands,
) {
    let Ok(workspace_id) = workspaces
        .get(trigger.entity)
        .map(|(_, strip, _)| strip.id())
    else {
        return;
    };

    // Remove the marker from other strips on the same workspace.
    workspaces.iter().for_each(|(entity, strip, marker)| {
        if marker
            && entity != trigger.entity
            && strip.id() == workspace_id
            && let Ok(mut entity_commands) = commands.get_entity(entity)
        {
            entity_commands.try_remove::<SelectedVirtualMarker>();
        }
    });
}

#[allow(clippy::needless_pass_by_value)]
fn handle_virtual_window_moves(
    moved_windows: Populated<(Entity, &VirtualMoveMarker), With<Window>>,
    mut workspaces: Query<(
        Entity,
        &mut LayoutStrip,
        &Position,
        Has<ActiveWorkspaceMarker>,
    )>,
    active_display: Single<(Entity, &Display), With<ActiveDisplayMarker>>,
    mut commands: Commands,
) {
    let Some((workspace_id, source_entity)) = workspaces
        .iter()
        .find_map(|(entity, strip, _, active)| active.then_some((strip.id(), entity)))
    else {
        return;
    };

    let (display_entity, active_display) = *active_display;
    for (window_entity, move_marker) in &moved_windows {
        commands.entity(window_entity).remove::<VirtualMoveMarker>();
        let follow = matches!(move_marker.move_focus, MoveFocus::Follow);

        let target_idx = move_marker.target_virtual_index;
        let target = workspaces.iter().find_map(|(entity, strip, _, _)| {
            (strip.id() == workspace_id && strip.virtual_index == target_idx).then_some(entity)
        });

        // Must be captured before strip.remove below.
        let source_neighbour = workspaces
            .get(source_entity)
            .ok()
            .and_then(|(_, strip, _, _)| {
                strip
                    .left_neighbour(window_entity)
                    .or_else(|| strip.right_neighbour(window_entity))
            });
        // If source will be empty after the move, Stay becomes Follow
        // since there's nothing left to look at.
        let stay = !follow && source_neighbour.is_some();

        let target_entity = if let Some(entity) = target {
            entity
        } else {
            // Stay: spawn offscreen with PreviousStripPosition for later restoration.
            // Follow (or empty source): spawn visible, user is switching to it.
            let visible_origin = active_display.bounds().min;
            let origin = if stay {
                active_display.bounds().max - 10
            } else {
                visible_origin
            };
            debug!(
                "Creating new virtual row {target_idx} on workspace {}",
                workspace_id
            );
            let mut new_strip = LayoutStrip::new(workspace_id, target_idx);
            new_strip.append(window_entity);

            let mut spawned = commands.spawn((
                new_strip,
                Position(origin),
                SelectedVirtualMarker,
                ChildOf(display_entity),
            ));
            if stay {
                // show_active_workspace needs this to restore the strip
                // onscreen when the user later switches to this workspace.
                spawned.insert(PreviousStripPosition {
                    origin: visible_origin,
                    focus: Some(window_entity),
                });
            }
            spawned.id()
        };

        // Preserve the source strip's scroll position for when the user returns.
        if !stay
            && let Ok(mut entity_commands) = commands.get_entity(source_entity)
            && let Ok((_, source_strip, position, _)) = workspaces.get(source_entity)
        {
            let focus = source_strip
                .left_neighbour(window_entity)
                .or_else(|| source_strip.right_neighbour(window_entity));
            entity_commands.try_insert(PreviousStripPosition {
                origin: position.0,
                focus,
            });
        }

        // Move the window before moving markers to avoid being detected as a moved window.
        for (entity, mut strip, _, _) in &mut workspaces {
            if entity == target_entity {
                strip.append(window_entity);
            } else {
                strip.remove(window_entity);
            }
        }

        // Insert new markers. ActiveWorkspaceMarker switches the view.
        if let Ok(mut entity_commands) = commands.get_entity(target_entity) {
            entity_commands.try_insert(SelectedVirtualMarker);
            if !stay {
                entity_commands.try_insert(ActiveWorkspaceMarker);
            }
        }

        if stay && let Some(neighbour) = source_neighbour {
            // Layout chain repositions the window offscreen with its hidden strip.
            focus_entity(neighbour, false, &mut commands);
            reshuffle_around(neighbour, &mut commands);
        } else {
            reshuffle_around(window_entity, &mut commands);
        }
        debug!(
            "Moved window {} to virtual workspace {}",
            window_entity, target_idx
        );
    }
}

/// Handles the keybinding for switching between virtual workspaces.
#[instrument(level = Level::DEBUG, skip_all)]
#[allow(clippy::needless_pass_by_value)]
fn switch_virtual_workspace_bind(
    mut messages: MessageReader<Event>,
    active_display: ActiveDisplay,
    workspaces: Query<(Entity, &LayoutStrip, Has<ActiveWorkspaceMarker>)>,
    mut commands: Commands,
) {
    let Some(operation) = filter_window_operations(&mut messages, |op| {
        matches!(op, Operation::Virtual(_) | Operation::VirtualNumber(_))
    })
    .next() else {
        return;
    };

    let workspace_id = active_display.active_strip().id();
    let mut rows = workspaces
        .iter()
        .filter(|(_, strip, _)| strip.id() == workspace_id)
        .collect::<Vec<_>>();

    if rows.is_empty() {
        return;
    }
    rows.sort_by_key(|(_, strip, _)| strip.virtual_index);

    let current_index = rows.iter().position(|(_, _, active)| *active).unwrap_or(0);
    let next_index = match operation {
        Operation::Virtual(Direction::South) => (current_index + 1).clamp(0, rows.len() - 1),
        Operation::Virtual(Direction::North) => current_index.saturating_sub(1),
        Operation::VirtualNumber(target_virtual_index) => {
            let Some(index) = rows
                .iter()
                .position(|(_, strip, _)| strip.virtual_index == *target_virtual_index)
            else {
                if *target_virtual_index == 0 {
                    return;
                }
                let strip = LayoutStrip::new(workspace_id, *target_virtual_index);
                commands.spawn((
                    strip,
                    Position(active_display.bounds().min),
                    ChildOf(active_display.entity()),
                    SelectedVirtualMarker,
                    ActiveWorkspaceMarker,
                ));
                flash_message(format!("{}", *target_virtual_index + 1), 1.0, &mut commands);
                return;
            };
            index
        }
        _ => return,
    };

    if next_index == current_index {
        return;
    }

    let new_entity = rows[next_index].0;
    let next_virtual_index = rows[next_index].1.virtual_index;
    if let Ok(mut entity_commands) = commands.get_entity(new_entity) {
        entity_commands
            .try_insert(SelectedVirtualMarker)
            .try_insert(ActiveWorkspaceMarker);

        // Flash workspace number
        flash_message(format!("{}", next_virtual_index + 1), 1.0, &mut commands);
    }
    debug!(
        "Switched virtual workspace on display {} from {} to {}",
        active_display.id(),
        rows[current_index].1.virtual_index,
        rows[next_index].1.virtual_index
    );
}

/// Handles the keybinding to move windows between virtual workspaces.
#[instrument(level = Level::DEBUG, skip_all)]
#[allow(clippy::needless_pass_by_value)]
fn move_virtual_workspace_bind(
    mut messages: MessageReader<Event>,
    windows: Windows,
    active_display: ActiveDisplay,
    mut commands: Commands,
) {
    let Some(operation) = filter_window_operations(&mut messages, |op| {
        matches!(
            op,
            Operation::VirtualMove(_, _) | Operation::VirtualMoveNumber(_, _)
        )
    })
    .next() else {
        return;
    };

    let Some((_, focused_entity)) = windows.focused() else {
        return;
    };

    let current_virtual_index = active_display.active_strip().virtual_index;

    let (target_virtual_index, move_focus) = match operation {
        Operation::VirtualMove(Direction::South, move_focus)
            if active_display.active_strip().len() > 1 =>
        {
            (current_virtual_index + 1, *move_focus)
        }
        Operation::VirtualMove(Direction::North, move_focus) => {
            if current_virtual_index == 0 {
                return;
            }
            (current_virtual_index - 1, *move_focus)
        }
        Operation::VirtualMoveNumber(target_virtual_index, move_focus) => {
            if *target_virtual_index == current_virtual_index {
                return;
            }
            (*target_virtual_index, *move_focus)
        }
        _ => return,
    };

    commands.entity(focused_entity).insert(VirtualMoveMarker {
        target_virtual_index,
        move_focus,
    });

    if move_focus == MoveFocus::Follow {
        flash_message(format!("{}", target_virtual_index + 1), 1.0, &mut commands);
    }

    debug!("Moving {focused_entity} to new virtual space {target_virtual_index}");
}

#[allow(clippy::needless_pass_by_value)]
#[instrument(level = Level::DEBUG, skip_all)]
fn show_active_workspace(
    activated: Single<Entity, Added<ActiveWorkspaceMarker>>,
    windows: Windows,
    mut workspaces: Query<
        (
            Entity,
            &mut Position,
            &LayoutStrip,
            Option<&PreviousStripPosition>,
        ),
        Without<Window>,
    >,
    active_display: Single<&Display, With<ActiveDisplayMarker>>,
    mut commands: Commands,
) {
    let Some(workspace_id) = workspaces
        .iter()
        .find_map(|(entity, _, strip, _)| (entity == *activated).then_some(strip.id()))
    else {
        return;
    };

    // Hide other strips on the current workspace
    let current_focus = windows.focused();
    let current_workspace = workspaces
        .iter_mut()
        .filter(|(entity, _, strip, _)| strip.id() == workspace_id && *entity != *activated);

    for (entity, mut position, strip, previous) in current_workspace {
        if previous.is_none() {
            let mut focus =
                current_focus.and_then(|(_, entity)| strip.contains(entity).then_some(entity));
            if focus.is_none() {
                let display_center = active_display.bounds().center().x;
                let closest = strip
                    .all_columns()
                    .into_iter()
                    .filter_map(|candidate| {
                        let center = windows.moving_frame(candidate)?.center().x;
                        let distance = (center - display_center).abs();
                        Some((candidate, distance))
                    })
                    .min_by_key(|(_, dist)| *dist)
                    .map(|min| min.0);
                focus = closest;
                debug!("No previous focus, taking centered one {focus:?}.");
            }

            if let Ok(mut entity_commands) = commands.get_entity(entity) {
                entity_commands.try_insert(PreviousStripPosition {
                    origin: position.0,
                    focus,
                });
            }
        }

        let bounds = active_display.bounds();
        position.0 = bounds.max - 10;
    }

    let Ok((_, mut position, strip, previous_position)) = workspaces.get_mut(*activated) else {
        return;
    };
    debug!("showing virtual workspace {} ({})", strip.id(), *activated);

    // If no previous strip position exists, then the workspace was not hidden.
    if let Some(PreviousStripPosition { origin, focus }) = previous_position {
        if let Ok(mut entity_commands) = commands.get_entity(*activated) {
            entity_commands.try_remove::<PreviousStripPosition>();
        }
        position.0 = *origin;

        if let Some((_, current_focus)) = windows.focused()
            && strip.contains(current_focus)
        {
            return;
        }

        // Focus on the previous window
        if let Some(entity) = focus
            && strip.contains(*entity)
        {
            focus_entity(*entity, false, &mut commands);
        }
    }
}