paneru 0.5.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
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
use bevy::app::{App, Plugin, PostUpdate, PreUpdate, Update};
use bevy::ecs::change_detection::{DetectChanges as _, DetectChangesMut, Ref};
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, ParamSet, Populated, Query, Res, ResMut, Single};
use bevy::ecs::world::World;
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};
use crate::commands::{
    Direction, MoveFocus, Operation, filter_window_operations, get_window_in_direction,
};
use crate::config::Config;
use crate::ecs::focus::FocusHistory;
use crate::ecs::layout::{LayoutStrip, PARKED_STRIP_SLIVER, origin_exposing};
use crate::ecs::params::{ActiveDisplay, WindowCtx, Windows};
use crate::ecs::{
    ActiveWorkspaceMarker, DockPosition, FocusedMarker, Initializing, ManualStripOffset,
    NativeFullscreenMarker, Position, RaiseWindow, RepositionMarker, Scrolling,
    SelectedVirtualMarker, SendMessageTrigger, SpawnCommandsExt, Timeout, Unmanaged,
};
use crate::errors::Result;
use crate::events::{DestroySource, Event};
use crate::manager::{Application, Display, Origin, Window, WindowManager};
use crate::platform::{WinID, WorkspaceId};

pub struct WorkspaceEventsPlugin;

/// The strip, its origin, whether it's visible, and its saved position, as
/// [`handle_virtual_window_moves`] needs them to slide a strip to/from its
/// parked position.
type MovableStrips<'w, 's> = Query<
    'w,
    's,
    (
        Entity,
        &'static mut LayoutStrip,
        &'static mut Position,
        Has<ActiveWorkspaceMarker>,
        Option<&'static mut PreviousStripPosition>,
    ),
    Without<Window>,
>;

/// The saved origin and any in-flight `RepositionMarker`, as
/// [`show_active_workspace`] needs them to restore a strip.
type RestorableStrips<'w, 's> = Query<
    'w,
    's,
    (
        Entity,
        &'static mut Position,
        &'static LayoutStrip,
        &'static ChildOf,
        Option<&'static PreviousStripPosition>,
        Option<&'static RepositionMarker>,
    ),
    Without<Window>,
>;

/// `p0`: strips added this tick. `p1`: rewrites indexes of strips sharing
/// their workspace. Must be a `ParamSet` since `p1` aliases `p0` mutably.
type RenumberStrips<'w, 's> = ParamSet<
    'w,
    's,
    (
        Query<'static, 'static, &'static LayoutStrip, Added<LayoutStrip>>,
        Query<'static, 'static, (Entity, &'static mut LayoutStrip)>,
    ),
>;

impl Plugin for WorkspaceEventsPlugin {
    fn build(&self, app: &mut App) {
        const DISPLAY_CHANGE_CHECK_FREQ: Duration = Duration::from_secs(1);

        let reap_workspaces = |config: Option<Res<Config>>| {
            config.is_some_and(|config| config.reap_empty_workspaces())
        };

        app.add_systems(
            PreUpdate,
            (switch_virtual_workspace_bind, move_virtual_workspace_bind),
        );
        app.add_systems(
            PreUpdate,
            find_orphaned_workspaces
                .after(crate::ecs::display::reconcile_displays)
                .run_if(on_timer(DISPLAY_CHANGE_CHECK_FREQ)),
        );
        app.add_systems(
            Update,
            (
                renumber_virtual_indexes,
                reap_empty_virtual_workspaces.run_if(reap_workspaces),
                workspace_change_handler,
                workspace_created_handler,
                show_active_workspace,
                handle_virtual_window_moves,
                detect_moved_windows.run_if(not(resource_exists::<Initializing>)),
            ),
        );
        app.add_systems(PostUpdate, workspace_destroyed_handler);
        app.add_observer(cleanup_active_workspace_marker)
            .add_observer(cleanup_selected_space_marker);
    }
}

/// Marker component to move a window to a specific virtual index on its current workspace.
#[derive(Component)]
pub(super) 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>,
}

/// Guard spawned alongside the re-focus of a restored strip's remembered
/// window. The OS's focus acknowledgment arrives several ticks after the
/// strip was already placed at its saved origin, so without this guard
/// `autocenter_window_on_focus` and `window_focused_trigger`'s reshuffle would
/// slide the strip away again (a visible wiggle on every switch); both skip
/// the named entity while this marker exists. It is despawned once focus
/// moves elsewhere, or expires via `timeout_ticker`.
#[derive(Component, Debug)]
pub(crate) struct RestoreFocusMarker {
    pub entity: Entity,
}

/// Long enough for the OS focus acknowledgments to arrive, short enough that
/// a user re-clicking the restored window soon after the switch gets the
/// normal expose-reshuffle back.
const RESTORE_FOCUS_GUARD_TIMEOUT: Duration = Duration::from_secs(2);

fn spawn_restore_focus_guard(entity: Entity, commands: &mut Commands) {
    let timeout = Timeout::new(RESTORE_FOCUS_GUARD_TIMEOUT, None, commands);
    commands.spawn((timeout, RestoreFocusMarker { entity }));
}

/// Guard spawned when `show_active_workspace` writes a restored strip's
/// `Position` directly (`virtual_workspace_animations = false`). That write
/// only fixes the strip's own aggregate offset instantly; individual member
/// windows still get re-evaluated by `position_layout_windows` on a
/// following tick (via `position_layout_strips` reacting to the strip's now
/// -`Changed<Position>`), using whatever `Position` they were last left at —
/// which, for a lower stack member parked while its strip was hidden, can
/// land close enough to its restored target that neither the "offscreen
/// distance" nor the "parked at the corner" heuristic recognizes it as a
/// restore-driven move. Left to the ordinary heuristic, that move animates,
/// riding along even though the strip itself just snapped. While a live
/// guard names a strip, `position_layout_windows` snaps every member
/// window directly, bypassing that heuristic entirely. Expires via
/// `timeout_ticker` like `RestoreFocusMarker`.
#[derive(Component, Debug)]
pub(crate) struct SnapStripMarker {
    pub strip: Entity,
}

/// Long enough for the settle described above to actually finish (it can
/// take more than one tick), short enough that an ordinary layout change
/// shortly after a switch still animates normally.
const SNAP_STRIP_GUARD_TIMEOUT: Duration = Duration::from_millis(500);

fn spawn_snap_strip_guard(strip: Entity, commands: &mut Commands) {
    let timeout = Timeout::new(SNAP_STRIP_GUARD_TIMEOUT, None, commands);
    commands.spawn((timeout, SnapStripMarker { strip }));
}

fn fullscreen_window_in_strip(
    workspace_id: WorkspaceId,
    strip: &LayoutStrip,
    windows: &Windows,
    window_manager: &WindowManager,
) -> Option<Entity> {
    window_manager
        .windows_in_workspace(workspace_id)
        .ok()
        .and_then(|window_ids| {
            window_ids.into_iter().find_map(|window_id| {
                windows
                    .find_managed(window_id)
                    .map(|(_, entity)| entity)
                    .filter(|entity| strip.contains(*entity))
            })
        })
        .or_else(|| {
            windows.managed_iter().find_map(|(window, entity, _)| {
                (strip.contains(entity) && window.is_full_screen()).then_some(entity)
            })
        })
        .or_else(|| {
            windows
                .focused()
                .map(|(_, entity)| entity)
                .filter(|entity| strip.contains(*entity))
        })
}

#[instrument(level = Level::DEBUG, skip_all, fields(trigger))]
fn workspace_change_handler(
    mut messages: MessageReader<Event>,
    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,
) {
    if !messages
        .read()
        .any(|event| matches!(event, Event::SpaceChanged))
    {
        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 Ok((mut old_strip, old_strip_entity, _, _)) = workspaces.get_mut(old_space)
        && let Some(fullscreen_window) =
            fullscreen_window_in_strip(workspace_id, &old_strip, &windows, &window_manager)
        && let Ok(original_index) = old_strip.index_of(fullscreen_window)
    {
        debug!("workspace_change: space={workspace_id} fullscreen");

        let fullscreen_marker = NativeFullscreenMarker {
            layout_strip: old_strip_entity,
            workspace_id: old_strip.id(),
            index: original_index,
        };
        old_strip.remove(fullscreen_window);

        let fullscreen_strip = LayoutStrip::fullscreen(workspace_id, fullscreen_window);
        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);
    }
}

#[instrument(level = Level::DEBUG, skip_all, fields(trigger))]
fn detect_moved_windows(
    activated_workspace: Single<Entity, Added<ActiveWorkspaceMarker>>,
    mut workspaces: Query<(&mut LayoutStrip, Entity, Has<NativeFullscreenMarker>)>,
    apps: Query<&mut Application>,
    window_manager: Res<WindowManager>,
    mut ignored_windows: Local<HashSet<WinID>>,
    mut ctx: WindowCtx,
) {
    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| {
        ctx.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) && ctx.windows.find(*window_id).is_none()
    });

    if !unresolved.is_empty() {
        let unresolved_ids = unresolved.iter().copied().collect::<HashSet<_>>();
        // 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(&ctx.config)
                    .into_iter()
                    .filter(|window| unresolved_ids.contains(&window.id()))
            })
            .collect::<Vec<_>>();
        if retry_windows.is_empty() {
            for id in unresolved_ids {
                ignored_windows.insert(id);
            }
        } else {
            debug!(
                "retrying unresolved windows: {}",
                retry_windows
                    .iter()
                    .map(|window| format!("{}", window.id()))
                    .collect::<Vec<_>>()
                    .join(" ")
            );
            ctx.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}.");
        let moving_entities = workspaces
            .iter()
            .find_map(|(strip, _, _)| strip.tab_group(entity))
            .unwrap_or_else(|| vec![entity]);
        for (mut strip, strip_entity, _) in &mut workspaces {
            if strip_entity == *activated_workspace {
                strip.append_tab_group(&moving_entities);
            } else {
                for moving_entity in &moving_entities {
                    strip.remove(*moving_entity);
                }
            }
        }
    }
}

#[instrument(level = Level::DEBUG, skip_all, fields(trigger))]
fn workspace_destroyed_handler(
    mut messages: MessageReader<Event>,
    mut workspaces: Populated<(&mut LayoutStrip, Entity, Option<&NativeFullscreenMarker>)>,
    mut focus_history: ResMut<FocusHistory>,
    mut commands: Commands,
) {
    for event in messages.read() {
        let Event::SpaceDestroyed { space_id } = event else {
            continue;
        };
        focus_history.forget_workspace(*space_id);

        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 {
            continue;
        };

        if let Some((
            window,
            NativeFullscreenMarker {
                layout_strip,
                workspace_id,
                index,
            },
        )) = fullscreen
        {
            let mut strip = workspaces
                .iter_mut()
                .find_map(|(strip, entity, _)| (entity == layout_strip).then_some(strip));
            if strip.is_none() {
                strip = workspaces
                    .iter_mut()
                    .find_map(|(strip, _, _)| (strip.id() == workspace_id).then_some(strip));
            }

            debug!(
                "previously fullscreened window {entity} inserted at {}",
                index
            );
            if let Some(mut strip) = strip {
                strip.insert_at(index, window);
                commands.reshuffle_around(window);
            }
        }

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

#[instrument(level = Level::DEBUG, skip_all, fields(trigger))]
fn workspace_created_handler(
    mut messages: MessageReader<Event>,
    active_display: Single<(&Display, Entity), With<ActiveDisplayMarker>>,
    workspaces: Query<&LayoutStrip>,
    mut commands: Commands,
) {
    for event in messages.read() {
        let Event::SpaceCreated { space_id } = event else {
            continue;
        };

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

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)
        })
}

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

    for (orphan, orphan_entity, timeout, child) in orphans {
        // Row 0 is the row every space is created with, so it is re-parented
        // like a populated strip: despawning it leaves the space numbered from
        // "2" with no row that any switch or reap path recreates.
        if orphan.len() == 0 && orphan.virtual_index > 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>();
            }
            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));
            commands.queue(move |world: &mut World| {
                crate::ecs::display::refresh_reparented_strip(world, orphan_entity);
            });
            rehomed = true;
        }
    }
    if rehomed {
        commands.trigger(SendMessageTrigger(Event::DisplayChanged));
    }
}

#[allow(clippy::needless_pass_by_value)]
pub(crate) fn cleanup_unordered_windows(
    windows: Query<&Window>,
    workspaces: Query<&LayoutStrip>,
    window_manager: Res<WindowManager>,
    mut commands: Commands,
) {
    let windows = workspaces
        .iter()
        .flat_map(|strip| {
            strip
                .all_windows()
                .into_iter()
                .filter(|entity| !strip.tabbed(*entity))
        })
        .filter_map(|entity| windows.get(entity).ok());

    for window in windows {
        let window_id = window.id();
        if window_manager.window_is_unordered(window_id) && window.role().is_err() {
            debug!("Window {window_id} is unordered; removing it.");
            commands.trigger(SendMessageTrigger(Event::WindowDestroyed {
                window_id,
                source: DestroySource::Accessibility,
            }));
        }
    }
}

/// Removes previuos `ActiveWorkspaceMarker`'s when a new one is inserted.
#[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 entity == trigger.entity
            && let Ok(mut entity_commands) = commands.get_entity(entity)
        {
            // Mark the currently selected VW with selected marker. This also removes the previously
            // selected markers from other VW's on the same workspace.
            entity_commands.try_insert(SelectedVirtualMarker);
        } else if marker && let Ok(mut entity_commands) = commands.get_entity(entity) {
            // Remove the active marker from any other workspace.
            entity_commands.try_remove::<ActiveWorkspaceMarker>();
        }
    });
}

/// Removes previuos `SelectedVirtualMarker`'s when a new one is inserted.
#[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::too_many_lines)]
fn handle_virtual_window_moves(
    moved_windows: Populated<(Entity, &VirtualMoveMarker), With<Window>>,
    mut workspaces: MovableStrips,
    windows: Windows,
    mut scrollings: Query<&mut Scrolling>,
    active_display: Single<(Entity, &Display, Option<&DockPosition>), With<ActiveDisplayMarker>>,
    config: Res<Config>,
    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, dock) = *active_display;
    let viewport = active_display.actual_display_bounds(dock, &config);
    for (window_entity, move_marker) in &moved_windows {
        let moving_entities = workspaces
            .get(source_entity)
            .ok()
            .and_then(|(_, strip, _, _, _)| strip.tab_group(window_entity))
            .unwrap_or_else(|| vec![window_entity]);
        for moving_entity in &moving_entities {
            if let Ok(mut entity_commands) = commands.get_entity(*moving_entity) {
                entity_commands.try_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();

        // With `insert_windows_mid_strip`, the window keeps its current on-screen
        // x. For an existing destination, work out the column slot nearest that x
        // and the scroll offset that lands it there; for a new strip the lone
        // window just sits at that x.
        let moved_left = config
            .insert_windows_mid_strip()
            .then(|| windows.moving_frame(window_entity).map(|frame| frame.min.x))
            .flatten();
        let mid_placement = moved_left.and_then(|moved_left| {
            let (_, strip, position, _, previous) = workspaces.get(target?).ok()?;
            let scroll_x = previous.map_or(position.0.x, |previous| previous.origin.x);
            Some(mid_strip_slot(strip, scroll_x, moved_left, &windows))
        });

        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 = viewport.min;
            // mid-strip: keep the lone window at its current x.
            let shown = Origin::new(moved_left.unwrap_or(visible_origin.x), visible_origin.y);
            let parked = viewport.max - PARKED_STRIP_SLIVER;
            let origin = if stay { parked } else { shown };
            debug!(
                "Creating new virtual row {target_idx} on workspace {}",
                workspace_id
            );
            let mut new_strip = LayoutStrip::new(workspace_id, target_idx);
            new_strip.append_tab_group(&moving_entities);

            let mut spawned = commands.spawn_layout_strip(new_strip, origin, display_entity, false);
            if stay {
                // show_active_workspace needs this to restore the strip
                // onscreen when the user later switches to this workspace.
                spawned.insert(PreviousStripPosition {
                    origin: shown,
                    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 {
                match mid_placement {
                    Some((slot, _)) => strip.insert_tab_group_at(slot, &moving_entities),
                    None => strip.append_tab_group(&moving_entities),
                }
            } else {
                for moving_entity in &moving_entities {
                    strip.remove(*moving_entity);
                }
            }
        }

        // Scroll the destination so the inserted window keeps its exact x. Done
        // before the strip is shown so show_active_workspace snaps every window
        // to its final spot in one go (no horizontal slide). Resetting Scrolling
        // stops stale momentum from overriding the offset on reactivation.
        if let Some((_, desired_scroll)) = mid_placement {
            if let Ok((_, _, _, _, Some(mut previous))) = workspaces.get_mut(target_entity) {
                previous.origin.x = desired_scroll;
            }
            if let Ok(mut scroll) = scrollings.get_mut(target_entity) {
                scroll.position = f64::from(desired_scroll);
                scroll.velocity = 0.0;
            }
        }

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

        if stay && let Some(neighbour) = source_neighbour {
            // Layout chain repositions the window offscreen with its hidden strip.
            commands.focus_entity(neighbour, false);

            // Force position change on the hidden strip, so it hides the moved window.
            if let Ok(mut position) = workspaces
                .get_mut(target_entity)
                .map(|(_, _, pos, _, _)| pos)
            {
                position.set_changed();
            }
        } else {
            let previous_position = workspaces
                .get_mut(target_entity)
                .ok()
                .and_then(|(_, _, _, _, previos_pos)| previos_pos);
            if let Some(mut previous) = previous_position {
                previous.focus = Some(window_entity);
            }
            commands.reshuffle_around(window_entity);

            if mid_placement.is_none()
                && let Ok(mut entity_commands) = commands.get_entity(window_entity)
            {
                entity_commands.try_remove::<FocusedMarker>();
                commands.focus_entity(window_entity, false);
            }
        }
        debug!(
            "Moved window {} to virtual workspace {}",
            window_entity, target_idx
        );
    }
}

/// Picks where in `strip` a window currently at on-screen x `moved_left` should
/// be inserted so it keeps that position. Inserting at column `i` lands the
/// window at that column's left edge, so we choose the column boundary nearest
/// `moved_left`, then return the scroll offset that makes that slot sit exactly
/// at `moved_left`. `scroll_x` is the strip's (intended) scroll offset.
///
/// Returns `(insert_index, desired_scroll)`.
fn mid_strip_slot(
    strip: &LayoutStrip,
    scroll_x: i32,
    moved_left: i32,
    windows: &Windows,
) -> (usize, i32) {
    let columns: Vec<(i32, i32)> = strip
        .all_columns()
        .into_iter()
        .filter_map(|column| {
            let layout_x = windows.layout_position(column)?.0.x;
            let width = windows
                .moving_frame(column)
                .map_or(0, |frame| frame.width());
            Some((layout_x, width))
        })
        .collect();

    let mut index = columns.len();
    let mut chosen_layout_x = columns
        .last()
        .map_or(0, |(layout_x, width)| layout_x + width);
    let mut best = (chosen_layout_x + scroll_x - moved_left).abs();
    for (i, (layout_x, _)) in columns.iter().enumerate() {
        let dist = (layout_x + scroll_x - moved_left).abs();
        if dist < best {
            best = dist;
            index = i;
            chosen_layout_x = *layout_x;
        }
    }
    (index, moved_left - chosen_layout_x)
}

/// Handles the keybinding for switching between virtual workspaces. Moving South
/// creates a new workspace if the current one is populated and auto-create is on.
#[allow(clippy::too_many_lines)]
#[instrument(level = Level::DEBUG, skip_all)]
fn switch_virtual_workspace_bind(
    mut messages: MessageReader<Event>,
    windows: Windows,
    active_display: ActiveDisplay,
    workspaces: Query<(Entity, &LayoutStrip, Has<ActiveWorkspaceMarker>)>,
    config: Res<Config>,
    mut commands: Commands,
) {
    let Some(operation) = filter_window_operations(&mut messages, |op| {
        matches!(
            op,
            Operation::Virtual(_)
                | Operation::VirtualNumber(_)
                | Operation::VirtualAdd
                | Operation::FocusOrVirtual(_)
        )
    })
    .next() else {
        return;
    };

    // `FocusOrVirtual` is a distinct command from `Operation::Virtual` on
    // purpose: `window_virtual_north/south` must keep meaning exactly
    // "switch the virtual workspace", unconditionally, for anyone who binds
    // it that way — this new command is for callers who explicitly want
    // "focus a stack neighbor above/below first, and only switch workspace
    // once there's nothing left to focus", the same within-column traversal
    // `window_focus_north/south` uses. Only North/South are meaningful here
    // (there's no "focus" reading of East/West/First/Last/Nth to pair with
    // a workspace switch); anything else is a no-op. Once the focus check
    // doesn't apply, this reduces to a plain `Operation::Virtual(direction)`
    // and falls through to the exact same switching logic below.
    let synthesized_virtual;
    let operation = match operation {
        Operation::FocusOrVirtual(direction @ (Direction::North | Direction::South)) => {
            if let Some((_, focused_entity)) = windows.focused()
                && let Some(target) = get_window_in_direction(
                    direction,
                    focused_entity,
                    active_display.active_strip(),
                )
            {
                commands.focus_entity(target, true);
                commands.reshuffle_around(target);
                return;
            }
            synthesized_virtual = Operation::Virtual(direction.clone());
            &synthesized_virtual
        }
        Operation::FocusOrVirtual(_) => return,
        operation => operation,
    };

    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 | Direction::East) => {
            if current_index + 1 < rows.len() {
                current_index + 1
            } else if active_display.active_strip().len() != 0
                && config.create_workspace_automatically()
            {
                let target_index = rows[current_index].1.virtual_index + 1;
                commands.spawn_layout_strip(
                    LayoutStrip::new(workspace_id, target_index),
                    active_display.bounds().min,
                    active_display.entity(),
                    true,
                );
                if config.workspace_popup_status() {
                    commands.flash_message(format!("{}", target_index + 1), 1.0);
                }
                return;
            } else {
                current_index
            }
        }
        Operation::Virtual(Direction::North | Direction::West) => current_index.saturating_sub(1),
        Operation::Virtual(Direction::First) => 0,
        Operation::Virtual(Direction::Last) => rows.len().saturating_sub(1),
        Operation::VirtualNumber(target_virtual_index) => {
            let Some(index) = rows
                .iter()
                .position(|(_, strip, _)| strip.virtual_index == *target_virtual_index)
            else {
                commands.spawn_layout_strip(
                    LayoutStrip::new(workspace_id, *target_virtual_index),
                    active_display.bounds().min,
                    active_display.entity(),
                    true,
                );

                if config.workspace_popup_status() {
                    commands.flash_message(format!("{}", *target_virtual_index + 1), 1.0);
                }
                return;
            };
            index
        }
        Operation::VirtualAdd => {
            let next_virtual_index = rows
                .iter()
                .map(|(_, strip, _)| strip.virtual_index)
                .max()
                .unwrap_or(0)
                + 1;

            commands.spawn_layout_strip(
                LayoutStrip::new(workspace_id, next_virtual_index),
                active_display.bounds().min,
                active_display.entity(),
                true,
            );

            if config.workspace_popup_status() {
                commands.flash_message(format!("{}", next_virtual_index + 1), 1.0);
            }
            return;
        }
        _ => 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(ActiveWorkspaceMarker);

        if config.workspace_popup_status() {
            commands.flash_message(format!("{}", next_virtual_index + 1), 1.0);
        }
    }
    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.
/// Missing destinations are created by `handle_virtual_window_moves`. South at
/// the last row only proceeds when `create_workspace_automatically` is on;
/// numbered targets always may create, row 0 included.
#[instrument(level = Level::DEBUG, skip_all)]
fn move_virtual_workspace_bind(
    mut messages: MessageReader<Event>,
    windows: Windows,
    active_display: ActiveDisplay,
    workspaces: Query<(Entity, &LayoutStrip, Has<ActiveWorkspaceMarker>)>,
    config: Res<Config>,
    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 mut rows = workspaces
        .iter()
        .filter(|(_, strip, _)| strip.id() == active_display.active_strip().id())
        .collect::<Vec<_>>();
    rows.sort_by_key(|(_, strip, _)| strip.virtual_index);

    let current_virtual_index = active_display.active_strip().virtual_index;
    let current_index = rows.iter().position(|(_, _, active)| *active).unwrap_or(0);

    let (target_virtual_index, move_focus) = match operation {
        Operation::VirtualMove(Direction::South | Direction::East, move_focus)
            if active_display.active_strip().len() > 1 =>
        {
            if config.create_workspace_automatically() && current_index + 1 < rows.len() {
                (rows[current_index + 1].1.virtual_index, *move_focus)
            } else {
                (current_virtual_index + 1, *move_focus)
            }
        }
        Operation::VirtualMove(Direction::North | Direction::West, move_focus) => {
            if current_virtual_index == 0 {
                return;
            }
            (current_virtual_index - 1, *move_focus)
        }
        Operation::VirtualMove(Direction::First, move_focus) => {
            if current_virtual_index == 0 {
                return;
            }
            (0, *move_focus)
        }
        Operation::VirtualMove(Direction::Last, move_focus) => {
            let last_virtual_index = rows.last().map_or(0, |(_, strip, _)| strip.virtual_index);
            if current_virtual_index == last_virtual_index {
                return;
            }
            (last_virtual_index, *move_focus)
        }
        Operation::VirtualMoveNumber(target_virtual_index, move_focus) => {
            if *target_virtual_index == current_virtual_index {
                return;
            }
            (*target_virtual_index, *move_focus)
        }
        _ => return,
    };

    if let Ok(mut entity_commands) = commands.get_entity(focused_entity) {
        entity_commands.try_insert(VirtualMoveMarker {
            target_virtual_index,
            move_focus,
        });
    }

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

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

/// The column of `strip` whose window sits nearest the display's horizontal
/// centre. Stands in for the focus a strip never had when it is parked, so
/// that returning to it lands on whatever the user was looking at.
fn column_closest_to_center(
    strip: &LayoutStrip,
    display: &Display,
    windows: &Windows,
) -> Option<Entity> {
    let display_center = display.bounds().center().x;
    strip
        .all_columns()
        .into_iter()
        .filter_map(|candidate| {
            let center = windows.moving_frame(candidate)?.center().x;
            Some((candidate, (center - display_center).abs()))
        })
        .min_by_key(|(_, distance)| *distance)
        .map(|(candidate, _)| candidate)
}

#[instrument(level = Level::DEBUG, skip_all)]
pub(crate) fn show_active_workspace(
    activated: Single<Entity, Added<ActiveWorkspaceMarker>>,
    windows: Windows,
    mut workspaces: RestorableStrips,
    displays: Query<(&Display, Option<&DockPosition>)>,
    focus_markers: Query<Ref<FocusedMarker>>,
    config: Res<Config>,
    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, child, previous, moving) in current_workspace {
        let Ok((active_display, _)) = displays.get(child.parent()) else {
            continue;
        };
        if previous.is_none() {
            let mut focus =
                current_focus.and_then(|(_, entity)| strip.contains(entity).then_some(entity));
            if focus.is_none() {
                focus = column_closest_to_center(strip, active_display, &windows);
                debug!("No previous focus, taking centered one {focus:?}.");
            }

            let origin = match &moving {
                Some(RepositionMarker(destination)) => *destination,
                None => position.0,
            };
            if let Ok(mut entity_commands) = commands.get_entity(entity) {
                entity_commands.try_insert(PreviousStripPosition { origin, focus });
            }
        }

        let bounds = active_display.bounds();

        if let Ok(mut cmd) = commands.get_entity(entity) {
            cmd.try_remove::<Scrolling>()
                .try_remove::<RepositionMarker>()
                .try_remove::<ManualStripOffset>();
        }

        if config.virtual_workspace_animations() {
            commands.reposition_entity(entity, bounds.max - PARKED_STRIP_SLIVER);
        } else {
            position.0 = bounds.max - PARKED_STRIP_SLIVER;
        }
    }

    let Ok((_, mut position, strip, child, 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>();
        }

        // A window of this strip already holding focus is what activated it in
        // the first place - a Cmd-Tab straight into one of its windows. The
        // remembered focus is a fallback for a plain workspace switch, so it
        // must not pull focus away from that window.
        let focused = windows
            .focused()
            .map(|(_, entity)| entity)
            .filter(|entity| strip.contains(*entity));
        let keeps_focus = focused.is_some();

        // Only a focus that arrived with this activation gets the strip moved
        // for it. A window that held focus all along - switching back from an
        // empty workspace, say - keeps the offset the user left behind, even
        // if they had scrolled it out of sight.
        let arriving_focus = focused.filter(|entity| {
            focus_markers
                .get(*entity)
                .is_ok_and(|marker| marker.is_added())
        });

        // The saved origin describes where the strip sat when it was parked,
        // which says nothing about the window that just took focus: it can
        // easily land mostly off-screen. Scroll the strip the minimum amount
        // needed to expose it, the same correction `ensure_visible_in_strip`
        // makes - it cannot do it here, because it skips a strip on the frame
        // its `ActiveWorkspaceMarker` is added.
        let origin = arriving_focus
            .and_then(|focus_entity| {
                let layout = windows.layout_position(focus_entity)?.0;
                let size = windows.size(focus_entity)?;
                let (display, dock) = displays.get(child.parent()).ok()?;
                let viewport = display.actual_display_bounds(dock, &config);
                Some(origin_exposing(layout, size, *origin, viewport))
            })
            .unwrap_or(*origin);

        if config.virtual_workspace_animations() {
            commands.reposition_entity(*activated, origin);
        } else {
            position.0 = origin;
            // The strip's own offset is fixed instantly, but member windows
            // (a lower stack member especially) can still need a correction
            // on a following tick that the ordinary offscreen/parking
            // heuristic in `position_layout_windows` won't recognize as
            // restore-driven — see `SnapStripMarker`.
            spawn_snap_strip_guard(*activated, &mut commands);
        }

        if keeps_focus {
            // The layout of a strip that has just been unparked can still
            // settle over the next frames (widths recomputed, windows the
            // workspace picked up while it was hidden). Re-check the arriving
            // window then: `ensure_visible_in_strip` only scrolls if the slot
            // it ends up in really falls off an edge. That correction fires a
            // tick after this one (its own `is_added` guard skips the
            // activation tick), so it must snap rather than animate when
            // `virtual_workspace_animations` is off — otherwise the strip
            // (and everything in it) visibly slides on top of the restore
            // this function just did instantly.
            if let Some(focus_entity) = arriving_focus {
                commands.ensure_visible_snap(focus_entity, !config.virtual_workspace_animations());
            }
            return;
        }

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

            commands.focus_entity(focus, false);
            commands.trigger(RaiseWindow {
                entity: focus,
                with_strip: true,
            });
        }
    }
}

/// Resolves duplicate `virtual_index` values by reassigning each
/// duplicate to the lowest unused index on its workspace. Triggered by
/// `Added<LayoutStrip>` — the only event that can introduce a duplicate
/// (despawning a strip can leave a gap but never collides). Runs
/// independently of `reap_empty_workspaces` because without it, duplicate
/// indices silently break navigation: `switch_virtual_workspace_bind`
/// sorts rows by `virtual_index` and flashes `next_virtual_index + 1` as
/// the OSD label, so two rows both at 0 mean South moves between them
/// while the OSD stays at "1" and North no-ops at the bottom of the
/// saturating sub.
///
/// Sources of duplicate creation we have to defend against:
/// - `LayoutStrip::fullscreen` pins `virtual_index` to 0 unconditionally.
/// - Restoration trusts whatever the saved state contained.
/// - Races in `handle_virtual_window_moves` between checking the target
///   and spawning a new strip for it.
///
/// Gaps in the index sequence are preserved — only duplicates get
/// renumbered. Single-strip configurations at non-zero indices stay
/// where they are.
fn renumber_virtual_indexes(mut set: RenumberStrips) {
    let affected: HashSet<WorkspaceId> = set.p0().iter().map(LayoutStrip::id).collect();
    if affected.is_empty() {
        return;
    }

    let mut strips = set.p1();
    for workspace_id in affected {
        let mut rows = strips
            .iter_mut()
            .filter(|(_, strip)| strip.id() == workspace_id)
            .collect::<Vec<_>>();
        rows.sort_by_key(|(_, strip)| strip.virtual_index);

        let mut taken: HashSet<u32> = HashSet::new();
        let mut dups: Vec<usize> = Vec::new();
        for (i, (_, strip)) in rows.iter().enumerate() {
            if !taken.insert(strip.virtual_index) {
                dups.push(i);
            }
        }
        if dups.is_empty() {
            continue;
        }

        // Reassign each dup to the lowest free index, growing `taken` as
        // we go so the next dup doesn't pick the same slot.
        for i in dups {
            let mut probe = 0u32;
            while !taken.insert(probe) {
                probe += 1;
            }
            rows[i].1.virtual_index = probe;
        }
    }
}

fn reap_empty_virtual_workspaces(
    changed: Single<Entity, Added<ActiveWorkspaceMarker>>,
    strips: Populated<(Entity, &LayoutStrip)>,
    mut commands: Commands,
) {
    let changed_entity = *changed;
    let Some(workspace_id) = strips.get(changed_entity).ok().map(|(_, strip)| strip.id()) else {
        return;
    };
    debug!("cleaning up virtual workspaces on space {workspace_id}");
    let mut rows = strips
        .iter()
        .filter(|(_, strip)| strip.id() == workspace_id)
        .collect::<Vec<_>>();
    rows.sort_by_key(|(_, strip)| strip.virtual_index);

    if rows.is_empty() {
        return;
    }

    // Do not reap the strip that just became active. Switching/creating onto an
    // empty virtual workspace is intentional (e.g. South auto-create); only
    // empty rows left behind should be removed.
    for (entity, strip) in rows {
        if entity != changed_entity
            && strip.virtual_index > 0
            && strip.len() == 0
            && let Ok(mut entity_commands) = commands.get_entity(entity)
        {
            entity_commands.try_despawn();
        }
    }
}