paneru 0.3.7

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
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
use bevy::ecs::entity::Entity;
use bevy::ecs::hierarchy::{ChildOf, Children};
use bevy::ecs::lifecycle::{Add, Remove};
use bevy::ecs::message::MessageWriter;
use bevy::ecs::observer::On;
use bevy::ecs::query::{Has, With};
use bevy::ecs::system::{Commands, NonSend, NonSendMut, Populated, Query, Res, ResMut, Single};
use bevy::math::IRect;
use notify::event::{DataChange, MetadataKind, ModifyKind};
use notify::{EventKind, Watcher};
use objc2_app_kit::NSScreen;
use objc2_foundation::{NSNumber, NSString, ns_string};
use std::pin::Pin;
use std::sync::atomic::Ordering;
use std::time::Duration;
use tracing::{Level, debug, error, info, instrument, trace, warn};

use super::{
    ActiveDisplayMarker, BProcess, FocusedMarker, FreshMarker, MissionControlActive,
    MouseHeldMarker, NativeFullscreenMarker, RetryFrontSwitch, SpawnWindowTrigger, StrayFocusEvent,
    SystemTheme, Timeout, Unmanaged, WMEventTrigger, WindowDraggedMarker,
};
use crate::commands::ON_FULLSCREEN_SPACE;
use crate::config::{Config, WindowParams};
use crate::ecs::layout::LayoutStrip;
use crate::ecs::params::{ActiveDisplay, ActiveDisplayMut, Configuration, Windows};
use crate::ecs::{
    ActiveWorkspaceMarker, Bounds, LayoutPosition, LocateDockTrigger, Position, Scrolling,
    SendMessageTrigger, WidthRatio, WindowPropoerties, reposition_entity, reshuffle_around,
    resize_entity,
};
use crate::errors::Result;
use crate::events::Event;
use crate::manager::{
    Application, Display, Origin, Process, Size, Window, WindowManager, WindowPadding, irect_from,
};
use crate::platform::{PlatformCallbacks, WinID, WorkspaceId};
use crate::util::symlink_target;

/// Computes the passthrough keybinding set for the given window/app and
/// publishes it to the input thread. Called on focus change and config reload.
fn update_passthrough(window: &Window, app: &Application, config: &Config) {
    let properties = WindowPropoerties::new(app, window, config);
    crate::platform::input::set_focused_passthrough(properties.passthrough_keys());
}

/// Handles mouse moved events.
///
/// If "focus follows mouse" is enabled, this function finds the window under the cursor and
/// focuses it. It also handles child windows like sheets and drawers to ensure the correct
/// window receives focus.
///
/// # Arguments
///
/// * `trigger` - The Bevy event trigger containing the mouse moved event.
/// * `windows` - A query for all windows.
/// * `focused_window` - A query for the currently focused window.
/// * `main_cid` - The main connection ID resource.
/// * `config` - The optional configuration resource.
#[allow(clippy::needless_pass_by_value)]
pub(super) fn mouse_moved_trigger(
    trigger: On<WMEventTrigger>,
    windows: Windows,
    apps: Query<&Application>,
    window_manager: Res<WindowManager>,
    mut config: Configuration,
) {
    let Event::MouseMoved { point } = trigger.event().0 else {
        return;
    };

    if !config.focus_follows_mouse() {
        return;
    }
    if config.mission_control_active() {
        return;
    }
    if config.ffm_flag().is_some() {
        trace!("ffm_window_id > 0");
        return;
    }
    let Ok(window_id) = window_manager.find_window_at_point(&point) else {
        debug!("can not find window at point {point:?}");
        return;
    };
    if windows
        .focused()
        .is_some_and(|(window, _)| window.id() == window_id)
    {
        trace!("allready focused {window_id}");
        return;
    }
    let Some((window, _)) = windows.find(window_id) else {
        trace!("can not find focused window: {window_id}");
        return;
    };

    let child_window = window_manager
        .get_associated_windows(window_id)
        .into_iter()
        .find_map(|child_wid| {
            windows.find(child_wid).and_then(|(window, _)| {
                window
                    .child_role()
                    .inspect_err(|err| {
                        warn!("getting role {window_id}: {err}");
                    })
                    .is_ok_and(|child| child)
                    .then_some(window)
            })
        });
    if let Some(child) = child_window {
        debug!("found child of {}: {}", child.id(), window.id());
    }

    // Do not reshuffle windows due to moved mouse focus.
    config.set_skip_reshuffle(true);
    config.set_ffm_flag(Some(window.id()));

    if let Some(psn) = windows.psn(window.id(), &apps) {
        if let Some((focused_window, _)) = windows.focused()
            && let Some(focused_psn) = windows.psn(focused_window.id(), &apps)
        {
            window.focus_without_raise(psn, focused_window, focused_psn);
        } else {
            window.focus_with_raise(psn);
        }
    }
}

/// Handles mouse down events.
///
/// This function finds the window at the click point. If the window is not fully visible,
/// it triggers a reshuffle to expose it.
///
/// # Arguments
///
/// * `trigger` - The Bevy event trigger containing the mouse down event.
/// * `windows` - A query for all windows.
/// * `active_display` - A query for the active display.
/// * `main_cid` - The main connection ID resource.
/// * `mission_control_active` - A resource indicating if Mission Control is active.
/// * `commands` - Bevy commands to trigger a reshuffle.
#[allow(clippy::needless_pass_by_value, clippy::too_many_arguments)]
pub(super) fn mouse_down_trigger(
    trigger: On<WMEventTrigger>,
    windows: Windows,
    active_workspace: Query<(Entity, Option<&Scrolling>), With<ActiveWorkspaceMarker>>,
    window_manager: Res<WindowManager>,
    mission_control_active: Res<MissionControlActive>,
    config: Configuration,
    mouse_held: Query<Entity, With<MouseHeldMarker>>,
    mut commands: Commands,
) {
    let Event::MouseDown { point } = trigger.event().0 else {
        return;
    };
    if mission_control_active.0 {
        return;
    }
    trace!("{point:?}");

    let Some((_, entity)) = window_manager
        .find_window_at_point(&point)
        .ok()
        .and_then(|window_id| windows.find(window_id))
    else {
        return;
    };

    // Stop any ongoing scroll.
    for (entity, scroll) in active_workspace {
        if scroll.is_some() {
            commands.entity(entity).try_remove::<Scrolling>();
        }
    }

    // Clean up any stale marker from a previous click.
    for held in &mouse_held {
        commands.entity(held).despawn();
    }

    if config.window_hidden_ratio() >= 1.0 {
        // At max hidden ratio, never reshuffle on click.
    } else {
        // Defer reshuffle until mouse-up so the window doesn't shift
        // mid-click. The Timeout auto-despawns if mouse-up is lost.
        let timeout = Timeout::new(Duration::from_secs(5), None);
        commands.spawn((MouseHeldMarker(entity), timeout));
    }
}

/// Handles mouse-up events. Triggers the deferred reshuffle so the clicked
/// window slides into view after the user releases the button.
#[allow(clippy::needless_pass_by_value)]
pub(super) fn mouse_up_trigger(
    trigger: On<WMEventTrigger>,
    mouse_held: Query<(Entity, &MouseHeldMarker)>,
    mut commands: Commands,
) {
    let Event::MouseUp { .. } = trigger.event().0 else {
        return;
    };
    for (held_entity, marker) in &mouse_held {
        reshuffle_around(marker.0, &mut commands);
        commands.entity(held_entity).despawn();
    }
}

/// Handles mouse dragged events.
///
/// This function is currently a placeholder and only logs the drag event.
///
/// # Arguments
///
/// * `trigger` - The Bevy event trigger containing the mouse dragged event.
/// * `mission_control_active` - A resource indicating if Mission Control is active.
#[allow(clippy::needless_pass_by_value)]
pub(super) fn mouse_dragged_trigger(
    trigger: On<WMEventTrigger>,
    active_display: ActiveDisplay,
    windows: Windows,
    mut drag_marker: Query<(&mut Timeout, &mut WindowDraggedMarker)>,
    window_manager: Res<WindowManager>,
    mission_control_active: Res<MissionControlActive>,
    mut commands: Commands,
) {
    const DRAG_MARKER_TIMEOUT_MS: u64 = 1000;
    let Event::MouseDragged { point } = trigger.event().0 else {
        return;
    };
    if mission_control_active.0 {
        return;
    }

    let Some((window, entity)) = window_manager
        .0
        .find_window_at_point(&point)
        .ok()
        .and_then(|window_id| windows.find(window_id))
    else {
        return;
    };

    if let Ok((mut timeout, mut marker)) = drag_marker.single_mut() {
        // Change the current marker contents and refresh the timer.
        if entity != marker.entity {
            let marker = marker.as_mut();
            marker.entity = entity;
            marker.display_id = active_display.id();
            timeout.timer.reset();
        }
    } else {
        debug!(
            "Adding a drag marker ({entity}, {}) to window id {}.",
            active_display.id(),
            window.id(),
        );
        let timeout = Timeout::new(Duration::from_millis(DRAG_MARKER_TIMEOUT_MS), None);
        commands.spawn((
            timeout,
            WindowDraggedMarker {
                entity,
                display_id: active_display.id(),
            },
        ));
    }
}

fn windows_not_in_strip<F: Fn(WinID) -> Option<Entity>>(
    workspace_id: WorkspaceId,
    find_window: F,
    strip: &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 {
                match find_window(id) {
                    Some(entity) if strip.index_of(entity).is_err() => moved.push(entity),
                    Some(_) => {}
                    None => unresolved.push(id),
                }
            }
            (moved, unresolved)
        })
}

#[allow(clippy::needless_pass_by_value)]
pub(super) fn workspace_change_trigger(
    trigger: On<WMEventTrigger>,
    active_display: Single<&Display, With<ActiveDisplayMarker>>,
    mut workspaces: Query<(&mut LayoutStrip, Entity, Has<ActiveWorkspaceMarker>)>,
    windows: Windows,
    fs_query: Query<&NativeFullscreenMarker>,
    window_manager: Res<WindowManager>,
    mut commands: Commands,
) {
    let Event::SpaceChanged = trigger.event().0 else {
        return;
    };

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

    let fullscreen = window_manager.is_fullscreen_space(active_display.id());
    let was_fullscreen = ON_FULLSCREEN_SPACE.swap(fullscreen, Ordering::Relaxed);
    debug!("workspace_change: space={workspace_id} fullscreen={fullscreen}");

    // Entering fullscreen → remove the focused window from the strip so there
    // is no layout gap and mark it with NativeFullscreenMarker.
    // Guard: the focused entity must not already carry the marker (which means
    // we're just switching TO an existing fullscreen space, not a new one).
    if !was_fullscreen
        && fullscreen
        && let Some((_, entity)) = windows.focused()
        && !fs_query.contains(entity)
        && let Some((mut strip, _, _)) = workspaces.iter_mut().find(|(_, _, active)| *active)
    {
        let idx = strip.index_of(entity).ok().unwrap_or(strip.len());
        strip.remove(entity);
        let next_order = fs_query.iter().map(|m| m.order + 1).max().unwrap_or(0);
        debug!("entering fullscreen: removed {entity} (idx={idx}), order={next_order}");
        commands
            .entity(entity)
            .insert(NativeFullscreenMarker { order: next_order });
        // Reshuffle around nearest remaining window to close the gap.
        if let Some(target) = strip
            .get(idx.saturating_sub(1))
            .ok()
            .and_then(|col| col.top())
        {
            reshuffle_around(target, &mut commands);
        }
    }

    // Exiting fullscreen → re-insert the window at the end of the strip.
    if was_fullscreen
        && !fullscreen
        && let Some((_, entity)) = windows.focused()
        && fs_query.contains(entity)
        && let Some((mut strip, _, _)) = workspaces.iter_mut().find(|(_, _, active)| *active)
    {
        let end = strip.len();
        strip.insert_at(end, entity);
        debug!("exiting fullscreen: re-inserted {entity} at end of strip");
        commands.entity(entity).remove::<NativeFullscreenMarker>();
        reshuffle_around(entity, &mut commands);
    }

    // Dynamic fullscreen spaces (created by macOS when a window goes fullscreen)
    // have no LayoutStrip entity.  Only remove the old ActiveWorkspaceMarker when
    // a new strip exists to receive it, so that ActiveDisplay keeps resolving and
    // command systems can raise a tiled window to switch back.
    let has_matching_strip = workspaces
        .iter()
        .any(|(strip, _, _)| strip.id() == workspace_id);

    for (strip, entity, active) in workspaces {
        if active && strip.id() != workspace_id && has_matching_strip {
            debug!("Workspace id {} no longer active", strip.id());
            commands
                .entity(entity)
                .try_remove::<ActiveWorkspaceMarker>();
        }
        if !active && strip.id() == workspace_id {
            debug!("Workspace id {} is active", strip.id());
            commands.entity(entity).try_insert(ActiveWorkspaceMarker);
        }
    }

    // let timeout = Timeout::new(
    //     Duration::from_millis(WORKSPACE_CHANGE_TIMEOUT),
    //     Some("marker despawned".to_string()),
    // );
    // commands.spawn((SpaceRecentlyChanged, timeout));
}

#[allow(clippy::needless_pass_by_value, clippy::type_complexity)]
#[instrument(level = Level::DEBUG, skip_all)]
pub(super) fn active_workspace_trigger(
    trigger: On<Add, ActiveWorkspaceMarker>,
    windows: Windows,
    mut workspaces: Query<(&mut LayoutStrip, &ChildOf), With<ChildOf>>,
    active_display: Single<(Entity, &Display), With<ActiveDisplayMarker>>,
    apps: Query<&mut Application>,
    window_manager: Res<WindowManager>,
    mut commands: Commands,
) {
    let Ok((active_strip, _)) = workspaces.get(trigger.entity) else {
        return;
    };
    let workspace_id = active_strip.id();
    debug!("workspace {workspace_id}");

    let find_window = |window_id| windows.find_managed(window_id).map(|(_, entity)| entity);
    let Ok((moved_windows, unresolved)) =
        windows_not_in_strip(workspace_id, find_window, active_strip, &window_manager).inspect_err(
            |err| {
                warn!("unable to get windows in the current workspace: {err}");
            },
        )
    else {
        return;
    };

    // 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.
    if !unresolved.is_empty() {
        let mut retry_windows = Vec::new();
        for app in &apps {
            for window in app.window_list() {
                if unresolved.contains(&window.id()) {
                    retry_windows.push(window);
                }
            }
        }
        if !retry_windows.is_empty() {
            debug!(
                "retrying unresolved windows: {}",
                retry_windows
                    .iter()
                    .map(|window| format!("{}", window.id()))
                    .collect::<Vec<_>>()
                    .join(" ")
            );
            commands.trigger(SpawnWindowTrigger(retry_windows));
        }
    }

    let had_moved_windows = !moved_windows.is_empty();
    for entity in moved_windows {
        debug!("Window {entity} moved to workspace {workspace_id}.");

        workspaces.iter_mut().for_each(|(mut strip, child)| {
            strip.remove(entity);
            if strip.id() == workspace_id && child.parent() == active_display.0 {
                strip.append(entity);
            }
        });
        reshuffle_around(entity, &mut commands);
    }

    // Always reshuffle on workspace activation so that windows are
    // re-laid-out after returning from a different space (e.g. native
    // fullscreen) where they may have been positioned with stale data.
    // Prefer the focused window so the viewport centres on what the user
    // was looking at; fall back to the first column.
    if !had_moved_windows {
        let focused_entity = windows.focused().map(|(_, entity)| entity).filter(|e| {
            workspaces
                .get(trigger.entity)
                .is_ok_and(|(strip, _)| strip.index_of(*e).is_ok())
        });
        let fallback = || {
            workspaces
                .get(trigger.entity)
                .ok()
                .and_then(|(strip, _)| strip.get(0).ok())
                .and_then(|col| col.top())
        };
        if let Some(entity) = focused_entity.or_else(fallback) {
            reshuffle_around(entity, &mut commands);
        }
    }
}

/// Handles display change events.
///
/// When the active display or space changes, this function ensures that the window manager's
/// internal state is updated. It marks the new active display with `FocusedMarker` and moves
/// the focused window to the correct `LayoutStrip` if it has been moved to a different display
/// or workspace.
///
/// # Arguments
///
/// * `trigger` - The Bevy event trigger containing the display change event.
/// * `focused_window` - A query for the currently focused window.
/// * `displays` - A query for all displays, with their focus state.
/// * `main_cid` - The main connection ID resource.
/// * `commands` - Bevy commands to manage components and trigger events.
#[allow(clippy::needless_pass_by_value)]
pub(super) fn display_change_trigger(
    trigger: On<WMEventTrigger>,
    displays: Query<(&Display, Entity, Has<ActiveDisplayMarker>)>,
    window_manager: Res<WindowManager>,
    mut commands: Commands,
) {
    let Event::DisplayChanged = trigger.event().0 else {
        return;
    };

    let Ok(active_id) = window_manager.active_display_id() else {
        error!("Unable to get active display id!");
        return;
    };

    for (display, entity, focused) in displays {
        let display_id = display.id();
        if focused && display_id != active_id {
            debug!("Display id {display_id} no longer active");
            if let Ok(mut cmd) = commands.get_entity(entity) {
                cmd.try_remove::<ActiveDisplayMarker>();
            }
        }
        if !focused && display_id == active_id {
            debug!("Display id {display_id} is active");
            if let Ok(mut cmd) = commands.get_entity(entity) {
                cmd.try_insert(ActiveDisplayMarker);
            }
        }
    }
    commands.trigger(WMEventTrigger(Event::SpaceChanged));
}

/// Handles the event when an application switches to the front. It updates the focused window and PSN.
///
/// # Arguments
///
/// * `trigger` - The Bevy event trigger containing the application front switched event.
/// * `processes` - A query for all processes with their children.
/// * `applications` - A query for all applications.
/// * `focused_window` - A query for the focused window.
/// * `focus_follows_mouse_id` - The resource to track focus follows mouse window ID.
/// * `commands` - Bevy commands to trigger events and manage components.
#[allow(clippy::needless_pass_by_value)]
pub(super) fn front_switched_trigger(
    trigger: On<WMEventTrigger>,
    processes: Query<(&BProcess, &Children)>,
    applications: Query<&Application>,
    window_manager: Res<WindowManager>,
    mut config: Configuration,
    mut commands: Commands,
) {
    const FRONT_SWITCH_RETRY_SEC: u64 = 2;
    let Event::ApplicationFrontSwitched { ref psn } = trigger.event().0 else {
        return;
    };
    let Some((BProcess(process), children)) =
        processes.iter().find(|process| &process.0.psn() == psn)
    else {
        error!("Unable to find process with PSN {psn:?}");
        return;
    };

    if children.len() > 1 {
        warn!("Multiple apps registered to process '{}'.", process.name());
    }
    let Some(&app_entity) = children.first() else {
        error!("No application for process '{}'.", process.name());
        return;
    };
    let Some(app) = applications.get(app_entity).ok() else {
        error!("No application for process '{}'.", process.name());
        return;
    };
    debug!("front switching process: {}", process.name());

    if let Ok(focused_id) = app.focused_window_id().inspect_err(|err| {
        warn!("can not get current focus: {err}");
    }) {
        if let Some(point) = window_manager.cursor_position()
            && window_manager
                .find_window_at_point(&point)
                .is_ok_and(|window_id| window_id != focused_id)
        {
            // Window got focus without mouse movement - probably with a Cmd-Tab.
            // If so, bring it into view.
            config.set_skip_reshuffle(false);
            config.set_ffm_flag(None);
        }
        commands.trigger(WMEventTrigger(Event::WindowFocused {
            window_id: focused_id,
        }));
    } else {
        // Transient AX error (e.g. kAXErrorCannotComplete during app transitions).
        // Schedule a retry to query the focused window once the app is ready.
        let timeout = Timeout::new(
            Duration::from_secs(FRONT_SWITCH_RETRY_SEC),
            Some(format!(
                "Front switch retry for '{}' timed out.",
                process.name()
            )),
        );
        commands.spawn((timeout, RetryFrontSwitch(app_entity)));
    }
}

#[allow(clippy::needless_pass_by_value)]
pub(super) fn center_mouse_trigger(
    trigger: On<Add, FocusedMarker>,
    windows: Windows,
    config: Configuration,
    active_display: ActiveDisplay,
    window_manager: Res<WindowManager>,
    active_workspace: Query<&Scrolling, With<ActiveWorkspaceMarker>>,
) {
    let entity = trigger.event().entity;
    let Some(window) = windows.get(entity) else {
        return;
    };
    if active_workspace
        .iter()
        .next()
        .is_some_and(|scrolling| scrolling.is_user_swiping)
    {
        debug!("Suppressing center mouse due to a swipe");
        return;
    }

    if config.mouse_follows_focus()
        && !config.skip_reshuffle()
        && config.ffm_flag().is_none_or(|id| id != window.id())
        && let Some(mut frame) = windows.moving_frame(entity)
    {
        let display_bounds = active_display.bounds();
        // Expose the window if it's offscreen.
        let size = frame.size();
        frame.min = frame
            .min
            .clamp(display_bounds.min, display_bounds.max - size);
        frame.max = frame.min + size;

        let origin = frame.center() - display_bounds.min;
        debug!("centering on {} {origin}", window.id());
        window_manager.warp_mouse(origin);
    }
}

#[allow(clippy::needless_pass_by_value)]
pub(super) fn dim_window_trigger(
    trigger: On<Add, FocusedMarker>,
    windows: Windows,
    window_manager: Res<WindowManager>,
    config: Res<Config>,
    theme: Option<Res<SystemTheme>>,
) {
    let Some(window) = windows.get(trigger.event().entity) else {
        return;
    };

    let dark = theme.is_some_and(|theme| theme.is_dark);
    if config.window_dim_ratio(dark).is_some() {
        window_manager.dim_windows(&[window.id()], 0.0);
    }
}

#[allow(clippy::needless_pass_by_value)]
pub(super) fn dim_remove_window_trigger(
    trigger: On<Remove, FocusedMarker>,
    windows: Windows,
    window_manager: Res<WindowManager>,
    config: Res<Config>,
    theme: Option<Res<SystemTheme>>,
) {
    let Some(window) = windows.get(trigger.event().entity) else {
        return;
    };

    let dark = theme.is_some_and(|theme| theme.is_dark);
    if let Some(dim_ratio) = config.window_dim_ratio(dark) {
        window_manager.dim_windows(&[window.id()], dim_ratio);
    }
}

#[allow(clippy::needless_pass_by_value)]
pub(super) fn theme_change_trigger(
    trigger: On<WMEventTrigger>,
    windows: Windows,
    window_manager: Res<WindowManager>,
    config: Res<Config>,
    mut theme: Option<ResMut<SystemTheme>>,
) {
    let Event::ThemeChanged = trigger.event().0 else {
        return;
    };
    let Some(ref mut theme) = theme else {
        return;
    };

    let is_dark = crate::util::is_dark_mode();
    if theme.is_dark == is_dark {
        return;
    }
    theme.is_dark = is_dark;
    info!("System theme changed: dark_mode={is_dark}");

    let Some(dim_ratio) = config.window_dim_ratio(is_dark) else {
        return;
    };

    // Re-apply dimming to all windows that are NOT focused.
    let focused_id = windows.focused().map(|(window, _)| window.id());
    let windows_to_dim: Vec<WinID> = windows
        .iter()
        .filter(|(window, _)| Some(window.id()) != focused_id)
        .map(|(window, _)| window.id())
        .collect();

    if !windows_to_dim.is_empty() {
        window_manager.dim_windows(&windows_to_dim, dim_ratio);
    }
}

/// Handles the event when a window gains focus. It updates the focused window, PSN, and reshuffles windows.
/// It also centers the mouse on the focused window if focus-follows-mouse is enabled.
///
/// # Arguments
///
/// * `trigger` - The Bevy event trigger containing the window focused event.
/// * `applications` - A query for all applications.
/// * `windows` - A query for all windows with their parent and focus state.
/// * `main_cid` - The main connection ID resource.
/// * `focus_follows_mouse_id` - The resource to track focus follows mouse window ID.
/// * `skip_reshuffle` - The resource to indicate if reshuffling should be skipped.
/// * `commands` - Bevy commands to manage components and trigger events.
#[allow(clippy::needless_pass_by_value)]
#[instrument(level = Level::DEBUG, skip_all)]
pub(super) fn window_focused_trigger(
    trigger: On<WMEventTrigger>,
    applications: Query<&Application>,
    windows: Windows,
    mut active_display: ActiveDisplayMut,
    mut config: Configuration,
    mouse_held: Query<&MouseHeldMarker>,
    mut commands: Commands,
) {
    const STRAY_FOCUS_RETRY_SEC: u64 = 2;

    let Event::WindowFocused { window_id } = trigger.event().0 else {
        return;
    };

    if let Some((window, _)) = windows.focused()
        && window.id() == window_id
    {
        return;
    }

    let Some((window, entity, parent)) = windows.find_parent(window_id) else {
        let timeout = Timeout::new(Duration::from_secs(STRAY_FOCUS_RETRY_SEC), None);
        commands.spawn((timeout, StrayFocusEvent(window_id)));
        return;
    };

    let Ok(app) = applications.get(parent) else {
        warn!("Unable to get parent for window {}.", window.id());
        return;
    };

    // Guard against stale focus events. Without these checks, delayed
    // events (e.g. from RetryFrontSwitch or dont_focus re-assertions)
    // can pull FocusedMarker back to an old window after focus has moved on.
    //
    // 1. Cross-app: skip if the window's app is no longer frontmost.
    // 2. Same-app: skip if the app's current focused window differs from
    //    this event's window_id (the event is outdated).
    if !app.is_frontmost() {
        return;
    }
    if app.focused_window_id().is_ok_and(|id| id != window_id) {
        return;
    }

    // Handle tab switching: if the focused window is a tab, make it the leader.
    let layout_strip = active_display.active_strip();
    if let Ok(index) = layout_strip.index_of(entity)
        && let Some(column) = layout_strip.get_column_mut(index)
    {
        column.move_to_front(entity);
    }

    let focus = windows.focused().map(|(_, entity)| entity);
    for (window, entity) in windows.iter() {
        let Ok(mut cmd) = commands.get_entity(entity) else {
            continue;
        };
        let focused = focus.is_some_and(|focus| entity == focus);
        if focused && window.id() != window_id {
            cmd.try_remove::<FocusedMarker>();
        }
        if !focused && window.id() == window_id {
            cmd.try_insert(FocusedMarker);
        }
    }

    debug!("focused window id {}", window.id());

    update_passthrough(window, app, config.config());

    commands.entity(entity).try_insert(FocusedMarker);

    if !(config.skip_reshuffle() || config.initializing() || !mouse_held.is_empty()) {
        if config.auto_center()
            && let Some((_, _, None)) = windows.get_managed(entity)
            && let Some(size) = windows.size(entity)
            && let Some(mut origin) = windows.origin(entity)
        {
            let center = active_display.bounds().center();
            origin.x = center.x - size.x / 2;
            reposition_entity(entity, origin, &mut commands);
        }
        reshuffle_around(entity, &mut commands);
    }

    // Check if the reshuffle was caused by a keyboard switch or mouse move.
    // Skip reshuffle if caused by mouse - because then it won't center.
    if config.ffm_flag().is_none() {
        config.set_skip_reshuffle(false);
    }
    config.set_ffm_flag(None);
}

/// Handles Mission Control events, updating the `MissionControlActive` resource.
///
/// # Arguments
///
/// * `trigger` - The Bevy event trigger containing the Mission Control event.
/// * `mission_control_active` - The `MissionControlActive` resource.
#[allow(clippy::needless_pass_by_value)]
pub(super) fn mission_control_trigger(
    trigger: On<WMEventTrigger>,
    mut mission_control_active: ResMut<MissionControlActive>,
    active_workspace: Query<(Entity, Option<&Scrolling>), With<ActiveWorkspaceMarker>>,
    mut commands: Commands,
) {
    match trigger.event().0 {
        Event::MissionControlShowAllWindows
        | Event::MissionControlShowFrontWindows
        | Event::MissionControlShowDesktop => {
            mission_control_active.as_mut().0 = true;
            for (entity, scroll) in active_workspace {
                if scroll.is_some() {
                    commands.entity(entity).try_remove::<Scrolling>();
                }
            }
        }
        Event::MissionControlExit => {
            mission_control_active.as_mut().0 = false;
        }
        _ => (),
    }
}

/// Dispatches process-related messages, such as application launch and termination.
///
/// # Arguments
///
/// * `trigger` - The Bevy event trigger containing the application event.
/// * `processes` - A query for all processes.
/// * `commands` - Bevy commands to spawn or despawn entities.
#[allow(clippy::needless_pass_by_value)]
pub(super) fn application_event_trigger(
    trigger: On<WMEventTrigger>,
    processes: Query<(&BProcess, Entity)>,
    mut commands: Commands,
) {
    const PROCESS_READY_TIMEOUT_SEC: u64 = 5;
    let find_process = |psn| {
        processes
            .iter()
            .find(|(BProcess(process), _)| &process.psn() == psn)
    };

    match &trigger.event().0 {
        Event::ApplicationLaunched { psn, observer } => {
            if find_process(psn).is_none() {
                let process: BProcess = Process::new(psn, observer.clone()).into();
                let timeout = Timeout::new(
                    Duration::from_secs(PROCESS_READY_TIMEOUT_SEC),
                    Some(format!(
                        "Process '{}' did not become ready in {PROCESS_READY_TIMEOUT_SEC}s.",
                        process.name()
                    )),
                );
                commands.spawn((FreshMarker, timeout, process));
            }
        }

        Event::ApplicationTerminated { psn } => {
            if let Some((_, entity)) = find_process(psn) {
                commands.entity(entity).despawn();
            }
        }
        _ => (),
    }
}

/// Dispatches application-related messages, such as window creation, destruction, and resizing.
///
/// # Arguments
///
/// * `trigger` - The Bevy event trigger containing the window event.
/// * `windows` - A query for all windows.
/// * `displays` - A query for the active display.
/// * `main_cid` - The main connection ID resource.
/// * `commands` - Bevy commands to spawn or despawn entities.
#[allow(clippy::needless_pass_by_value)]
pub(super) fn dispatch_application_messages(
    trigger: On<WMEventTrigger>,
    windows: Windows,
    applications: Query<(&Application, &Children)>,
    unmanaged_query: Query<&Unmanaged>,
    mut commands: Commands,
) {
    let find_window = |window_id| windows.find(window_id);

    match &trigger.event().0 {
        Event::WindowMinimized { window_id } => {
            if let Some((_, entity)) = find_window(*window_id) {
                commands.entity(entity).try_insert(Unmanaged::Minimized);
            }
        }

        Event::WindowDeminimized { window_id } => {
            if let Some((_, entity)) = find_window(*window_id)
                && matches!(unmanaged_query.get(entity), Ok(Unmanaged::Minimized))
            {
                commands.entity(entity).try_remove::<Unmanaged>();
            }
        }

        Event::ApplicationHidden { pid } => {
            let Some((_, children)) = applications.iter().find(|(app, _)| app.pid() == *pid) else {
                warn!("Unable to find with pid {pid}");
                return;
            };
            for entity in children {
                // Only hide windows that are currently managed (no Unmanaged component).
                // Preserve existing Floating, Minimized, and Hidden states.
                if unmanaged_query.get(*entity).is_err() {
                    commands.entity(*entity).try_insert(Unmanaged::Hidden);
                }
            }
        }

        Event::ApplicationVisible { pid } => {
            let Some((_, children)) = applications.iter().find(|(app, _)| app.pid() == *pid) else {
                warn!("Unable to find application with pid {pid}");
                return;
            };
            for entity in children {
                // Only restore windows that were hidden by the app hide/show cycle.
                // Preserve Floating and Minimized states.
                if matches!(unmanaged_query.get(*entity), Ok(Unmanaged::Hidden)) {
                    commands.entity(*entity).try_remove::<Unmanaged>();
                }
            }
        }
        _ => (),
    }
}

#[allow(clippy::needless_pass_by_value)]
#[instrument(level = Level::DEBUG, skip_all, fields(trigger))]
pub(super) fn window_unmanaged_trigger(
    trigger: On<Add, Unmanaged>,
    windows: Windows,
    apps: Query<(Entity, &Application)>,
    mut active_display: ActiveDisplayMut,
    config: Configuration,
    mut commands: Commands,
) {
    const UNMANAGED_MAX_SCREEN_RATIO_NUM: i32 = 4;
    const UNMANAGED_MAX_SCREEN_RATIO_DEN: i32 = 5;
    const UNMANAGED_POP_OFFSET: i32 = 32;

    fn clamp_origin_to_bounds(origin: IRect, size: Size, bounds: IRect) -> IRect {
        let max = (bounds.max - size).max(bounds.min);
        let min = origin.min.clamp(bounds.min, max);
        IRect::from_corners(min, min + size)
    }

    fn offset_frame_within_bounds(frame: IRect, bounds: IRect, offset: i32) -> IRect {
        let candidates = [
            (offset, offset),
            (offset, -offset),
            (-offset, offset),
            (-offset, -offset),
            (offset, 0),
            (-offset, 0),
            (0, offset),
            (0, -offset),
        ];

        for (dx, dy) in candidates {
            let moved = IRect::from_corners(
                Origin::new(frame.min.x + dx, frame.min.y + dy),
                Origin::new(frame.max.x + dx, frame.max.y + dy),
            );
            if moved.min.x >= bounds.min.x
                && moved.max.x <= bounds.max.x
                && moved.min.y >= bounds.min.y
                && moved.max.y <= bounds.max.y
            {
                return moved;
            }
        }

        frame
    }

    let entity = trigger.event().entity;
    let Some((_, _, Some(Unmanaged::Floating))) = windows.get_managed(entity) else {
        return;
    };
    let display_bounds = active_display
        .display()
        .actual_display_bounds(active_display.dock(), config.config());
    let active_strip = active_display.active_strip();

    debug!("Entity {entity} is floating.");

    let Some((window, frame)) = windows.get(entity).zip(windows.frame(entity)) else {
        return;
    };
    let Some((_, app)) = windows
        .find_parent(window.id())
        .and_then(|(_, _, parent)| apps.get(parent).ok())
    else {
        return;
    };

    let properties = WindowPropoerties::new(app, window, config.config());

    if let Some((rx, ry, rw, rh)) = properties.grid_ratios() {
        let x = (f64::from(display_bounds.width()) * rx) as i32;
        let y = (f64::from(display_bounds.height()) * ry) as i32;
        let w = (f64::from(display_bounds.width()) * rw) as i32;
        let h = (f64::from(display_bounds.height()) * rh) as i32;
        reposition_entity(entity, Origin::new(x, y), &mut commands);
        resize_entity(entity, Size::new(w, h), &mut commands);
    } else {
        let max_width = display_bounds.width() * UNMANAGED_MAX_SCREEN_RATIO_NUM
            / UNMANAGED_MAX_SCREEN_RATIO_DEN;
        let max_height = display_bounds.height() * UNMANAGED_MAX_SCREEN_RATIO_NUM
            / UNMANAGED_MAX_SCREEN_RATIO_DEN;
        let new_width = frame.width().min(max_width);
        let new_height = frame.height().min(max_height);

        let mut target_frame =
            IRect::from_corners(frame.min, frame.min + Origin::new(new_width, new_height));
        target_frame = clamp_origin_to_bounds(target_frame, target_frame.size(), display_bounds);
        target_frame =
            offset_frame_within_bounds(target_frame, display_bounds, UNMANAGED_POP_OFFSET);

        if target_frame.size() != frame.size() {
            resize_entity(
                entity,
                Size::new(target_frame.width(), target_frame.height()),
                &mut commands,
            );
        }
        if target_frame.min != frame.min {
            reposition_entity(entity, target_frame.min, &mut commands);
        }
    }

    if let Some(neighbour) = active_strip
        .left_neighbour(entity)
        .or_else(|| active_strip.right_neighbour(entity))
    {
        debug!("Reshuffling around its neighbour {neighbour}.");
        reshuffle_around(neighbour, &mut commands);
    }
    active_strip.remove(entity);
}

#[allow(clippy::needless_pass_by_value)]
#[instrument(level = Level::DEBUG, skip_all, fields(trigger))]
pub(super) fn window_minimized_trigger(
    trigger: On<Add, Unmanaged>,
    windows: Windows,
    mut active_display: ActiveDisplayMut,
    mut config: Configuration,
    mut commands: Commands,
) {
    let entity = trigger.event().entity;
    if let Some((_, _, Some(Unmanaged::Minimized | Unmanaged::Hidden))) =
        windows.get_managed(entity)
    {
        debug!("Entity {entity} is minimized or hidden.");
        let display_bounds = active_display.bounds();
        let active_strip = active_display.active_strip();
        give_away_focus(
            entity,
            &windows,
            active_strip,
            &display_bounds,
            &mut config,
            &mut commands,
        );
        active_strip.remove(entity);
    }
}

#[allow(clippy::needless_pass_by_value)]
pub(super) fn window_managed_trigger(
    trigger: On<Remove, Unmanaged>,
    mut active_display: ActiveDisplayMut,
    windows: Windows,
    apps: Query<(Entity, &Application)>,
    config: Configuration,
    mut commands: Commands,
) {
    let entity = trigger.event().entity;
    debug!("Entity {entity} is managed again.");

    if let Some(window) = windows.get(entity)
        && let Some((_, app)) = windows
            .find_parent(window.id())
            .and_then(|(_, _, parent)| apps.get(parent).ok())
    {
        let properties = WindowPropoerties::new(app, window, config.config());
        if properties.floating() {
            return;
        }
    }

    active_display.active_strip().append(entity);
    reshuffle_around(entity, &mut commands);
}

/// Handles the event when a window is destroyed. The windows itself is not removed from the layout
/// strip. This happens in the On<Remove, Window> trigger.
///
/// # Arguments
///
/// * `trigger` - The Bevy event trigger containing the ID of the destroyed window.
/// * `windows` - A query for all windows with their parent.
/// * `apps` - A query for all applications.
/// * `displays` - A query for all displays.
/// * `commands` - Bevy commands to despawn entities and trigger events.
#[allow(clippy::needless_pass_by_value)]
#[instrument(level = Level::DEBUG, skip_all)]
pub(super) fn window_destroyed_trigger(
    trigger: On<WMEventTrigger>,
    windows: Windows,
    active_display: ActiveDisplay,
    mut apps: Query<&mut Application>,
    mut config: Configuration,
    mut commands: Commands,
) {
    let Event::WindowDestroyed { window_id } = trigger.event().0 else {
        return;
    };

    let Some((window, entity, parent)) = windows.find_parent(window_id) else {
        error!("Trying to destroy non-existing window {window_id}.");
        return;
    };

    let Ok(mut app) = apps.get_mut(parent) else {
        error!("Window {} has no parent!", window.id());
        return;
    };
    app.unobserve_window(window);

    give_away_focus(
        entity,
        &windows,
        active_display.active_strip(),
        &active_display.bounds(),
        &mut config,
        &mut commands,
    );

    // NOTE: If the entity had an Unmanaged marker, despawning it will cause it to be re-inserted
    // into the strip again. Therefore we do it just before despawning the entity itself, so it
    // then can be properly removed again in the main entity despawn trigger.
    commands.entity(entity).remove::<Unmanaged>().despawn();

    // The window entity will be removed from the layout strip in the On<Remove> trigger.
}

/// Moves the focus away to a neighbour window.
fn give_away_focus(
    entity: Entity,
    windows: &Windows,
    active_strip: &LayoutStrip,
    viewport: &IRect,
    config: &mut Configuration,
    commands: &mut Commands,
) {
    if active_strip.tabbed(entity) {
        // Do not give away focus for tabbed windows.
        // Remaining tab gets the focus.
        return;
    }
    let display_center = viewport.center().x;
    let closest = active_strip
        .all_columns()
        .into_iter()
        .filter_map(|candidate| {
            if candidate == entity {
                return None;
            }
            let center = windows.moving_frame(candidate)?.center().x;
            let distance = (center - display_center).abs();
            Some((candidate, distance))
        })
        .min_by_key(|(_, dist)| *dist);

    if let Some((neighbour, _)) = closest
        && let Some(window) = windows.get(neighbour)
    {
        let window_id = window.id();

        config.set_ffm_flag(None);
        commands.trigger(WMEventTrigger(Event::WindowFocused { window_id }));
        reshuffle_around(neighbour, commands);
    }
}

/// Handles the event when a new window is created. It adds the window to the manager and sets focus.
///
/// # Arguments
///
/// * `trigger` - The Bevy event trigger containing the new windows.
/// * `windows` - A query for all windows.
/// * `apps` - A query for all applications.
/// * `active_display` - A query for the active display.
/// * `main_cid` - The main connection ID resource.
/// * `commands` - Bevy commands to manage components and trigger events.
#[allow(clippy::needless_pass_by_value)]
#[instrument(level = Level::DEBUG, skip_all)]
pub(super) fn spawn_window_trigger(
    mut trigger: On<SpawnWindowTrigger>,
    windows: Windows,
    mut apps: Query<(Entity, &mut Application)>,
    mut active_display: ActiveDisplayMut,
    config: Configuration,
    mut commands: Commands,
) {
    let new_windows = &mut trigger.event_mut().0;

    while let Some(mut window) = new_windows.pop() {
        let window_id = window.id();

        if windows.find(window_id).is_some() {
            continue;
        }

        let Ok(pid) = window.pid() else {
            trace!("Unable to get window pid for {window_id}");
            continue;
        };
        let Some((app_entity, mut app)) = apps.iter_mut().find(|(_, app)| app.pid() == pid) else {
            trace!("unable to find application with pid {pid}.");
            continue;
        };

        debug!(
            "created {} title: {} role: {} subrole: {} element: {}",
            window_id,
            window.title().unwrap_or_default(),
            window.role().unwrap_or_default(),
            window.subrole().unwrap_or_default(),
            window
                .element()
                .map(|element| format!("{element}"))
                .unwrap_or_default(),
        );

        if app.observe_window(&window).is_err() {
            warn!("Error observing window {window_id}.");
        }
        debug!(
            "window {} title: {}",
            window_id,
            window.title().unwrap_or_default()
        );

        let properties = WindowPropoerties::new(&app, &window, config.config());
        if !properties.params.is_empty() {
            debug!("Applying window properties for '{}'", window.id());
        }

        apply_window_defaults(
            &mut window,
            &mut active_display,
            &properties.params,
            config.edge_padding(),
        );

        // update_frame expands the OS rect by the per-window padding, so calling it *after*
        // set_padding produces the correct logical frame for the ECS components below.
        let Ok(frame) = window.update_frame().inspect_err(|err| error!("{err}")) else {
            continue;
        };
        let position = Position(frame.min);
        let bounds = Bounds(Size::new(frame.width(), frame.height()));
        let width_ratio =
            WidthRatio(f64::from(frame.width()) / f64::from(active_display.bounds().width()));
        let layout_position = LayoutPosition::default();

        // Overlapping Frame Strategy: check if this window overlaps exactly with an existing
        // window from the same application. If so, it's likely a native tab.
        let tabbed_entity = windows
            .all_iter()
            .find_map(|(existing_window, entity, parent)| {
                (parent.parent() == app_entity && existing_window.frame() == window.frame())
                    .then_some(entity)
            });

        // Insert the window into the internal Bevy state.
        // This insertion triggers window attributes observer.
        let entity = commands
            .spawn((
                position,
                bounds,
                width_ratio,
                window,
                layout_position,
                ChildOf(app_entity),
            ))
            .id();

        if let Some(leader) = tabbed_entity {
            debug!(
                "Adding window {window_id} as a tab follower for leader {leader:?} (overlapping frame)"
            );
            let layout_strip = active_display.active_strip();
            _ = layout_strip
                .convert_to_tabs(leader, entity)
                .inspect_err(|err| error!("Failed to convert to tabs: {err}"));
        }
    }
}

#[allow(clippy::cast_possible_truncation)]
fn apply_window_defaults(
    window: &mut Window,
    active_display: &mut ActiveDisplayMut,
    properties: &[WindowParams],
    edge_padding: (i32, i32, i32, i32),
) {
    let floating = properties
        .iter()
        .find_map(|props| props.floating)
        .unwrap_or(false);

    // Do not add padding to floating windows.
    if let Some(padding) = properties.iter().find_map(|props| props.vertical_padding)
        && !floating
    {
        window.set_padding(WindowPadding::Vertical(padding.clamp(0, 50)));
    }
    if let Some(padding) = properties.iter().find_map(|props| props.horizontal_padding)
        && !floating
    {
        window.set_padding(WindowPadding::Horizontal(padding.clamp(0, 50)));
    }
    if floating {
        if let Some((rx, ry, rw, rh)) = properties.iter().find_map(WindowParams::grid_ratios) {
            let bounds = active_display.bounds();
            let x = (f64::from(bounds.width()) * rx) as i32;
            let y = (f64::from(bounds.height()) * ry) as i32;
            let w = (f64::from(bounds.width()) * rw) as i32;
            let h = (f64::from(bounds.height()) * rh) as i32;
            window.reposition(Origin::new(x, y));
            window.resize(Size::new(w, h));
        }
        return;
    }

    // Apply configured width AFTER update_frame so it isn't overwritten.
    // Use padded display width (matching window_resize command behavior).
    if let Some(width) = properties.iter().find_map(|props| props.width) {
        let bounds = active_display.bounds();
        let (_, pad_right, _, pad_left) = edge_padding;
        let padded_width = bounds.width() - pad_left - pad_right;
        let new_width = (f64::from(padded_width) * width).round() as i32;
        let height = window.frame().height();
        window.resize(Size::new(new_width, height));
        // Re-read the actual OS size: the app may enforce a minimum width
        // that differs from our request.
        _ = window.update_frame().inspect_err(|err| error!("{err}"));
    }
}

#[allow(clippy::needless_pass_by_value)]
#[instrument(level = Level::DEBUG, skip_all, fields(trigger))]
pub(super) fn apply_window_properties(
    trigger: On<Add, Window>,
    mut active_display: ActiveDisplayMut,
    windows: Windows,
    apps: Query<&Application>,
    config: Configuration,
    mut commands: Commands,
) {
    let entity = trigger.event().entity;

    if active_display.active_strip().tabbed(entity) {
        debug!("Ignoring tabbed {entity} attributes.");
        return;
    }

    let Some((window, _, parent)) = windows
        .get(entity)
        .and_then(|window| windows.find_parent(window.id()))
    else {
        return;
    };
    let Ok(app) = apps.get(parent) else {
        return;
    };
    let properties = WindowPropoerties::new(app, window, config.config());

    if properties.floating() {
        // Avoid managing window if it's floating.
        commands.entity(entity).try_insert(Unmanaged::Floating);
        return;
    }

    let strip = active_display.active_strip();

    // Attempt inserting the window at a pre-defined position.
    let insert_at = properties.insertion().map_or_else(
        || {
            // Otherwise attempt inserting it after the current focus.
            let focused_window = windows.focused();
            // Insert to the right of the currently focused window
            focused_window
                .and_then(|(_, entity)| strip.index_of(entity).ok())
                .and_then(|insert_at| (insert_at + 1 < strip.len()).then_some(insert_at + 1))
        },
        Some,
    );

    debug!("New window adding at {strip}");
    match insert_at {
        Some(after) => {
            debug!("New window inserted at {after}");
            strip.insert_at(after, entity);
        }
        None => strip.append(entity),
    }

    // During init, skip per-window reshuffles. finish_setup does a single
    // reshuffle after all windows are added.
    if !config.initializing()
        && properties.dont_focus()
        && let Some((focus, _)) = windows.focused()
        && let Some(psn) = windows.psn(focus.id(), &apps)
    {
        debug!(
            "Not focusing new window {entity}, keeping focus on '{}'",
            focus.title().unwrap_or_default()
        );
        focus.focus_with_raise(psn);
    }
}

#[allow(clippy::needless_pass_by_value)]
pub(super) fn refresh_configuration_trigger(
    trigger: On<WMEventTrigger>,
    window_manager: Res<WindowManager>,
    mut config: ResMut<Config>,
    watcher: Option<NonSendMut<Box<dyn Watcher>>>,
    windows: Windows,
    mut displays: Query<&mut Display>,
    applications: Query<&Application>,
) {
    let Event::ConfigRefresh(event) = &trigger.event().0 else {
        return;
    };
    let Some(mut watcher) = watcher else {
        return;
    };

    match &event.kind {
        EventKind::Modify(
            // When using the RecommendedWatcher, the event triggers on file data.
            // When using PollWatcher, it triggers on modification time.
            ModifyKind::Metadata(MetadataKind::WriteTime) | ModifyKind::Data(DataChange::Content),
        ) => (),
        EventKind::Remove(_) => {
            for path in &event.paths {
                _ = watcher.unwatch(path).inspect_err(|err| {
                    error!("unwatching the config '{}': {err}", path.display());
                });
            }
            return;
        }
        _ => return,
    }

    for path in &event.paths {
        if let Some(symlink) = symlink_target(path) {
            debug!(
                "symlink '{}' changed, replacing the watcher.",
                symlink.display()
            );
            if let Ok(new_watcher) = window_manager
                .setup_config_watcher(path)
                .inspect_err(|err| {
                    error!("watching the config '{}': {err}", path.display());
                })
            {
                *watcher = new_watcher;
            }
        }
        info!("Reloading configuration file; {}", path.display());
        _ = config.reload_config(path.as_path()).inspect_err(|err| {
            error!("loading config '{}': {err}", path.display());
        });
    }

    let height = config.menubar_height();
    for mut display in &mut displays {
        display.set_menubar_height_override(height);
    }

    // Recompute passthrough keys for the currently focused window.
    if let Some((window, _, parent)) = windows
        .focused()
        .and_then(|(w, e)| windows.find_parent(w.id()).map(|(w, _, p)| (w, e, p)))
        && let Ok(app) = applications.get(parent)
    {
        update_passthrough(window, app, &config);
    }
}

#[allow(clippy::needless_pass_by_value)]
pub(super) fn stray_focus_observer(
    trigger: On<Add, Window>,
    focus_events: Populated<(Entity, &StrayFocusEvent)>,
    windows: Windows,
    mut commands: Commands,
) {
    let entity = trigger.event().entity;
    let Some(window_id) = windows.get(entity).map(|window| window.id()) else {
        return;
    };

    focus_events
        .iter()
        .filter(|(_, stray_focus)| stray_focus.0 == window_id)
        .for_each(|(timeout_entity, _)| {
            debug!("Re-queueing lost focus event for window id {window_id}.");
            commands.trigger(SendMessageTrigger(Event::WindowFocused { window_id }));
            commands.entity(timeout_entity).despawn();
        });
}

#[allow(clippy::needless_pass_by_value)]
pub(super) fn window_removal_trigger(
    trigger: On<Remove, Window>,
    mut workspaces: Query<&mut LayoutStrip>,
) {
    let entity = trigger.event().entity;

    if let Some(mut strip) = workspaces
        .iter_mut()
        .find(|strip| strip.index_of(entity).is_ok())
    {
        strip.remove(entity);
    }
}

#[allow(clippy::needless_pass_by_value)]
pub(super) fn locate_dock_trigger(
    trigger: On<LocateDockTrigger>,
    displays: Query<(&mut Display, Entity)>,
    platform: Option<NonSend<Pin<Box<PlatformCallbacks>>>>,
    mut commands: Commands,
) {
    let Ok((display, entity)) = displays.get(trigger.event().0) else {
        return;
    };
    let display_id = display.id();

    // NSScreen::screen needs to run in the main thread, thus we run it in a NonSend trigger.
    let screens = platform.map(|platform| NSScreen::screens(platform.main_thread_marker));
    let dock = screens.as_ref().and_then(|screens| {
        screens.iter().find_map(|screen| {
            let dict = screen.deviceDescription();
            let numbers = unsafe { dict.cast_unchecked::<NSString, NSNumber>() };
            let id = numbers.objectForKey(ns_string!("NSScreenNumber"));
            id.is_some_and(|id| id.as_u32() == display_id).then(|| {
                let visible_frame = irect_from(screen.visibleFrame());
                display.locate_dock(&visible_frame)
            })
        })
    });
    if let Some(dock) = dock {
        debug!("dock on display {display_id}: {:?}", dock);
        if let Ok(mut entity_cmmands) = commands.get_entity(entity) {
            entity_cmmands.try_insert(dock);
        }
    }
}

#[allow(clippy::needless_pass_by_value)]
pub(super) fn send_message_trigger(
    trigger: On<SendMessageTrigger>,
    mut messages: MessageWriter<Event>,
) {
    let event = &trigger.event().0;
    messages.write(event.clone());
}