bevy_window_manager 0.20.2

Bevy plugin for primary window restoration and multi-monitor support
Documentation
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
//! Systems for window restoration and state management.
//!
//! # Monitor Detection
//!
//! [`update_current_monitor`] is the unified system that maintains `CurrentMonitor` on all
//! managed windows. It uses winit's `current_monitor()` as the primary detection method,
//! with position-based center-point detection as a fallback. This ensures correct monitor
//! identification even for newly spawned windows whose `window.position` is still `Automatic`.
//!
//! On Wayland, `window.position` always returns `(0,0)` for security/privacy reasons, making
//! winit's `current_monitor()` the only viable detection method on that platform.

use bevy::ecs::system::NonSendMarker;
use bevy::prelude::*;
use bevy::window::MonitorSelection;
use bevy::window::PrimaryWindow;
use bevy::window::WindowMode;
use bevy::window::WindowScaleFactorChanged;
use bevy::winit::WINIT_WINDOWS;
use bevy_kana::ToI32;
use bevy_kana::ToU32;

use super::ManagedWindow;
use super::ManagedWindowPersistence;
use super::Platform;
use super::WindowKey;
use super::constants::DEFAULT_SCALE_FACTOR;
use super::constants::SCALE_FACTOR_EPSILON;
use super::monitors::CurrentMonitor;
use super::monitors::MonitorInfo;
use super::monitors::Monitors;
use super::restore_plan;
use super::state;
use super::types::FullscreenRestoreState;
use super::types::MonitorScaleStrategy;
use super::types::RestoreWindowConfig;
use super::types::SavedWindowMode;
use super::types::SettleSnapshot;
use super::types::SettleState;
use super::types::TargetPosition;
use super::types::WindowDecoration;
use super::types::WindowRestoreMismatch;
use super::types::WindowRestoreState;
use super::types::WindowRestored;
use super::types::WindowState;
use super::types::WinitInfo;
use super::types::X11FrameCompensated;

/// Populate `WinitInfo` resource from winit (decoration and starting monitor).
///
/// # Panics
///
/// Panics if no monitors are available (e.g., laptop lid closed at startup).
/// Window management requires at least one monitor to function.
pub(crate) fn init_winit_info(
    mut commands: Commands,
    window_entity: Single<Entity, With<PrimaryWindow>>,
    monitors: Res<Monitors>,
    _non_send: NonSendMarker,
) {
    assert!(
        !monitors.is_empty(),
        "No monitors available - cannot initialize window manager without a display"
    );

    WINIT_WINDOWS.with(|ww| {
        let ww = ww.borrow();
        if let Some(winit_window) = ww.get_window(*window_entity) {
            let outer = winit_window.outer_size();
            let inner = winit_window.inner_size();
            let decoration = WindowDecoration {
                width:  outer.width.saturating_sub(inner.width),
                height: outer.height.saturating_sub(inner.height),
            };

            // Get actual position from winit to determine starting monitor
            let pos = winit_window
                .outer_position()
                .map(|p| IVec2::new(p.x, p.y))
                .unwrap_or(IVec2::ZERO);

            debug!(
                "[init_winit_info] outer_position={pos:?} platform={:?}",
                Platform::detect()
            );

            // Use winit's current_monitor() as the primary source for starting monitor.
            // Falls back to position-based detection if current_monitor() returns None.
            let starting_monitor = winit_window
                .current_monitor()
                .and_then(|cm| {
                    let monitor_position = cm.position();
                    let info = monitors.at(monitor_position.x, monitor_position.y);
                    debug!(
                        "[init_winit_info] current_monitor() position=({}, {}) -> index={:?}",
                        monitor_position.x, monitor_position.y, info.map(|m| m.index)
                    );
                    info.copied()
                })
                .unwrap_or_else(|| {
                    debug!(
                        "[init_winit_info] current_monitor() unavailable, falling back to closest_to({}, {})",
                        pos.x, pos.y
                    );
                    *monitors.closest_to(pos.x, pos.y)
                });
            let starting_monitor_index = starting_monitor.index;

            debug!(
                "[init_winit_info] decoration={}x{} pos=({}, {}) starting_monitor={}",
                decoration.width, decoration.height, pos.x, pos.y, starting_monitor_index
            );

            // Insert initial CurrentMonitor component on window entity
            commands
                .entity(*window_entity)
                .insert(CurrentMonitor {
                    monitor:        starting_monitor,
                    effective_mode: WindowMode::Windowed,
                });

            commands.insert_resource(WinitInfo {
                starting_monitor_index,
                decoration,
            });
        }
    });
}

/// Load saved window state and insert `TargetPosition` component on the primary window entity.
///
/// Runs after `init_winit_info` so we have access to starting monitor info.
pub(crate) fn load_target_position(
    mut commands: Commands,
    window_entity: Single<Entity, With<PrimaryWindow>>,
    monitors: Res<Monitors>,
    winit_info: Res<WinitInfo>,
    mut config: ResMut<RestoreWindowConfig>,
    platform: Res<Platform>,
) {
    // Load all states from the file into `loaded_states` as a startup snapshot.
    // This must happen before any managed window observers fire so they can check
    // `loaded_states` instead of re-reading the file (which may have been modified
    // by `on_managed_window_added` saving initial state for new windows).
    if let Some(all_states) = state::load_all_states(&config.path) {
        config.loaded_states = all_states;
    }

    let Some(state) = config.loaded_states.get(&WindowKey::Primary).cloned() else {
        debug!("[load_target_position] No saved bevy_window_manager state, showing window");
        // No saved state - show window at default position (user may have started hidden)
        commands.queue(|world: &mut World| {
            let mut query = world.query_filtered::<&mut Window, With<PrimaryWindow>>();
            if let Some(mut window) = query.iter_mut(world).next() {
                window.visible = true;
            }
        });
        return;
    };

    debug!(
        "[load_target_position] Loaded state: position={:?} logical_size={}x{} monitor_scale={} monitor_index={} mode={:?}",
        state.logical_position,
        state.logical_width,
        state.logical_height,
        state.monitor_scale,
        state.monitor_index,
        state.mode
    );

    // Get starting monitor from WinitInfo
    let starting_monitor_index = winit_info.starting_monitor_index;
    let starting_info = monitors.by_index(starting_monitor_index);
    let starting_scale = starting_info.map_or(DEFAULT_SCALE_FACTOR, |m| m.scale);

    let (target_info, fallback_position, used_fallback) =
        restore_plan::resolve_target_monitor_and_position(
            state.monitor_index,
            state.logical_position,
            &monitors,
        );
    if used_fallback {
        warn!(
            "[load_target_position] Target monitor {} not found, falling back to monitor 0",
            state.monitor_index
        );
    }

    let target = restore_plan::compute_target_position(
        &state,
        target_info,
        fallback_position,
        winit_info.decoration(),
        starting_scale,
        *platform,
    );

    debug!(
        "[load_target_position] Starting monitor={} scale={}, Target monitor={} scale={}, strategy={:?}, position={:?}",
        starting_monitor_index,
        starting_scale,
        target.target_monitor_index,
        target.target_scale,
        target.scale_strategy,
        target.position
    );

    // Windows W3 workaround (winit #3124): For exclusive fullscreen restore, we must
    // show the window to ensure surfaces are created before the workaround applies
    // fullscreen mode. Otherwise, we want visible = false to prevent the flickering
    // jump from the default position to the restored position.
    #[cfg(all(target_os = "windows", feature = "workaround-winit-3124"))]
    if matches!(state.mode, SavedWindowMode::Fullscreen { .. }) {
        debug!(
            "[load_target_position] Windows exclusive fullscreen: showing window for surface creation"
        );
        commands.queue(|world: &mut World| {
            let mut query = world.query_filtered::<&mut Window, With<PrimaryWindow>>();
            if let Some(mut window) = query.iter_mut(world).next() {
                window.visible = true;
            }
        });
    }

    let entity = *window_entity;
    let is_fullscreen = state.mode.is_fullscreen();
    commands.entity(entity).insert(target);

    // Insert X11FrameCompensated token for platforms that don't need compensation.
    // On Linux + W6 + X11, the compensation system inserts this token after adjusting position.
    // For fullscreen modes, skip frame compensation entirely — the window will cover the whole
    // screen so frame extents are irrelevant, and delaying restore_windows by extra frames
    // gives the compositor time to revert our PreStartup position change.
    if is_fullscreen || !platform.needs_frame_compensation() {
        commands.entity(entity).insert(X11FrameCompensated);
    }
}

/// Move the primary window to the target monitor for fullscreen restore on X11.
///
/// On X11, the compositor (`KWin` via `XWayland`) reverts fullscreen if the position
/// and mode changes arrive in the same `changed_windows` pass. By setting position
/// in a separate `PreStartup` system (direct mutation, not commands.queue), the change
/// is processed by `bevy_winit` before the `Update` system applies fullscreen mode.
///
/// Skipped on Wayland (no position) and non-fullscreen modes.
/// For managed windows, the equivalent happens in `on_managed_window_load`.
#[cfg(target_os = "linux")]
pub(crate) fn move_to_target_monitor(
    mut window: Single<&mut Window, With<PrimaryWindow>>,
    targets: Query<&TargetPosition, With<PrimaryWindow>>,
    platform: Res<Platform>,
) {
    if platform.is_wayland() {
        return;
    }

    let Ok(target) = targets.single() else {
        return;
    };

    if !target.mode.is_fullscreen() {
        return;
    }

    if let Some(pos) = target.position {
        debug!("[move_to_target_monitor] X11 fullscreen: setting position={pos:?}");
        window.position = WindowPosition::At(pos);
    }
}

/// Apply the initial window move to the target monitor.
///
/// Sets position and size based on the `TargetPosition` strategy, handling fullscreen,
/// Wayland (no position), and cross-DPI scenarios. Called from `restore_windows` during
/// the `NeedInitialMove` phase for `HigherToLower` and `CompensateSizeOnly` strategies.
///
/// On macOS with `HigherToLower` strategy, the position is compensated because winit
/// divides coordinates by the launch monitor's scale factor.
///
/// On Windows with `CompensateSizeOnly`, position is applied directly and size is
/// compensated by `starting_scale / target_scale`. Phase 2 re-applies the exact size.
///
/// For fullscreen modes, we still move to the target monitor so the fullscreen mode
/// is applied on the correct monitor when `try_apply_restore` runs.
pub(crate) fn apply_initial_move(target: &TargetPosition, window: &mut Window) {
    /// Computed parameters for the initial window move to target monitor.
    #[derive(Debug)]
    struct MoveParams {
        position: IVec2,
        width:    u32,
        height:   u32,
    }

    // For fullscreen modes, just move to target monitor position (no 1x1 size)
    // The fullscreen mode will be applied later in try_apply_restore
    if target.mode.is_fullscreen() {
        if let Some(pos) = target.position {
            debug!(
                "[apply_initial_move] Moving to target position {:?} for fullscreen mode {:?}",
                pos, target.mode
            );
            window.position = WindowPosition::At(pos);
        } else {
            debug!(
                "[apply_initial_move] No position available (Wayland), fullscreen mode {:?}",
                target.mode
            );
        }
        return;
    }

    // Position may be None on Wayland - skip position setting if unavailable
    let Some(pos) = target.position else {
        debug!(
            "[apply_initial_move] No position available (Wayland), setting size only: {}x{}",
            target.width, target.height
        );
        debug!(
            "[apply_initial_move] BEFORE set_physical_resolution: physical={}x{} logical={}x{} scale={}",
            window.resolution.physical_width(),
            window.resolution.physical_height(),
            window.resolution.width(),
            window.resolution.height(),
            window.resolution.scale_factor()
        );
        window
            .resolution
            .set_physical_resolution(target.width, target.height);
        debug!(
            "[apply_initial_move] AFTER set_physical_resolution: physical={}x{} logical={}x{} scale={}",
            window.resolution.physical_width(),
            window.resolution.physical_height(),
            window.resolution.width(),
            window.resolution.height(),
            window.resolution.scale_factor()
        );
        return;
    };

    // Compute move parameters based on scale strategy
    let params = match target.scale_strategy {
        MonitorScaleStrategy::HigherToLower(_) => {
            // Compensate position because winit divides by launch scale
            let ratio = target.starting_scale / target.target_scale;
            let compensated_x = (f64::from(pos.x) * ratio).to_i32();
            let compensated_y = (f64::from(pos.y) * ratio).to_i32();
            debug!(
                "[apply_initial_move] HigherToLower: compensating position {:?} -> ({}, {}) (ratio={})",
                pos, compensated_x, compensated_y, ratio
            );
            MoveParams {
                position: IVec2::new(compensated_x, compensated_y),
                // Use actual target size to avoid macOS caching tiny size
                width:    target.width,
                height:   target.height,
            }
        },
        MonitorScaleStrategy::CompensateSizeOnly(_) => {
            // Position applied directly, size compensated to survive DPI transition.
            // Phase 2 will re-apply the exact target size after ScaleFactorChanged.
            let compensated = target.compensated_size();
            debug!(
                "[apply_initial_move] CompensateSizeOnly: position={:?} compensated_size={}x{} (ratio={})",
                pos,
                compensated.x,
                compensated.y,
                target.ratio()
            );
            MoveParams {
                position: pos,
                width:    compensated.x,
                height:   compensated.y,
            }
        },
        _ => MoveParams {
            position: pos,
            width:    target.width,
            height:   target.height,
        },
    };

    debug!(
        "[apply_initial_move] position={:?} size={}x{} visible={}",
        params.position, params.width, params.height, window.visible
    );

    window.position = WindowPosition::At(params.position);
    window
        .resolution
        .set_physical_resolution(params.width, params.height);
}

/// Cached window state for change detection comparison.
#[derive(Default)]
pub(crate) struct CachedWindowState {
    position:       Option<IVec2>,
    logical_width:  u32,
    logical_height: u32,
    mode:           Option<SavedWindowMode>,
    monitor_index:  Option<usize>,
}

/// Build state from all currently-active windows and write it to the state file.
///
/// Iterates every primary and managed window, captures position/size/monitor/mode,
/// and writes the full persisted state map in one shot. Used by the
/// `ActiveOnly` persistence mode so that the file always reflects exactly which
/// windows are open right now.
///
/// `exclude_entity` allows callers (e.g., `On<Remove>` observers) to skip an entity
/// whose component is still visible in the query but is being removed.
pub(crate) fn save_active_window_state(
    config: &RestoreWindowConfig,
    monitors: &Monitors,
    all_windows: &Query<
        (
            Entity,
            &Window,
            Option<&CurrentMonitor>,
            Option<&ManagedWindow>,
        ),
        Or<(With<PrimaryWindow>, With<ManagedWindow>)>,
    >,
    primary_q: &Query<(), With<PrimaryWindow>>,
    exclude_entity: Option<Entity>,
) {
    if monitors.is_empty() {
        return;
    }

    let app_name = std::env::current_exe()
        .ok()
        .and_then(|p| p.file_stem().and_then(|s| s.to_str()).map(String::from))
        .unwrap_or_default();

    let mut states = std::collections::HashMap::new();

    for (entity, window, existing_monitor, managed) in all_windows {
        if exclude_entity == Some(entity) {
            continue;
        }

        let key = if primary_q.get(entity).is_ok() {
            WindowKey::Primary
        } else if let Some(m) = managed {
            WindowKey::Managed(m.name.clone())
        } else {
            continue;
        };

        let pos = get_window_position(entity, window);

        let (monitor_index, monitor_scale) = existing_monitor.map_or_else(
            || {
                let p = monitors.first();
                (p.index, p.scale)
            },
            |m| (m.index, m.scale),
        );
        let mode: SavedWindowMode =
            existing_monitor.map_or_else(|| (&window.mode).into(), |m| (&m.effective_mode).into());
        let logical_position = pos.map(|p| {
            let logical_x = (f64::from(p.x) / monitor_scale).round().to_i32();
            let logical_y = (f64::from(p.y) / monitor_scale).round().to_i32();
            (logical_x, logical_y)
        });
        states.insert(
            key,
            WindowState {
                logical_position,
                logical_width: window.resolution.width().to_u32(),
                logical_height: window.resolution.height().to_u32(),
                monitor_scale,
                monitor_index,
                mode,
                app_name: app_name.clone(),
            },
        );
    }

    state::save_all_states(&config.path, &states);
}

/// Persist window states using the `RememberAll` strategy: load existing file,
/// merge with cached entries, and save. Preserves entries for closed windows.
fn persist_remember_all(
    config: &RestoreWindowConfig,
    monitors: &Monitors,
    cached: &std::collections::HashMap<Entity, CachedWindowState>,
    all_windows: &Query<
        (
            Entity,
            &Window,
            Option<&CurrentMonitor>,
            Option<&ManagedWindow>,
        ),
        Or<(With<PrimaryWindow>, With<ManagedWindow>)>,
    >,
    primary_q: &Query<(), With<PrimaryWindow>>,
) {
    let app_name = std::env::current_exe()
        .ok()
        .and_then(|p| p.file_stem().and_then(|s| s.to_str()).map(String::from))
        .unwrap_or_default();

    let mut states = state::load_all_states(&config.path).unwrap_or_default();

    // Update with current window states from cache
    for (entity, entry) in cached {
        let key = if primary_q.get(*entity).is_ok() {
            WindowKey::Primary
        } else if let Ok((_, _, _, Some(managed))) = all_windows.get(*entity) {
            WindowKey::Managed(managed.name.clone())
        } else {
            // Entity may have been despawned - skip stale cached entry
            continue;
        };

        if let Some(mode) = &entry.mode {
            let monitor_index = entry.monitor_index.unwrap_or(0);
            let monitor_scale = monitors
                .by_index(monitor_index)
                .map_or(DEFAULT_SCALE_FACTOR, |m| m.scale);
            let logical_position = entry.position.map(|p| {
                let logical_x = (f64::from(p.x) / monitor_scale).round().to_i32();
                let logical_y = (f64::from(p.y) / monitor_scale).round().to_i32();
                (logical_x, logical_y)
            });
            states.insert(
                key,
                WindowState {
                    logical_position,
                    logical_width: entry.logical_width,
                    logical_height: entry.logical_height,
                    monitor_scale,
                    monitor_index,
                    mode: mode.clone(),
                    app_name: app_name.clone(),
                },
            );
        }
    }

    state::save_all_states(&config.path, &states);
}

/// Save window state when position, size, or mode changes. Runs only when not restoring.
///
/// Handles both the primary window and any `ManagedWindow` entities. Uses
/// `ManagedWindowPersistence` to decide whether closed windows keep their saved state.
pub(crate) fn save_window_state(
    config: Res<RestoreWindowConfig>,
    monitors: Res<Monitors>,
    persistence: Res<ManagedWindowPersistence>,
    windows: Query<
        (
            Entity,
            &Window,
            Option<&CurrentMonitor>,
            Option<&ManagedWindow>,
        ),
        (
            Or<(With<PrimaryWindow>, With<ManagedWindow>)>,
            Or<(Changed<Window>, Changed<CurrentMonitor>)>,
        ),
    >,
    all_windows: Query<
        (
            Entity,
            &Window,
            Option<&CurrentMonitor>,
            Option<&ManagedWindow>,
        ),
        Or<(With<PrimaryWindow>, With<ManagedWindow>)>,
    >,
    primary_q: Query<(), With<PrimaryWindow>>,
    mut cached: Local<std::collections::HashMap<Entity, CachedWindowState>>,
    _non_send: NonSendMarker,
) {
    // Can't save state if no monitors exist (e.g., laptop lid closed).
    if monitors.is_empty() {
        return;
    }

    let mut any_changed = false;

    for (window_entity, window, existing_monitor, managed) in &windows {
        // Determine the key for this window in the state file
        let key = if primary_q.get(window_entity).is_ok() {
            WindowKey::Primary
        } else if let Some(m) = managed {
            WindowKey::Managed(m.name.clone())
        } else {
            continue;
        };

        // Get window position for saving state.
        let pos = get_window_position(window_entity, window);

        let physical_w = window.resolution.physical_width();
        let physical_h = window.resolution.physical_height();
        let logical_w = window.resolution.width().to_u32();
        let logical_h = window.resolution.height().to_u32();
        let res_scale = window.resolution.scale_factor();

        // Read monitor and effective mode from `CurrentMonitor` (maintained by
        // `update_current_monitor`)
        let (monitor_index, monitor_scale) = existing_monitor.map_or_else(
            || {
                let p = monitors.first();
                (p.index, p.scale)
            },
            |m| (m.index, m.scale),
        );
        let mode: SavedWindowMode =
            existing_monitor.map_or_else(|| (&window.mode).into(), |m| (&m.effective_mode).into());

        let entry = cached.entry(window_entity).or_default();

        // Only save if position, size, or mode actually changed
        let position_changed = entry.position != pos;
        let size_changed = entry.logical_width != logical_w || entry.logical_height != logical_h;
        let mode_changed = entry.mode.as_ref() != Some(&mode);
        let monitor_changed = entry.monitor_index != Some(monitor_index);

        if !position_changed && !size_changed && !mode_changed && !monitor_changed {
            continue;
        }

        debug!(
            "[save_window_state] [{key}] SAVE DETAIL: pos={pos:?} physical={physical_w}x{physical_h} logical={logical_w}x{logical_h} res_scale={res_scale} monitor={monitor_index} mode={mode:?}",
        );

        // Log monitor transitions with detailed info
        if monitor_changed {
            let prev_scale = entry
                .monitor_index
                .and_then(|i| monitors.by_index(i))
                .map(|m| m.scale);
            debug!(
                "[save_window_state] [{key}] MONITOR CHANGE: {:?} (scale={:?}) -> {} (scale={})",
                entry.monitor_index, prev_scale, monitor_index, monitor_scale
            );
        }

        // Update cache
        entry.position = pos;
        entry.logical_width = logical_w;
        entry.logical_height = logical_h;
        entry.mode = Some(mode.clone());
        entry.monitor_index = Some(monitor_index);

        any_changed = true;

        debug!(
            "[save_window_state] [{key}] pos={pos:?} logical={logical_w}x{logical_h} physical={physical_w}x{physical_h} monitor={monitor_index} scale={monitor_scale} mode={mode:?}",
        );
    }

    if !any_changed {
        return;
    }

    match *persistence {
        ManagedWindowPersistence::ActiveOnly => {
            // Build state from all active windows and write in one shot
            save_active_window_state(&config, &monitors, &all_windows, &primary_q, None);
        },
        ManagedWindowPersistence::RememberAll => {
            persist_remember_all(&config, &monitors, &cached, &all_windows, &primary_q);
        },
    }
}

/// Apply pending window restore. Runs only when entities with `TargetPosition` exist.
/// Processes all windows with both `TargetPosition` and `X11FrameCompensated` components.
///
/// Requires `NonSendMarker` because we access `WINIT_WINDOWS` thread-local to gate
/// restore on the winit window existing. Without this gate, managed windows spawned
/// at runtime would have their physical size set by `set_physical_resolution()` and
/// then doubled by `create_windows` → `set_scale_factor_and_apply_to_physical_size()`
/// which runs between frames.
pub(crate) fn restore_windows(
    mut scale_changed_messages: MessageReader<WindowScaleFactorChanged>,
    mut windows: Query<(Entity, &mut TargetPosition, &mut Window), With<X11FrameCompensated>>,
    _non_send: NonSendMarker,
    platform: Res<Platform>,
) {
    let scale_changed = scale_changed_messages.read().last().is_some();

    for (entity, mut target, mut window) in &mut windows {
        // Wait for the winit window to be created before applying restore.
        //
        // Primary window: `create_windows` runs during winit `init()` before any Bevy
        // schedules, so the winit window always exists when we get here.
        //
        // Managed windows: spawned at runtime, `create_windows` runs between frames via
        // `WinitUserEvent::WindowAdded`. If we apply `set_physical_resolution()` before
        // `create_windows` runs, `create_windows` will call
        // `set_scale_factor_and_apply_to_physical_size(scale)` which multiplies our
        // already-correct physical size by the scale factor (doubling it on 2x displays).
        // Already settling — skip restore logic, handled by check_restore_settling
        if target.settle_state.is_some() {
            continue;
        }

        let winit_window_exists = WINIT_WINDOWS.with(|ww| ww.borrow().get_window(entity).is_some());
        if !winit_window_exists {
            debug!("[restore_windows] Skipping entity {entity:?}: winit window not yet created");
            continue;
        }

        // Managed windows may be created on a different monitor than assumed.
        // `starting_scale` was computed from the primary window's current monitor,
        // but Windows OS places new windows on the OS primary display (which may differ).
        // Detect this and recalculate the scale strategy with the actual creation scale.
        if platform.needs_managed_scale_fixup() {
            let actual_scale = f64::from(window.resolution.base_scale_factor());
            if (actual_scale - target.starting_scale).abs() > SCALE_FACTOR_EPSILON {
                let old_strategy = target.scale_strategy;
                target.starting_scale = actual_scale;
                target.scale_strategy = platform.scale_strategy(actual_scale, target.target_scale);
                debug!(
                    "[restore_windows] Corrected starting_scale for entity {entity:?}: \
                     strategy: {old_strategy:?} -> {:?} (actual_scale={actual_scale:.2})",
                    target.scale_strategy
                );
            }
        }

        // Two-phase restore for cross-DPI strategies (HigherToLower, CompensateSizeOnly).
        // Phase 1: apply_initial_move sets compensated position/size to trigger DPI change.
        // Phase 2: after ScaleFactorChanged, re-apply exact target size.
        if matches!(
            target.scale_strategy,
            MonitorScaleStrategy::HigherToLower(WindowRestoreState::NeedInitialMove)
                | MonitorScaleStrategy::CompensateSizeOnly(WindowRestoreState::NeedInitialMove)
        ) && try_cross_dpi_initial_move(&mut target, &mut window)
        {
            continue;
        }

        // Handle state transition on scale change for both strategies.
        // CompensateSizeOnly: also advance if no scale change arrives (e.g., hidden window
        // didn't trigger WM_DPICHANGED, or the app launched on the target monitor).
        match target.scale_strategy {
            MonitorScaleStrategy::HigherToLower(WindowRestoreState::WaitingForScaleChange)
                if scale_changed =>
            {
                debug!(
                    "[Restore] ScaleChanged received, transitioning to WindowRestoreState::ApplySize"
                );
                target.scale_strategy =
                    MonitorScaleStrategy::HigherToLower(WindowRestoreState::ApplySize);
            },
            MonitorScaleStrategy::CompensateSizeOnly(WindowRestoreState::WaitingForScaleChange) => {
                debug!(
                    "[Restore] CompensateSizeOnly: transitioning to ApplySize (scale_changed={scale_changed})"
                );
                target.scale_strategy =
                    MonitorScaleStrategy::CompensateSizeOnly(WindowRestoreState::ApplySize);
            },
            _ => {},
        }

        // Fullscreen phase state machine.
        // Phases: MoveToMonitor → WaitForMove → ApplyMode (Linux X11)
        //         WaitForSurface → ApplyMode (Windows DX12)
        //         ApplyMode (Wayland, macOS — direct apply)
        if let Some(fs_state) = target.fullscreen_state {
            match fs_state {
                FullscreenRestoreState::MoveToMonitor => {
                    // Move window to target monitor so compositor knows where it belongs
                    if let Some(pos) = target.position {
                        debug!("[restore_windows] Fullscreen MoveToMonitor: position={pos:?}");
                        window.position = WindowPosition::At(pos);
                    }
                    target.fullscreen_state = Some(FullscreenRestoreState::WaitForMove);
                    continue;
                },
                FullscreenRestoreState::WaitForMove => {
                    // Wait one frame for compositor to process the position change
                    debug!("[restore_windows] Fullscreen WaitForMove: waiting for compositor");
                    target.fullscreen_state = Some(FullscreenRestoreState::ApplyMode);
                    continue;
                },
                FullscreenRestoreState::WaitForSurface => {
                    // Wait one frame for GPU surface creation (Windows DX12, winit #3124)
                    debug!("[restore_windows] Fullscreen WaitForSurface: waiting for GPU surface");
                    target.fullscreen_state = Some(FullscreenRestoreState::ApplyMode);
                    continue;
                },
                FullscreenRestoreState::ApplyMode => {
                    // Fall through to try_apply_restore which applies the fullscreen mode
                },
            }
        }

        if matches!(
            try_apply_restore(&target, &mut window, *platform),
            RestoreStatus::Complete
        ) {
            // Restore applied — start settle timer to wait for compositor/winit to
            // deliver matching state before declaring success or mismatch.
            if target.settle_state.is_none() {
                info!(
                    "[restore_windows] Restore applied, starting settle (200ms stability / 1s timeout)"
                );
                target.settle_state = Some(SettleState::new());
            }
        }
    }
}

/// Build a [`SettleSnapshot`] from the current window state, returning the snapshot
/// and the actual scale factor (tracked separately since scale is informational).
fn build_actual_snapshot(
    window: &Window,
    current_monitor: Option<&CurrentMonitor>,
    platform: Platform,
) -> (SettleSnapshot, f64) {
    let position = if platform.position_available() {
        match window.position {
            WindowPosition::At(p) => Some(IVec2::new(p.x, p.y)),
            _ => None,
        }
    } else {
        None
    };
    let size = UVec2::new(
        window.resolution.physical_width(),
        window.resolution.physical_height(),
    );
    (
        SettleSnapshot {
            position,
            size,
            mode: window.mode,
            monitor: current_monitor.map_or(0, |cm| cm.monitor.index),
        },
        f64::from(window.resolution.scale_factor()),
    )
}

/// Check whether actual window state matches the target for settle purposes.
///
/// Fullscreen modes skip position and size comparison — the window fills the
/// monitor so the stored position/size are irrelevant. On macOS, borderless
/// fullscreen reports position offset by the menu bar height; on X11 (W6),
/// frame vs client coords differ. The physical size can also differ when
/// scales differ between backends (e.g. Wayland scale 1 vs `XWayland` scale 2).
fn check_settle_matches(
    target: &TargetPosition,
    target_position: Option<IVec2>,
    target_size: UVec2,
    target_mode: WindowMode,
    target_monitor: usize,
    actual: &SettleSnapshot,
    platform: Platform,
) -> (bool, bool, bool, bool) {
    let is_fullscreen = target.mode.is_fullscreen();
    let position_matches = if is_fullscreen {
        true
    } else if platform.position_reliable_for_settle() {
        target_position == actual.position
    } else {
        true // X11 W6: target is frame coords, actual is client area — skip
    };
    let size_match = is_fullscreen || target_size == actual.size;
    let mode_match = platform.modes_match(target_mode, actual.mode);
    let monitor_match = target_monitor == actual.monitor;
    (position_matches, size_match, mode_match, monitor_match)
}

/// Detect whether the settle snapshot changed from the previous frame and reset the
/// stability timer if so. Returns `true` if the caller should skip further checks
/// this frame (snapshot just changed and we haven't timed out yet).
fn detect_settle_change(
    settle: &mut SettleState,
    snapshot: SettleSnapshot,
    key: &WindowKey,
    total_elapsed_ms: f32,
    total_timed_out: bool,
) -> bool {
    let changed = settle.last_snapshot.as_ref() != Some(&snapshot);
    if changed {
        if settle.last_snapshot.is_some() {
            debug!(
                "[check_restore_settling] [{key}] {total_elapsed_ms:.0}ms: values changed, \
                 resetting stability timer"
            );
        }
        settle.stability_timer.reset();
        settle.last_snapshot = Some(snapshot);
        // Don't check stability this frame — we just reset
        !total_timed_out
    } else {
        false
    }
}

/// Resolve the [`WindowKey`] for an entity — `Primary` if it has the `PrimaryWindow`
/// marker, otherwise the `ManagedWindow` name (falling back to `Primary`).
fn resolve_window_key(
    entity: Entity,
    primary_q: &Query<(), With<PrimaryWindow>>,
    managed_q: &Query<&ManagedWindow>,
) -> WindowKey {
    if primary_q.get(entity).is_ok() {
        WindowKey::Primary
    } else if let Ok(managed) = managed_q.get(entity) {
        WindowKey::Managed(managed.name.clone())
    } else {
        WindowKey::Primary
    }
}

/// Check settling windows each frame using a two-timer approach.
///
/// - **Stability timer** (200ms): resets whenever any compared value changes. If values stay stable
///   for 200ms, fires `WindowRestored`.
/// - **Total timeout** (1s): hard deadline. Fires `WindowRestoreMismatch` if stability is never
///   reached.
///
/// Runs while `TargetPosition` entities exist (same gate as `restore_windows`).
/// Only processes entities that have a `settle_state` set.
pub(crate) fn check_restore_settling(
    mut commands: Commands,
    time: Res<Time>,
    mut windows: Query<
        (
            Entity,
            &mut TargetPosition,
            &Window,
            Option<&CurrentMonitor>,
        ),
        With<X11FrameCompensated>,
    >,
    primary_q: Query<(), With<PrimaryWindow>>,
    managed_q: Query<&ManagedWindow>,
    platform: Res<Platform>,
) {
    for (entity, mut target, window, current_monitor) in &mut windows {
        // Read target fields before borrowing settle_state mutably
        let target_mode = target.mode.to_window_mode(target.target_monitor_index);
        let target_size = target.size();
        let target_logical_size = target.logical_size();
        let target_monitor = target.target_monitor_index;
        let expected_scale = target.target_scale;

        let target_position = platform
            .position_available()
            .then_some(target.position)
            .flatten();
        let key = resolve_window_key(entity, &primary_q, &managed_q);
        let (current_snapshot, actual_scale) =
            build_actual_snapshot(window, current_monitor, *platform);

        // Now borrow settle_state mutably for timer ticking and change detection
        let Some(settle) = target.settle_state.as_mut() else {
            continue;
        };
        settle.total_timeout.tick(time.delta());
        settle.stability_timer.tick(time.delta());

        let total_elapsed_ms = settle.total_timeout.elapsed_secs() * 1000.0;
        let stability_elapsed_ms = settle.stability_timer.elapsed_secs() * 1000.0;
        let total_timed_out = settle.total_timeout.is_finished();

        if detect_settle_change(
            settle,
            current_snapshot,
            &key,
            total_elapsed_ms,
            total_timed_out,
        ) {
            continue;
        }
        let stable = settle.stability_timer.is_finished();
        let (position_matches, size_match, mode_match, monitor_match) = check_settle_matches(
            &target,
            target_position,
            target_size,
            target_mode,
            target_monitor,
            &current_snapshot,
            *platform,
        );
        let all_match = position_matches && size_match && mode_match && monitor_match;
        debug!(
            "[check_restore_settling] [{key}] {total_elapsed_ms:.0}ms (stable: {stability_elapsed_ms:.0}ms): \
             pos={position_matches} size={size_match} mode={mode_match} monitor={monitor_match} | \
             size: {target_size} vs {}, \
             mode: {target_mode:?} vs {:?}, \
             monitor: {target_monitor} vs {}, \
             scale: {expected_scale} vs {actual_scale}",
            current_snapshot.size, current_snapshot.mode, current_snapshot.monitor,
        );

        let settle_target = SettleTarget {
            position:     target_position,
            size:         target_size,
            logical_size: target_logical_size,
            mode:         target_mode,
            monitor:      target_monitor,
            scale:        expected_scale,
        };
        if stable && all_match {
            emit_settle_success(
                &mut commands,
                entity,
                key,
                &settle_target,
                total_elapsed_ms,
                stability_elapsed_ms,
            );
        } else if total_timed_out {
            let settle_actual = SettleActual {
                snapshot:     current_snapshot,
                scale:        actual_scale,
                logical_size: UVec2::new(
                    window.resolution.width().to_u32(),
                    window.resolution.height().to_u32(),
                ),
            };
            emit_settle_mismatch(
                &mut commands,
                entity,
                key,
                &settle_target,
                &settle_actual,
                total_elapsed_ms,
            );
        }
    }
}

/// Bundled actual values for settle mismatch reporting.
struct SettleActual {
    snapshot:     SettleSnapshot,
    scale:        f64,
    logical_size: UVec2,
}

/// Extracted target values for settle resolution, avoiding too-many-arguments.
struct SettleTarget {
    position:     Option<IVec2>,
    size:         UVec2,
    logical_size: UVec2,
    mode:         WindowMode,
    monitor:      usize,
    scale:        f64,
}

/// Emit `WindowRestored` and clean up `TargetPosition` when settle succeeds.
fn emit_settle_success(
    commands: &mut Commands,
    entity: Entity,
    key: WindowKey,
    target: &SettleTarget,
    total_elapsed_ms: f32,
    stability_elapsed_ms: f32,
) {
    info!(
        "[check_restore_settling] [{key}] Settled after {total_elapsed_ms:.0}ms \
         (stable for {stability_elapsed_ms:.0}ms)"
    );
    commands
        .entity(entity)
        .trigger(|entity| WindowRestored {
            entity,
            window_id: key,
            position: target.position,
            size: target.size,
            logical_size: target.logical_size,
            mode: target.mode,
            monitor_index: target.monitor,
        })
        .remove::<TargetPosition>()
        .remove::<X11FrameCompensated>();
}

/// Emit `WindowRestoreMismatch` and clean up `TargetPosition` when settle times out.
fn emit_settle_mismatch(
    commands: &mut Commands,
    entity: Entity,
    key: WindowKey,
    target: &SettleTarget,
    actual: &SettleActual,
    total_elapsed_ms: f32,
) {
    warn!(
        "[check_restore_settling] [{key}] Settle timeout after {total_elapsed_ms:.0}ms — \
         mismatch remains: \
         position: {:?} vs {:?}, \
         size: {} vs {}, \
         mode: {:?} vs {:?}, \
         monitor: {} vs {}, \
         scale: {} vs {}",
        target.position,
        actual.snapshot.position,
        target.size,
        actual.snapshot.size,
        target.mode,
        actual.snapshot.mode,
        target.monitor,
        actual.snapshot.monitor,
        target.scale,
        actual.scale,
    );
    commands
        .entity(entity)
        .trigger(|entity| WindowRestoreMismatch {
            entity,
            window_id: key,
            expected_position: target.position,
            actual_position: actual.snapshot.position,
            expected_size: target.size,
            actual_size: actual.snapshot.size,
            expected_logical_size: target.logical_size,
            actual_logical_size: actual.logical_size,
            expected_mode: target.mode,
            actual_mode: actual.snapshot.mode,
            expected_monitor: target.monitor,
            actual_monitor: actual.snapshot.monitor,
            expected_scale: target.scale,
            actual_scale: actual.scale,
        })
        .remove::<TargetPosition>()
        .remove::<X11FrameCompensated>();
}

/// Result of attempting to apply a window restore.
enum RestoreStatus {
    /// Restore completed successfully.
    Complete,
    /// Waiting for conditions to be met (scale change, window position, etc.).
    Waiting,
}

/// Get window position from the OS via winit, falling back to `Window.position`.
///
/// On macOS, `Window.position` stays `Automatic` even after the OS places the window,
/// so we must query winit directly. On Linux with W5 workaround, we also use winit
/// to get `outer_position` (frame origin). On other platforms, `Window.position` suffices.
fn get_window_position(entity: Entity, window: &Window) -> Option<IVec2> {
    #[cfg(any(
        target_os = "macos",
        all(target_os = "linux", feature = "workaround-winit-4443")
    ))]
    {
        let _ = window;
        WINIT_WINDOWS.with(|ww| {
            let ww = ww.borrow();
            let winit_win = ww.get_window(entity)?;
            let outer_pos = winit_win.outer_position().ok()?;
            Some(IVec2::new(outer_pos.x, outer_pos.y))
        })
    }
    #[cfg(not(any(
        target_os = "macos",
        all(target_os = "linux", feature = "workaround-winit-4443")
    )))]
    {
        let _ = entity;
        match window.position {
            WindowPosition::At(p) => Some(p),
            _ => None,
        }
    }
}

/// Unified monitor detection system. Maintains `CurrentMonitor` on all managed windows.
///
/// Detection priority:
/// 1. winit's `current_monitor()` — most reliable, works even before `window.position` is set
/// 2. Position-based center-point detection — uses `window.position` when available
/// 3. Existing `CurrentMonitor` value — preserves last-known monitor during transient states
/// 4. `monitors.first()` — last resort fallback
///
/// All platforms: computes `effective_mode` (handles macOS green button fullscreen)
pub(crate) fn update_current_monitor(
    mut commands: Commands,
    windows: Query<
        (Entity, &Window, Option<&CurrentMonitor>),
        Or<(With<PrimaryWindow>, With<ManagedWindow>)>,
    >,
    monitors: Res<Monitors>,
    _non_send: NonSendMarker,
) {
    if monitors.is_empty() {
        return;
    }

    for (entity, window, existing) in &windows {
        let winit_result = winit_detect_monitor(entity, &monitors);
        let position_result = if winit_result.is_none() {
            position_detect_monitor(window, &monitors)
        } else {
            None
        };

        let (monitor_info, source) = match (winit_result, position_result, existing) {
            (Some(info), _, _) => (info, "winit"),
            (_, Some(info), _) => (info, "position"),
            (_, _, Some(cm)) => (cm.monitor, "existing"),
            _ => (*monitors.first(), "fallback"),
        };

        // Compute effective mode
        let effective_mode = compute_effective_mode(window, &monitor_info, &monitors);

        let new_current = CurrentMonitor {
            monitor: monitor_info,
            effective_mode,
        };

        // Only insert if changed to avoid unnecessary change detection triggers
        let changed = existing.is_none_or(|cm| {
            cm.monitor.index != new_current.monitor.index
                || cm.effective_mode != new_current.effective_mode
        });

        if changed {
            debug!(
                "[update_current_monitor] source={} index={} scale={} effective_mode={:?}",
                source, monitor_info.index, monitor_info.scale, effective_mode
            );
            commands.entity(entity).insert(new_current);
        }
    }
}

/// Detect monitor via winit's `current_monitor()`.
fn winit_detect_monitor(entity: Entity, monitors: &Monitors) -> Option<MonitorInfo> {
    WINIT_WINDOWS.with(|ww| {
        let ww = ww.borrow();
        ww.get_window(entity).and_then(|winit_window| {
            winit_window.current_monitor().and_then(|current_monitor| {
                let pos = current_monitor.position();
                monitors.at(pos.x, pos.y).copied()
            })
        })
    })
}

/// Detect monitor from `window.position` using center-point logic.
fn position_detect_monitor(window: &Window, monitors: &Monitors) -> Option<MonitorInfo> {
    if let WindowPosition::At(pos) = window.position {
        Some(*monitors.monitor_for_window(pos, window.physical_width(), window.physical_height()))
    } else {
        None
    }
}

/// Compute the effective window mode, including macOS green button detection.
///
/// On macOS, clicking the green "maximize" button fills the screen but `window.mode`
/// remains `Windowed`. This detects that case and returns `BorderlessFullscreen`.
fn compute_effective_mode(
    window: &Window,
    monitor_info: &MonitorInfo,
    monitors: &Monitors,
) -> WindowMode {
    // Trust exclusive fullscreen - OS manages this mode
    if matches!(window.mode, WindowMode::Fullscreen(_, _)) {
        return window.mode;
    }

    // Can't determine effective mode without monitors
    if monitors.is_empty() {
        return window.mode;
    }

    // On Wayland, position is unavailable so we can only trust self.mode
    let WindowPosition::At(pos) = window.position else {
        return window.mode;
    };

    // Check if window spans full width and reaches bottom of monitor
    let full_width = window.physical_width() == monitor_info.size.x;
    let left_aligned = pos.x == monitor_info.position.x;
    let reaches_bottom = pos.y + window.physical_height().to_i32()
        == monitor_info.position.y + monitor_info.size.y.to_i32();

    if full_width && left_aligned && reaches_bottom {
        WindowMode::BorderlessFullscreen(MonitorSelection::Index(monitor_info.index))
    } else {
        WindowMode::Windowed
    }
}

/// Apply fullscreen mode, handling Wayland limitations.
fn apply_fullscreen_restore(target: &TargetPosition, window: &mut Window, platform: Platform) {
    let monitor_index = target.target_monitor_index;

    // On Wayland, exclusive fullscreen is not supported by winit, so restore as
    // borderless fullscreen instead.
    let window_mode = if platform.exclusive_fullscreen_fallback()
        && matches!(target.mode, SavedWindowMode::Fullscreen { .. })
    {
        warn!(
            "Exclusive fullscreen is not supported on Wayland, restoring as BorderlessFullscreen"
        );
        WindowMode::BorderlessFullscreen(MonitorSelection::Index(monitor_index))
    } else {
        target.mode.to_window_mode(monitor_index)
    };

    debug!(
        "[Restore] Applying fullscreen mode {:?} on monitor {} -> WindowMode::{:?}",
        target.mode, monitor_index, window_mode
    );
    debug!(
        "[Restore] Current window state: position={:?} mode={:?}",
        window.position, window.mode
    );

    window.mode = window_mode;
}

/// Handle the initial move for cross-DPI strategies (`HigherToLower`, `CompensateSizeOnly`).
///
/// When position is available, starts the two-phase dance: move to trigger DPI change,
/// then wait for `ScaleFactorChanged` to apply final size.
///
/// When position is `None` (e.g., macOS first launch where `Window.position` stays
/// `Automatic`), the window can't move to the target monitor, so the two-phase dance
/// would wait for a `ScaleFactorChanged` that never arrives. Instead, recompute the
/// physical size for the starting monitor's scale and apply directly.
///
/// Returns `true` if the caller should `continue` (skip to next entity).
fn try_cross_dpi_initial_move(target: &mut TargetPosition, window: &mut Window) -> bool {
    if target.position.is_none() {
        let width = (f64::from(target.logical_width) * target.starting_scale).to_u32();
        let height = (f64::from(target.logical_height) * target.starting_scale).to_u32();
        debug!(
            "[restore_windows] No position for cross-DPI restore, applying logical size \
             {}x{} at starting_scale={} (physical {}x{}) instead of two-phase dance",
            target.logical_width, target.logical_height, target.starting_scale, width, height
        );
        window.resolution.set_physical_resolution(width, height);
        window.visible = true;
        target.settle_state = Some(SettleState::new());
        return true;
    }
    apply_initial_move(target, window);
    target.scale_strategy = match target.scale_strategy {
        MonitorScaleStrategy::HigherToLower(_) => {
            MonitorScaleStrategy::HigherToLower(WindowRestoreState::WaitingForScaleChange)
        },
        _ => MonitorScaleStrategy::CompensateSizeOnly(WindowRestoreState::WaitingForScaleChange),
    };
    true
}

/// Apply position and/or size to window with logging.
fn apply_window_geometry(
    window: &mut Window,
    position: Option<IVec2>,
    size: UVec2,
    strategy: &str,
    ratio: Option<f64>,
) {
    if let Some(pos) = position {
        if let Some(r) = ratio {
            debug!(
                "[try_apply_restore] position={:?} size={}x{} ({strategy}, ratio={r})",
                pos, size.x, size.y
            );
        } else {
            debug!(
                "[try_apply_restore] position={:?} size={}x{} ({strategy})",
                pos, size.x, size.y
            );
        }
        window.position = WindowPosition::At(pos);
    } else if let Some(r) = ratio {
        debug!(
            "[try_apply_restore] size={}x{} only ({strategy}, ratio={r}, no position)",
            size.x, size.y
        );
    } else {
        debug!(
            "[try_apply_restore] size={}x{} only ({strategy}, no position)",
            size.x, size.y
        );
    }
    window.resolution.set_physical_resolution(size.x, size.y);
}

/// Try to apply a pending window restore.
fn try_apply_restore(
    target: &TargetPosition,
    window: &mut Window,
    platform: Platform,
) -> RestoreStatus {
    // Handle fullscreen modes - use saved monitor index from TargetPosition
    if target.mode.is_fullscreen() {
        debug!(
            "[try_apply_restore] fullscreen: mode={:?} target_monitor={} current_physical={}x{} current_mode={:?} current_pos={:?}",
            target.mode,
            target.target_monitor_index,
            window.physical_width(),
            window.physical_height(),
            window.mode,
            window.position,
        );
        apply_fullscreen_restore(target, window, platform);

        window.visible = true;
        return RestoreStatus::Complete;
    }

    debug!(
        "[Restore] target_pos={:?} target_scale={} strategy={:?}",
        target.position, target.target_scale, target.scale_strategy
    );

    match target.scale_strategy {
        MonitorScaleStrategy::ApplyUnchanged => {
            apply_window_geometry(
                window,
                target.position(),
                target.size(),
                "ApplyUnchanged",
                None,
            );
        },
        MonitorScaleStrategy::CompensateSizeOnly(WindowRestoreState::ApplySize) => {
            let size = target.size();
            debug!(
                "[try_apply_restore] size={}x{} ONLY (CompensateSizeOnly::ApplySize, position already set)",
                size.x, size.y
            );
            window.resolution.set_physical_resolution(size.x, size.y);
        },
        MonitorScaleStrategy::CompensateSizeOnly(
            WindowRestoreState::NeedInitialMove | WindowRestoreState::WaitingForScaleChange,
        ) => {
            debug!(
                "[Restore] CompensateSizeOnly: waiting for initial move or ScaleChanged message"
            );
            return RestoreStatus::Waiting;
        },
        MonitorScaleStrategy::LowerToHigher => {
            apply_window_geometry(
                window,
                target.compensated_position(),
                target.compensated_size(),
                "LowerToHigher",
                Some(target.ratio()),
            );
        },
        MonitorScaleStrategy::HigherToLower(WindowRestoreState::ApplySize) => {
            let size = target.size();
            debug!(
                "[try_apply_restore] size={}x{} ONLY (HigherToLower::ApplySize, position already set)",
                size.x, size.y
            );
            window.resolution.set_physical_resolution(size.x, size.y);
        },
        MonitorScaleStrategy::HigherToLower(
            WindowRestoreState::NeedInitialMove | WindowRestoreState::WaitingForScaleChange,
        ) => {
            debug!("[Restore] HigherToLower: waiting for initial move or ScaleChanged message");
            return RestoreStatus::Waiting;
        },
    }

    // Show window now that restore is complete
    window.visible = true;
    RestoreStatus::Complete
}

#[cfg(test)]
mod tests {
    use bevy::window::MonitorSelection;
    use bevy::window::VideoModeSelection;
    use bevy::window::WindowMode;
    use bevy::window::WindowPosition;

    use super::*;

    fn monitor_0() -> MonitorInfo {
        MonitorInfo {
            index:    0,
            scale:    2.0,
            position: IVec2::ZERO,
            size:     UVec2::new(3456, 2234),
        }
    }

    fn monitors_with(info: MonitorInfo) -> Monitors { Monitors { list: vec![info] } }

    fn window_at(pos: IVec2, width: u32, height: u32) -> Window {
        let mut window = Window {
            position: WindowPosition::At(pos),
            mode: WindowMode::Windowed,
            ..Default::default()
        };
        window.resolution.set_physical_resolution(width, height);
        window
    }

    #[test]
    fn effective_mode_fullscreen_when_window_fills_monitor() {
        let mon = monitor_0();
        let monitors = monitors_with(mon);
        let window = window_at(mon.position, mon.size.x, mon.size.y);

        let mode = compute_effective_mode(&window, &mon, &monitors);
        assert_eq!(
            mode,
            WindowMode::BorderlessFullscreen(MonitorSelection::Index(0))
        );
    }

    #[test]
    fn effective_mode_windowed_when_window_smaller_than_monitor() {
        let mon = monitor_0();
        let monitors = monitors_with(mon);
        let window = window_at(IVec2::new(100, 100), 1600, 1200);

        let mode = compute_effective_mode(&window, &mon, &monitors);
        assert_eq!(mode, WindowMode::Windowed);
    }

    #[test]
    fn effective_mode_windowed_when_not_left_aligned() {
        let mon = monitor_0();
        let monitors = monitors_with(mon);
        // Full width + reaches bottom, but offset from left edge
        let window = window_at(IVec2::new(1, 0), mon.size.x, mon.size.y);

        let mode = compute_effective_mode(&window, &mon, &monitors);
        assert_eq!(mode, WindowMode::Windowed);
    }

    #[test]
    fn effective_mode_trusts_exclusive_fullscreen() {
        let mon = monitor_0();
        let monitors = monitors_with(mon);
        let mut window = window_at(IVec2::ZERO, 800, 600);
        window.mode =
            WindowMode::Fullscreen(MonitorSelection::Index(0), VideoModeSelection::Current);

        let mode = compute_effective_mode(&window, &mon, &monitors);
        assert!(matches!(mode, WindowMode::Fullscreen(_, _)));
    }

    #[test]
    fn effective_mode_returns_mode_when_no_position() {
        let mon = monitor_0();
        let monitors = monitors_with(mon);
        let mut window = Window::default();
        window
            .resolution
            .set_physical_resolution(mon.size.x, mon.size.y);
        // position is Automatic (no position available, like Wayland)

        let mode = compute_effective_mode(&window, &mon, &monitors);
        assert_eq!(mode, WindowMode::Windowed);
    }

    #[test]
    fn effective_mode_returns_mode_when_no_monitors() {
        let mon = monitor_0();
        let empty = Monitors { list: vec![] };
        let window = window_at(IVec2::ZERO, mon.size.x, mon.size.y);

        let mode = compute_effective_mode(&window, &mon, &empty);
        assert_eq!(mode, WindowMode::Windowed);
    }
}