bevy_window_manager 0.20.0

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
//! Interactive example for testing window restoration, fullscreen modes, and multi-window
//! management.
//!
//! Run with: `cargo run --example restore_window`
//!
//! Controls (all windows):
//! - Press `Enter` for exclusive fullscreen (uses selected video mode)
//!   WARNING: Exclusive fullscreen on macOS may panic on exit due to winit bugs.
//!   See: <https://github.com/rust-windowing/winit/issues/3668>
//! - Press `B` for borderless fullscreen (recommended on macOS)
//! - Press `W` for windowed mode
//! - Press `Up`/`Down` to cycle through available video modes
//!
//! - Press `Space` to spawn a new managed window
//! - Press `P` to toggle persistence mode (`RememberAll` / `ActiveOnly`)
//! - Press `Ctrl+Shift+Backspace` to clear saved state and quit
//! - Press `Q` to quit
//!
//! Move and resize windows to test state persistence across restarts.

// Monitor dimensions always fit in i32
#![allow(clippy::cast_possible_wrap)]

use std::collections::HashMap;

use bevy::camera::RenderTarget;
use bevy::ecs::system::NonSendMarker;
use bevy::prelude::*;
use bevy::ui::UiTargetCamera;
use bevy::window::Monitor;
use bevy::window::MonitorSelection;
use bevy::window::PrimaryWindow;
use bevy::window::VideoMode;
use bevy::window::VideoModeSelection;
use bevy::window::WindowMode;
use bevy::window::WindowPosition;
use bevy::window::WindowRef;
use bevy::window::WindowScaleFactorChanged;
use bevy::winit::WINIT_WINDOWS;
use bevy_brp_extras::BrpExtrasPlugin;
use bevy_kana::ToU32;
use bevy_window_manager::CurrentMonitor;
use bevy_window_manager::ManagedWindow;
use bevy_window_manager::ManagedWindowPersistence;
use bevy_window_manager::Monitors;
use bevy_window_manager::WindowManagerPlugin;
use bevy_window_manager::WindowRestoreMismatch;
use bevy_window_manager::WindowRestored;

/// When set, keyboard input is suppressed (used by the test runner).
const TEST_MODE_ENV_VAR: &str = "BWM_TEST_MODE";

/// BRP-triggerable event to spawn a managed secondary window.
#[derive(Event, Reflect)]
#[reflect(Event)]
struct SpawnManagedWindow;

/// Set the focused window to borderless fullscreen.
#[derive(Event, Reflect)]
#[reflect(Event)]
struct SetBorderlessFullscreen;

/// Set the focused window to windowed mode.
#[derive(Event, Reflect)]
#[reflect(Event)]
struct SetWindowed;

/// Set the focused window to exclusive fullscreen with the currently selected video mode.
#[derive(Event, Reflect)]
#[reflect(Event)]
struct SetExclusiveFullscreen;

/// Toggle persistence mode between `RememberAll` and `ActiveOnly`.
#[derive(Event, Reflect)]
#[reflect(Event)]
struct TogglePersistence;

/// Clear saved state file and quit.
#[derive(Event, Reflect)]
#[reflect(Event)]
struct ClearStateAndQuit;

/// Quit the app gracefully.
#[derive(Event, Reflect)]
#[reflect(Event)]
struct QuitApp;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins.set(WindowPlugin {
            primary_window: Some(Window {
                title: "Window Restore - Primary Window".into(),
                ..default()
            }),
            ..default()
        }))
        .add_plugins(WindowManagerPlugin)
        .add_plugins(BrpExtrasPlugin::default())
        .add_observer(on_spawn_managed_window)
        .add_observer(on_window_restored)
        .add_observer(on_window_restore_mismatch)
        .add_observer(on_secondary_window_added)
        .add_observer(on_secondary_window_removed)
        .add_observer(on_set_borderless_fullscreen)
        .add_observer(on_set_windowed)
        .add_observer(on_set_exclusive_fullscreen)
        .add_observer(on_toggle_persistence)
        .add_observer(on_clear_state_and_quit)
        .add_observer(on_quit_app)
        .insert_resource(TestMode(std::env::var(TEST_MODE_ENV_VAR).is_ok()))
        .init_resource::<SelectedVideoModes>()
        .init_resource::<WindowCounter>()
        .init_resource::<RestoredStates>()
        .init_resource::<MismatchStates>()
        .init_resource::<WindowsSettledCount>()
        .add_systems(Startup, setup)
        .add_systems(
            Update,
            (
                update_primary_display,
                update_secondary_displays,
                handle_global_input.run_if(keyboard_enabled),
                handle_window_mode_input.run_if(keyboard_enabled),
                debug_winit_monitor,
                debug_window_changed,
                debug_scale_factor_changed,
            ),
        )
        .run();
}

// --- Resources ---

/// When true, keyboard input is suppressed so the test script can control the app via BRP.
#[derive(Resource)]
struct TestMode(bool);

fn keyboard_enabled(test_mode: Res<TestMode>) -> bool { !test_mode.0 }

/// Tracks the next window number for auto-incrementing names.
#[derive(Resource, Default)]
struct WindowCounter {
    next: usize,
}

/// Tracks the selected video mode index per monitor for exclusive fullscreen.
#[derive(Resource, Default)]
struct SelectedVideoModes {
    /// Selected index per monitor (keyed by monitor index).
    indices:   HashMap<usize, usize>,
    /// Track last synced mode to avoid overriding user selection.
    last_sync: Option<(UVec2, u32)>,
}

impl SelectedVideoModes {
    fn get(&self, monitor_index: usize) -> usize {
        self.indices.get(&monitor_index).copied().unwrap_or(0)
    }

    fn set(&mut self, monitor_index: usize, index: usize) {
        self.indices.insert(monitor_index, index);
    }
}

// --- Components ---

/// Marker for the primary window's text display.
#[derive(Component)]
struct PrimaryDisplay;

/// Marker for a secondary window's text display, storing the window entity.
#[derive(Component)]
struct SecondaryDisplay(Entity);

// --- WindowRestored Test Support ---

/// Resource inserted when `WindowRestored` event is received.
/// Queryable via BRP to verify the event fired with expected values.
#[derive(Resource, Debug, Clone, Reflect)]
#[reflect(Resource)]
struct WindowRestoredReceived {
    position:      Option<IVec2>,
    size:          UVec2,
    mode:          WindowMode,
    monitor_index: usize,
}

/// Resource inserted when `WindowRestoreMismatch` event is received.
/// Queryable via BRP to verify the event fired.
#[derive(Resource, Debug, Clone, Reflect)]
#[reflect(Resource)]
struct WindowRestoreMismatchReceived {
    expected_monitor: usize,
    actual_monitor:   usize,
    expected_size:    UVec2,
    actual_size:      UVec2,
    expected_mode:    WindowMode,
    actual_mode:      WindowMode,
}

/// Count of windows that have completed settling (restored or mismatched).
/// Queryable via BRP so the test script can wait for all windows to settle.
#[derive(Resource, Debug, Default, Reflect)]
#[reflect(Resource)]
struct WindowsSettledCount {
    count: usize,
}

/// Cached mismatch state per window for display.
#[derive(Clone)]
struct CachedMismatchState {
    expected_position:     Option<IVec2>,
    actual_position:       Option<IVec2>,
    expected_size:         UVec2,
    actual_size:           UVec2,
    expected_logical_size: UVec2,
    actual_logical_size:   UVec2,
    expected_mode:         WindowMode,
    actual_mode:           WindowMode,
    expected_monitor:      usize,
    actual_monitor:        usize,
    expected_scale:        f64,
    actual_scale:          f64,
}

/// Per-entity mismatch states for display.
#[derive(Resource, Default)]
struct MismatchStates {
    states: HashMap<Entity, CachedMismatchState>,
}

/// Cached restored state per window, populated from `WindowRestored` events.
/// Used for the "File" column comparison display.
#[derive(Resource, Default)]
struct RestoredStates {
    states: HashMap<Entity, CachedRestoredState>,
}

/// State cached from a `WindowRestored` event for display comparison.
struct CachedRestoredState {
    position:       Option<IVec2>,
    width:          u32,
    height:         u32,
    logical_width:  u32,
    logical_height: u32,
    monitor_index:  usize,
    mode:           WindowMode,
}

// --- Constants ---

const MARGIN: Val = Val::Px(20.0);
const FONT_SIZE: f32 = 14.0;
const SECONDARY_WINDOW_WIDTH: u32 = 600;
const SECONDARY_WINDOW_HEIGHT: u32 = 400;
const MISMATCH_COLOR: Color = Color::linear_rgb(1.0, 0.3, 0.3);
const MISMATCH_WARN_COLOR: Color = Color::linear_rgb(1.0, 0.7, 0.2);
const DEFAULT_COLOR: Color = Color::WHITE;
const LABEL_WIDTH: usize = 18;

// --- Setup ---

fn setup(mut commands: Commands) {
    commands.spawn(Camera2d);

    commands.spawn((
        Text::new(""),
        TextFont {
            font_size: FONT_SIZE,
            ..default()
        },
        Node {
            position_type: PositionType::Absolute,
            top: MARGIN,
            left: MARGIN,
            ..default()
        },
        PrimaryDisplay,
    ));
}

// --- SpawnManagedWindow Observer ---

/// Observer: spawn a new managed secondary window.
fn on_spawn_managed_window(
    _trigger: On<SpawnManagedWindow>,
    mut commands: Commands,
    mut counter: ResMut<WindowCounter>,
) {
    counter.next += 1;
    let name = format!("window-{}", counter.next);
    let title = format!("Managed: {name}");

    commands.spawn((
        Window {
            title,
            resolution: bevy::window::WindowResolution::new(
                SECONDARY_WINDOW_WIDTH,
                SECONDARY_WINDOW_HEIGHT,
            ),
            ..default()
        },
        ManagedWindow {
            window_name: name.clone(),
        },
    ));

    info!("[restore_window] Spawned managed window \"{name}\"");
}

// --- Secondary Window Lifecycle ---

/// Observer: spawn `Camera2d` and text display when a `ManagedWindow` is added.
fn on_secondary_window_added(
    add: On<Add, ManagedWindow>,
    mut commands: Commands,
    primary_q: Query<(), With<PrimaryWindow>>,
) {
    let entity = add.entity;
    if primary_q.get(entity).is_ok() {
        return;
    }

    let camera = commands
        .spawn((Camera2d, RenderTarget::Window(WindowRef::Entity(entity))))
        .id();

    commands.spawn((
        Text::new(""),
        TextFont {
            font_size: FONT_SIZE,
            ..default()
        },
        Node {
            position_type: PositionType::Absolute,
            top: MARGIN,
            left: MARGIN,
            ..default()
        },
        UiTargetCamera(camera),
        SecondaryDisplay(entity),
    ));
}

/// Observer: clean up display entities when a `ManagedWindow` is removed.
fn on_secondary_window_removed(
    remove: On<Remove, ManagedWindow>,
    mut commands: Commands,
    displays: Query<(Entity, &SecondaryDisplay)>,
) {
    let entity = remove.entity;
    for (display_entity, display) in &displays {
        if display.0 == entity {
            commands.entity(display_entity).despawn();
        }
    }
}

// --- Comparison Display ---

/// Formatted current window values for comparison display.
struct CurrentValues {
    position:  String,
    size_phys: String,
    size_log:  String,
    scale:     String,
    monitor:   String,
    mode:      String,
}

/// Build comparison spans (restored vs current) for a window and add them as `TextSpan` children.
fn build_comparison_spans(
    cb: &mut ChildSpawnerCommands,
    restored_state: Option<&CachedRestoredState>,
    mismatch_state: Option<&CachedMismatchState>,
    window: &Window,
    monitor: &CurrentMonitor,
    font: &TextFont,
) {
    let effective_mode = monitor.effective_mode;
    let scale = window.resolution.scale_factor();

    let current = CurrentValues {
        position:  match window.position {
            WindowPosition::At(pos) => format!("({}, {})", pos.x, pos.y),
            _ => "Automatic".to_string(),
        },
        size_phys: format!("{}x{}", window.physical_width(), window.physical_height()),
        size_log:  format!(
            "{}x{}",
            window.resolution.width().to_u32(),
            window.resolution.height().to_u32()
        ),
        scale:     format!("{scale}"),
        monitor:   format!("{}", monitor.index),
        mode:      format!("{effective_mode:?}"),
    };

    if let Some(state) = restored_state {
        build_restored_spans(cb, state, mismatch_state, &current, font);
    } else {
        build_current_only_spans(cb, &current, font);
    }

    add_span(
        cb,
        font,
        &format!("\nEffective Mode: {effective_mode:?}\n"),
        DEFAULT_COLOR,
    );
}

/// Render comparison rows when restore data is available.
#[expect(
    clippy::too_many_lines,
    reason = "UI builder — splitting would scatter tightly-coupled formatting logic"
)]
fn build_restored_spans(
    cb: &mut ChildSpawnerCommands,
    state: &CachedRestoredState,
    mismatch_state: Option<&CachedMismatchState>,
    current: &CurrentValues,
    font: &TextFont,
) {
    let file_pos = state
        .position
        .map_or_else(|| "None".to_string(), |p| format!("({}, {})", p.x, p.y));
    let file_size_phys = format!("{}x{}", state.width, state.height);
    let file_size_log = format!("{}x{}", state.logical_width, state.logical_height);
    let file_monitor = format!("{}", state.monitor_index);
    let file_mode = format!("{:?}", state.mode);

    let col1_width = [
        file_pos.len(),
        file_size_phys.len(),
        file_monitor.len(),
        file_mode.len(),
    ]
    .into_iter()
    .max()
    .unwrap_or(0)
        + 2;
    let col1_width = col1_width.max(16);

    // Header
    if mismatch_state.is_some() {
        let header = format!(
            "{:LABEL_WIDTH$}{:<col1_width$}{:<col1_width$}{:<col1_width$}{}\n",
            "", "Restored", "Current", "Expected", "Actual"
        );
        add_span(cb, font, &header, DEFAULT_COLOR);
    } else {
        let header = format!(
            "{:LABEL_WIDTH$}{:<col1_width$}{}\n",
            "", "Restored", "Current"
        );
        add_span(cb, font, &header, DEFAULT_COLOR);
    }

    // Position
    let mm = mismatch_state.map(|m| {
        let exp = m
            .expected_position
            .map_or_else(|| "None".to_string(), |p| format!("({}, {})", p.x, p.y));
        let act = m
            .actual_position
            .map_or_else(|| "None".to_string(), |p| format!("({}, {})", p.x, p.y));
        (exp, act)
    });
    add_row(
        cb,
        font,
        "Position:",
        &file_pos,
        &current.position,
        mm.as_ref(),
        col1_width,
    );

    // Size (physical)
    let mm = mismatch_state.map(|m| {
        (
            format!("{}x{}", m.expected_size.x, m.expected_size.y),
            format!("{}x{}", m.actual_size.x, m.actual_size.y),
        )
    });
    add_row(
        cb,
        font,
        "Size (physical):",
        &file_size_phys,
        &current.size_phys,
        mm.as_ref(),
        col1_width,
    );

    // Size (logical)
    let mm = mismatch_state.map(|m| {
        (
            format!(
                "{}x{}",
                m.expected_logical_size.x, m.expected_logical_size.y
            ),
            format!("{}x{}", m.actual_logical_size.x, m.actual_logical_size.y),
        )
    });
    add_row(
        cb,
        font,
        "Size (logical):",
        &file_size_log,
        &current.size_log,
        mm.as_ref(),
        col1_width,
    );

    // Scale (no file value; custom no-mismatch rendering)
    if let Some(m) = mismatch_state {
        let exp_scale = format!("{}", m.expected_scale);
        let act_scale = format!("{}", m.actual_scale);
        add_comparison_row_5(
            cb,
            font,
            "Scale:",
            "",
            &current.scale,
            &exp_scale,
            &act_scale,
            col1_width,
        );
    } else {
        add_span(
            cb,
            font,
            &format!(
                "{:<LABEL_WIDTH$}{:<col1_width$}{}\n",
                "Scale:", "", current.scale
            ),
            DEFAULT_COLOR,
        );
    }

    // Monitor
    let mm = mismatch_state.map(|m| {
        (
            format!("{}", m.expected_monitor),
            format!("{}", m.actual_monitor),
        )
    });
    add_row(
        cb,
        font,
        "Monitor:",
        &file_monitor,
        &current.monitor,
        mm.as_ref(),
        col1_width,
    );

    // Mode
    let mm = mismatch_state.map(|m| {
        (
            format!("{:?}", m.expected_mode),
            format!("{:?}", m.actual_mode),
        )
    });
    add_row(
        cb,
        font,
        "Mode:",
        &file_mode,
        &current.mode,
        mm.as_ref(),
        col1_width,
    );
}

/// Render current-only values when no restore data exists.
fn build_current_only_spans(
    cb: &mut ChildSpawnerCommands,
    current: &CurrentValues,
    font: &TextFont,
) {
    add_span(cb, font, "State: No restore data\n\n", MISMATCH_COLOR);
    add_span(
        cb,
        font,
        &format!("{:<LABEL_WIDTH$}{}\n", "Position:", current.position),
        DEFAULT_COLOR,
    );
    add_span(
        cb,
        font,
        &format!(
            "{:<LABEL_WIDTH$}{}\n",
            "Size (physical):", current.size_phys
        ),
        DEFAULT_COLOR,
    );
    add_span(
        cb,
        font,
        &format!("{:<LABEL_WIDTH$}{}\n", "Size (logical):", current.size_log),
        DEFAULT_COLOR,
    );
    add_span(
        cb,
        font,
        &format!("{:<LABEL_WIDTH$}{}\n", "Scale:", current.scale),
        DEFAULT_COLOR,
    );
    add_span(
        cb,
        font,
        &format!("{:<LABEL_WIDTH$}{}\n", "Monitor:", current.monitor),
        DEFAULT_COLOR,
    );
    add_span(
        cb,
        font,
        &format!("{:<LABEL_WIDTH$}{}\n", "Mode:", current.mode),
        DEFAULT_COLOR,
    );
}

/// Add a comparison row, dispatching to 3-column or 5-column layout based on mismatch data.
fn add_row(
    cb: &mut ChildSpawnerCommands,
    font: &TextFont,
    label: &str,
    file_val: &str,
    current_val: &str,
    mismatch: Option<&(String, String)>,
    col_width: usize,
) {
    if let Some((expected, actual)) = mismatch {
        add_comparison_row_5(
            cb,
            font,
            label,
            file_val,
            current_val,
            expected,
            actual,
            col_width,
        );
    } else {
        add_comparison_row(cb, font, label, file_val, current_val, col_width);
    }
}

/// Add a comparison row: label + file value (white) + current value (white or red if mismatch).
fn add_comparison_row(
    cb: &mut ChildSpawnerCommands,
    font: &TextFont,
    label: &str,
    file_val: &str,
    current_val: &str,
    col_width: usize,
) {
    let color = if file_val == current_val {
        DEFAULT_COLOR
    } else {
        MISMATCH_COLOR
    };

    // Label + file value (always white)
    add_span(
        cb,
        font,
        &format!("{label:<LABEL_WIDTH$}{file_val:<col_width$}"),
        DEFAULT_COLOR,
    );
    // Current value (colored)
    add_span(cb, font, &format!("{current_val}\n"), color);
}

/// Add a 5-column comparison row: label + restored + current + expected + actual.
/// Expected/actual columns use warning color when they differ.
fn add_comparison_row_5(
    cb: &mut ChildSpawnerCommands,
    font: &TextFont,
    label: &str,
    file_val: &str,
    current_val: &str,
    expected_val: &str,
    actual_val: &str,
    col_width: usize,
) {
    let current_color = if file_val == current_val {
        DEFAULT_COLOR
    } else {
        MISMATCH_COLOR
    };
    let mismatch_color = if expected_val == actual_val {
        DEFAULT_COLOR
    } else {
        MISMATCH_WARN_COLOR
    };

    // Label + restored value (always white)
    add_span(
        cb,
        font,
        &format!("{label:<LABEL_WIDTH$}{file_val:<col_width$}"),
        DEFAULT_COLOR,
    );
    // Current value
    add_span(
        cb,
        font,
        &format!("{current_val:<col_width$}"),
        current_color,
    );
    // Expected value (always white)
    add_span(
        cb,
        font,
        &format!("{expected_val:<col_width$}"),
        DEFAULT_COLOR,
    );
    // Actual value (warning color if mismatch)
    add_span(cb, font, &format!("{actual_val}\n"), mismatch_color);
}

/// Add a single `TextSpan` child.
fn add_span(cb: &mut ChildSpawnerCommands, font: &TextFont, text: &str, color: Color) {
    cb.spawn((TextSpan(text.to_string()), font.clone(), TextColor(color)));
}

// --- Primary Window Display ---

#[expect(
    clippy::too_many_arguments,
    reason = "Bevy system — each param is a distinct system resource"
)]
fn update_primary_display(
    primary_display: Single<Entity, With<PrimaryDisplay>>,
    window_query: Single<(Entity, &Window, &CurrentMonitor), With<PrimaryWindow>>,
    monitors_res: Res<Monitors>,
    bevy_monitors: Query<(Entity, &Monitor)>,
    mut selected: ResMut<SelectedVideoModes>,
    persistence: Res<ManagedWindowPersistence>,
    managed_q: Query<(&Window, &ManagedWindow, Option<&CurrentMonitor>)>,
    restored_states: Res<RestoredStates>,
    mismatch_states: Res<MismatchStates>,
    mut commands: Commands,
) {
    let display_entity = *primary_display;
    let (window_entity, window, monitor) = *window_query;

    let restored_state = restored_states.states.get(&window_entity);
    let mismatch_state = mismatch_states.states.get(&window_entity);

    let (video_modes, refresh_rate) = get_video_modes_for_monitor(&bevy_monitors, monitor);
    let refresh_display = format_refresh_rate(window, refresh_rate);
    let active_mode_idx = find_active_video_mode_index(window, &video_modes);
    sync_selected_to_active(window, monitor, active_mode_idx, &mut selected);
    let selected_idx = selected.get(monitor.index);
    let video_modes_display =
        build_video_modes_display(&video_modes, selected_idx, active_mode_idx);

    let font = TextFont {
        font_size: FONT_SIZE,
        ..default()
    };

    commands.entity(display_entity).despawn_children();
    commands.entity(display_entity).with_children(|cb| {
        // Monitor header
        let monitor_row = format_monitor_row(monitor, &refresh_display);
        add_span(cb, &font, &format!("{monitor_row}\n\n"), DEFAULT_COLOR);

        // Comparison table
        build_comparison_spans(cb, restored_state, mismatch_state, window, monitor, &font);

        // Video modes
        add_span(
            cb,
            &font,
            &format!("\nVideo Modes (Up/Down to select):\n{video_modes_display}\n"),
            DEFAULT_COLOR,
        );

        // Controls
        add_span(
            cb,
            &font,
            &format!(
                "\nControls:\n\
                 [Enter] Exclusive Fullscreen\n\
                 [B] Borderless Fullscreen\n\
                 [W] Windowed\n\
                 [Space] Spawn managed window\n\
                 [P] Toggle persistence ({persistence:?})\n\
                 [Ctrl+Shift+Backspace] Clear state and quit\n\
                 [Q] Quit\n"
            ),
            DEFAULT_COLOR,
        );

        // Managed windows list
        let mut managed_lines = Vec::new();
        for (mw, managed, current_monitor) in &managed_q {
            let mon = current_monitor.map_or_else(|| *monitors_res.first(), |cm| cm.monitor);
            let pos = match mw.position {
                WindowPosition::At(p) => format!("({}, {})", p.x, p.y),
                _ => "Automatic".to_string(),
            };
            managed_lines.push(format!(
                "  {}: pos={pos} phys={}x{} log={}x{} scale={} monitor={}\n",
                managed.window_name,
                mw.physical_width(),
                mw.physical_height(),
                mw.resolution.width().to_u32(),
                mw.resolution.height().to_u32(),
                mw.resolution.scale_factor(),
                mon.index,
            ));
        }
        let managed_header = "\nManaged Windows:\n";
        add_span(cb, &font, managed_header, DEFAULT_COLOR);
        if managed_lines.is_empty() {
            add_span(cb, &font, "  (none)\n", DEFAULT_COLOR);
        } else {
            for line in &managed_lines {
                add_span(cb, &font, line, DEFAULT_COLOR);
            }
        }
    });
}

// --- Secondary Window Displays ---

#[expect(
    clippy::too_many_arguments,
    reason = "Bevy system — each param is a distinct system resource"
)]
fn update_secondary_displays(
    mut displays: Query<(Entity, &SecondaryDisplay)>,
    windows: Query<(&Window, Option<&CurrentMonitor>)>,
    managed_q: Query<&ManagedWindow>,
    monitors_res: Res<Monitors>,
    bevy_monitors: Query<(Entity, &Monitor)>,
    mut selected: ResMut<SelectedVideoModes>,
    restored_states: Res<RestoredStates>,
    mismatch_states: Res<MismatchStates>,
    mut commands: Commands,
) {
    for (display_entity, display) in &mut displays {
        let Ok((window, current_monitor)) = windows.get(display.0) else {
            continue;
        };
        let monitor_info = current_monitor.copied().unwrap_or_else(|| CurrentMonitor {
            monitor:        *monitors_res.first(),
            effective_mode: window.mode,
        });

        let name = managed_q
            .get(display.0)
            .map_or("unknown", |m| &m.window_name);
        let restored_state = restored_states.states.get(&display.0);
        let mismatch_state = mismatch_states.states.get(&display.0);

        let (video_modes, refresh_rate) =
            get_video_modes_for_monitor(&bevy_monitors, &monitor_info);
        let refresh_display = format_refresh_rate(window, refresh_rate);
        let active_mode_idx = find_active_video_mode_index(window, &video_modes);
        sync_selected_to_active(window, &monitor_info, active_mode_idx, &mut selected);
        let selected_idx = selected.get(monitor_info.index);
        let video_modes_display =
            build_video_modes_display(&video_modes, selected_idx, active_mode_idx);

        let font = TextFont {
            font_size: FONT_SIZE,
            ..default()
        };

        commands.entity(display_entity).despawn_children();
        commands.entity(display_entity).with_children(|cb| {
            // Window name + monitor header
            let monitor_row = format_monitor_row(&monitor_info, &refresh_display);
            add_span(
                cb,
                &font,
                &format!("Window: {name}\n{monitor_row}\n\n"),
                DEFAULT_COLOR,
            );

            // Comparison table
            build_comparison_spans(
                cb,
                restored_state,
                mismatch_state,
                window,
                &monitor_info,
                &font,
            );

            // Video modes
            add_span(
                cb,
                &font,
                &format!("\nVideo Modes (Up/Down to select):\n{video_modes_display}\n"),
                DEFAULT_COLOR,
            );

            // Controls
            add_span(
                cb,
                &font,
                "\nControls:\n\
                 [Enter] Exclusive Fullscreen\n\
                 [B] Borderless Fullscreen\n\
                 [W] Windowed\n\
                 [Space] Spawn managed window\n\
                 [P] Toggle persistence\n\
                 [Ctrl+Shift+Backspace] Clear state and quit\n\
                 [Q] Quit\n",
                DEFAULT_COLOR,
            );
        });
    }
}

// --- Input Handling ---

/// Handle global inputs: spawn windows, toggle persistence, quit, reset.
///
/// These work from any focused window, not just the primary.
fn handle_global_input(
    keys: Res<ButtonInput<KeyCode>>,
    windows: Query<&Window>,
    mut commands: Commands,
) {
    // Only process input when any window is focused
    if !windows.iter().any(|w| w.focused) {
        return;
    }

    if keys.just_pressed(KeyCode::Space) {
        commands.trigger(SpawnManagedWindow);
    }
    if keys.just_pressed(KeyCode::KeyP) {
        commands.trigger(TogglePersistence);
    }
    // Ctrl+Shift+Backspace: clear saved state and exit
    if keys.just_pressed(KeyCode::Backspace)
        && keys.pressed(KeyCode::ShiftLeft)
        && keys.pressed(KeyCode::ControlLeft)
    {
        commands.trigger(ClearStateAndQuit);
    }
    if keys.just_pressed(KeyCode::KeyQ) {
        commands.trigger(QuitApp);
    }
}

/// Despawn all managed windows before writing `AppExit::Success`.
///
/// Bevy's graceful shutdown via `AppExit::Success` intermittently hangs on macOS
/// (spinning beach ball, requires force quit). This was reproduced in a bare Bevy
/// app with no plugins — it's a Bevy/winit issue, not ours. The hang is much more
/// reliable when `NSWindow.tabbingMode` is set to `Disallowed` (our tabbing fix).
///
/// The alternative — `std::process::exit(0)` — never hangs but panics when exiting
/// exclusive fullscreen with multiple windows, because it bypasses winit's cleanup
/// of fullscreen state before TLS destruction.
///
/// Despawning managed windows first lets them go through Bevy's normal window
/// teardown path (rendering thread gets notified), leaving only the primary window
/// for the `exiting()` callback to handle. This avoids the hang in practice.
fn despawn_managed_and_exit(
    managed_entities: &Query<Entity, With<ManagedWindow>>,
    commands: &mut Commands,
    app_exit: &mut MessageWriter<AppExit>,
) {
    for entity in managed_entities.iter() {
        commands.entity(entity).despawn();
    }
    app_exit.write(AppExit::Success);
}

/// Compute the state file path using the same logic as the plugin.
fn get_state_file_path() -> Option<std::path::PathBuf> {
    let exe_name = std::env::current_exe()
        .ok()?
        .file_stem()?
        .to_str()?
        .to_string();
    dirs::config_dir().map(|d| d.join(exe_name).join("windows.ron"))
}

/// Sync effective mode and handle video mode navigation / keyboard mode triggers.
fn handle_window_mode_input(
    keys: Res<ButtonInput<KeyCode>>,
    mut windows: Query<(Entity, &mut Window, Option<&CurrentMonitor>)>,
    monitors_res: Res<Monitors>,
    bevy_monitors: Query<(Entity, &Monitor)>,
    mut selected: ResMut<SelectedVideoModes>,
    restored_states: Res<RestoredStates>,
    mut commands: Commands,
) {
    // Find the focused window
    let Some((entity, mut window, current_monitor)) =
        windows.iter_mut().find(|(_, w, _)| w.focused)
    else {
        return;
    };

    let monitor = current_monitor.copied().unwrap_or_else(|| CurrentMonitor {
        monitor:        *monitors_res.first(),
        effective_mode: window.mode,
    });

    // Sync `window.mode` to the effective mode so bevy's cached state matches reality.
    // The OS can change fullscreen state (e.g. macOS green button) without updating
    // `window.mode`, causing bevy's `changed_windows` to skip the mode change.
    //
    // Skip sync when:
    // 1. Any fullscreen mode is set — the plugin or user intentionally set fullscreen, but the
    //    compositor may not have processed it yet. Syncing back to `Windowed` would cancel the
    //    pending fullscreen transition.
    // 2. Restore not yet complete — the plugin sets `window.mode` to the target fullscreen mode,
    //    but the transition hasn't completed so `effective_mode` still reads `Windowed`.
    let is_fullscreen = !matches!(window.mode, WindowMode::Windowed);
    let restore_complete = restored_states.states.contains_key(&entity);
    #[allow(clippy::suspicious_operation_groupings)]
    // intentional: compare cached mode vs effective
    if !is_fullscreen && restore_complete && window.mode != monitor.effective_mode {
        window.mode = monitor.effective_mode;
    }

    let video_modes: Vec<VideoMode> = bevy_monitors
        .iter()
        .find(|(_, m)| m.physical_position == monitor.position)
        .map(|(_, m)| m.video_modes.clone())
        .unwrap_or_default();

    // Navigate video modes
    let current_idx = selected.get(monitor.index);
    if keys.just_pressed(KeyCode::ArrowUp) && current_idx > 0 {
        selected.set(monitor.index, current_idx - 1);
    }
    if keys.just_pressed(KeyCode::ArrowDown) && current_idx < video_modes.len().saturating_sub(1) {
        selected.set(monitor.index, current_idx + 1);
    }

    if keys.just_pressed(KeyCode::Enter) {
        commands.trigger(SetExclusiveFullscreen);
    }
    if keys.just_pressed(KeyCode::KeyB) {
        commands.trigger(SetBorderlessFullscreen);
    }
    if keys.just_pressed(KeyCode::KeyW) {
        commands.trigger(SetWindowed);
    }
}

// --- Video Mode Helpers ---

/// Get video modes and refresh rate for the monitor matching the given position.
fn get_video_modes_for_monitor<'a>(
    bevy_monitors: &'a Query<(Entity, &Monitor)>,
    monitor: &CurrentMonitor,
) -> (Vec<&'a VideoMode>, Option<u32>) {
    bevy_monitors
        .iter()
        .find(|(_, m)| m.physical_position == monitor.position)
        .map(|(_, m)| {
            (
                m.video_modes.iter().collect(),
                m.refresh_rate_millihertz.map(|r| r / 1000),
            )
        })
        .unwrap_or_default()
}

/// Format refresh rate - use video mode rate in exclusive fullscreen, otherwise monitor rate.
fn format_refresh_rate(window: &Window, monitor_refresh: Option<u32>) -> String {
    let active_refresh = match &window.mode {
        WindowMode::Fullscreen(_, VideoModeSelection::Specific(mode)) => {
            Some(mode.refresh_rate_millihertz / 1000)
        },
        _ => monitor_refresh,
    };
    active_refresh.map_or_else(|| "N/A".into(), |hz| format!("{hz}Hz"))
}

/// Find the index of the currently active video mode if in exclusive fullscreen.
fn find_active_video_mode_index(window: &Window, video_modes: &[&VideoMode]) -> Option<usize> {
    match &window.mode {
        WindowMode::Fullscreen(_, VideoModeSelection::Specific(active)) => {
            video_modes.iter().position(|m| {
                m.physical_size == active.physical_size
                    && m.refresh_rate_millihertz == active.refresh_rate_millihertz
            })
        },
        _ => None,
    }
}

/// Sync selected video mode index to active mode when mode changes.
fn sync_selected_to_active(
    window: &Window,
    monitor: &CurrentMonitor,
    active_mode_idx: Option<usize>,
    selected: &mut SelectedVideoModes,
) {
    if let WindowMode::Fullscreen(_, VideoModeSelection::Specific(active)) = &window.mode {
        let current_mode = (active.physical_size, active.refresh_rate_millihertz);
        if selected.last_sync != Some(current_mode)
            && let Some(active_idx) = active_mode_idx
        {
            selected.set(monitor.index, active_idx);
            selected.last_sync = Some(current_mode);
        }
    } else {
        selected.last_sync = None;
    }
}

// --- Formatting Helpers ---

/// Get platform suffix for Linux (Wayland or X11).
///
/// Not const on Linux due to `std::env::var` check; clippy false positive on other platforms.
#[cfg_attr(not(target_os = "linux"), allow(clippy::missing_const_for_fn))]
fn platform_suffix() -> &'static str {
    #[cfg(target_os = "linux")]
    {
        if std::env::var("WAYLAND_DISPLAY")
            .map(|v| !v.is_empty())
            .unwrap_or(false)
        {
            " (Wayland)"
        } else {
            " (X11)"
        }
    }
    #[cfg(not(target_os = "linux"))]
    {
        ""
    }
}

/// Format the first row with monitor info.
fn format_monitor_row(monitor: &CurrentMonitor, refresh_display: &str) -> String {
    let primary_marker = if monitor.index == 0 {
        " Primary Monitor -"
    } else {
        " -"
    };
    format!(
        "Monitor: {}{primary_marker} Scale: {} - Refresh Rate: {refresh_display}{}",
        monitor.index,
        monitor.scale,
        platform_suffix()
    )
}

/// Builds the video modes display string showing a scrollable window of modes.
fn build_video_modes_display(
    video_modes: &[&VideoMode],
    selected_idx: usize,
    active_mode_idx: Option<usize>,
) -> String {
    if video_modes.is_empty() {
        return "  (no video modes available)".into();
    }

    let selected_idx = selected_idx.min(video_modes.len().saturating_sub(1));
    let len = video_modes.len();

    // Determine the visible window start position
    let start = if len <= 5 {
        // Show all modes if 5 or fewer
        0
    } else {
        // Center on active mode (slot 3 of 5) if it exists, otherwise center on selected
        let center_target = active_mode_idx.unwrap_or(selected_idx);

        // But always ensure selected is visible by adjusting if needed
        let ideal_start = center_target.saturating_sub(2);
        let ideal_end = ideal_start + 5;

        // Check if selected would be outside the ideal window
        if selected_idx < ideal_start {
            // Selected is above the window, scroll up to show it
            selected_idx.saturating_sub(2)
        } else if selected_idx >= ideal_end {
            // Selected is below the window, scroll down to show it
            (selected_idx + 3).saturating_sub(5)
        } else {
            // Selected is visible, use the ideal centering on active
            ideal_start
        }
        .min(len.saturating_sub(5))
    };
    let end = (start + 5).min(len);

    video_modes[start..end]
        .iter()
        .enumerate()
        .map(|(i, mode)| {
            let actual_idx = start + i;
            let left_marker = if actual_idx == selected_idx { ">" } else { " " };
            let right_marker = if Some(actual_idx) == active_mode_idx {
                " <- active"
            } else {
                ""
            };
            format!(
                "  {left_marker} {}x{} @ {}Hz{right_marker}",
                mode.physical_size.x,
                mode.physical_size.y,
                mode.refresh_rate_millihertz / 1000
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

// --- Debug Systems ---

/// Debug system that runs every frame and logs winit-detected monitor changes.
fn debug_winit_monitor(
    window: Single<Entity, With<PrimaryWindow>>,
    monitors: Res<Monitors>,
    mut cached_monitor: Local<Option<usize>>,
    _non_send: NonSendMarker,
) {
    let window_entity = *window;

    let winit_monitor_index: Option<usize> = WINIT_WINDOWS.with(|ww| {
        let ww = ww.borrow();
        ww.get_window(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).map(|mon| mon.index)
            })
        })
    });

    if *cached_monitor != winit_monitor_index {
        info!(
            "[debug_winit_monitor] Monitor changed: {:?} -> {:?}",
            *cached_monitor, winit_monitor_index
        );
        *cached_monitor = winit_monitor_index;
    }
}

/// Cached state for detecting what changed in Window component.
#[derive(Default)]
struct CachedWindowDebug {
    position: Option<WindowPosition>,
    width:    u32,
    height:   u32,
    mode:     Option<WindowMode>,
    focused:  bool,
}

/// Debug system that logs when Changed<Window> fires and what changed.
fn debug_window_changed(
    window: Single<&Window, (With<PrimaryWindow>, Changed<Window>)>,
    mut cached: Local<CachedWindowDebug>,
) {
    let w = *window;

    let position_changed = cached.position.as_ref() != Some(&w.position);
    let size_changed = cached.width != w.physical_width() || cached.height != w.physical_height();
    let mode_changed = cached.mode.as_ref() != Some(&w.mode);
    let focused_changed = cached.focused != w.focused;

    let mut changes = Vec::new();
    if position_changed {
        changes.push(format!(
            "position: {:?} -> {:?}",
            cached.position, w.position
        ));
    }
    if size_changed {
        changes.push(format!(
            "size: {}x{} -> {}x{}",
            cached.width,
            cached.height,
            w.physical_width(),
            w.physical_height()
        ));
    }
    if mode_changed {
        changes.push(format!("mode: {:?} -> {:?}", cached.mode, w.mode));
    }
    if focused_changed {
        changes.push(format!("focused: {} -> {}", cached.focused, w.focused));
    }

    if !changes.is_empty() {
        info!("[debug_window_changed] {}", changes.join(", "));
    }

    // Update cache
    cached.position = Some(w.position);
    cached.width = w.physical_width();
    cached.height = w.physical_height();
    cached.mode = Some(w.mode);
    cached.focused = w.focused;
}

/// Debug system that logs when `WindowScaleFactorChanged` messages are received.
fn debug_scale_factor_changed(mut messages: MessageReader<WindowScaleFactorChanged>) {
    for msg in messages.read() {
        info!(
            "[debug_scale_factor_changed] WindowScaleFactorChanged received: scale_factor={}",
            msg.scale_factor
        );
    }
}

// --- Mode Change Observers ---
//
// These observers handle the actual window mode changes. They are triggered both by keyboard
// input (via `commands.trigger()`) and by BRP remote calls (via `world.trigger()`).

fn on_set_borderless_fullscreen(
    _trigger: On<SetBorderlessFullscreen>,
    mut windows: Query<(&mut Window, Option<&CurrentMonitor>)>,
    monitors_res: Res<Monitors>,
) {
    let Some((mut window, current_monitor)) = windows.iter_mut().find(|(w, _)| w.focused) else {
        return;
    };
    let monitor = current_monitor.copied().unwrap_or_else(|| CurrentMonitor {
        monitor:        *monitors_res.first(),
        effective_mode: window.mode,
    });
    window.mode = WindowMode::BorderlessFullscreen(MonitorSelection::Index(monitor.monitor.index));
}

fn on_set_windowed(_trigger: On<SetWindowed>, mut windows: Query<&mut Window>) {
    let Some(mut window) = windows.iter_mut().find(|w| w.focused) else {
        return;
    };
    window.mode = WindowMode::Windowed;
}

fn on_set_exclusive_fullscreen(
    _trigger: On<SetExclusiveFullscreen>,
    mut windows: Query<(&mut Window, Option<&CurrentMonitor>)>,
    monitors_res: Res<Monitors>,
    bevy_monitors: Query<(Entity, &Monitor)>,
    selected: Res<SelectedVideoModes>,
) {
    let Some((mut window, current_monitor)) = windows.iter_mut().find(|(w, _)| w.focused) else {
        return;
    };
    let monitor = current_monitor.copied().unwrap_or_else(|| CurrentMonitor {
        monitor:        *monitors_res.first(),
        effective_mode: window.mode,
    });

    let video_modes: Vec<VideoMode> = bevy_monitors
        .iter()
        .find(|(_, m)| m.physical_position == monitor.monitor.position)
        .map(|(_, m)| m.video_modes.clone())
        .unwrap_or_default();

    let selected_idx = selected
        .get(monitor.monitor.index)
        .min(video_modes.len().saturating_sub(1));
    let video_mode_selection = video_modes
        .get(selected_idx)
        .map_or(VideoModeSelection::Current, |mode| {
            VideoModeSelection::Specific(*mode)
        });

    window.mode = WindowMode::Fullscreen(
        MonitorSelection::Index(monitor.monitor.index),
        video_mode_selection,
    );
}

fn on_toggle_persistence(
    _trigger: On<TogglePersistence>,
    mut persistence: ResMut<ManagedWindowPersistence>,
) {
    *persistence = match *persistence {
        ManagedWindowPersistence::RememberAll => ManagedWindowPersistence::ActiveOnly,
        ManagedWindowPersistence::ActiveOnly => ManagedWindowPersistence::RememberAll,
    };
    info!("[restore_window] Persistence mode: {:?}", *persistence);
}

fn on_clear_state_and_quit(
    _trigger: On<ClearStateAndQuit>,
    managed_entities: Query<Entity, With<ManagedWindow>>,
    mut commands: Commands,
    mut app_exit: MessageWriter<AppExit>,
) {
    if let Some(state_path) = get_state_file_path() {
        if let Err(e) = std::fs::remove_file(&state_path) {
            warn!("[restore_window] Failed to remove state file: {e}");
        } else {
            info!("[restore_window] Cleared state file: {state_path:?}");
        }
    }
    despawn_managed_and_exit(&managed_entities, &mut commands, &mut app_exit);
}

fn on_quit_app(
    _trigger: On<QuitApp>,
    managed_entities: Query<Entity, With<ManagedWindow>>,
    mut commands: Commands,
    mut app_exit: MessageWriter<AppExit>,
) {
    despawn_managed_and_exit(&managed_entities, &mut commands, &mut app_exit);
}

/// Observer that logs when `WindowRestored` event is received and caches the restored state.
fn on_window_restored(
    trigger: On<WindowRestored>,
    mut commands: Commands,
    mut restored_states: ResMut<RestoredStates>,
    mut settled_count: ResMut<WindowsSettledCount>,
) {
    let event = trigger.event();
    info!(
        "[on_window_restored] Restore complete: window_id={} entity={:?} position={:?} physical={} logical={} mode={:?} monitor={}",
        event.window_id,
        event.entity,
        event.position,
        event.size,
        event.logical_size,
        event.mode,
        event.monitor_index
    );

    restored_states.states.insert(
        event.entity,
        CachedRestoredState {
            position:       event.position,
            width:          event.size.x,
            height:         event.size.y,
            logical_width:  event.logical_size.x,
            logical_height: event.logical_size.y,
            monitor_index:  event.monitor_index,
            mode:           event.mode,
        },
    );

    commands.insert_resource(WindowRestoredReceived {
        position:      event.position,
        size:          event.size,
        mode:          event.mode,
        monitor_index: event.monitor_index,
    });
    settled_count.count += 1;
}

/// Observer that logs when `WindowRestoreMismatch` event is received.
fn on_window_restore_mismatch(
    trigger: On<WindowRestoreMismatch>,
    mut commands: Commands,
    mut restored_states: ResMut<RestoredStates>,
    mut mismatch_states: ResMut<MismatchStates>,
    mut settled_count: ResMut<WindowsSettledCount>,
) {
    let event = trigger.event();
    warn!(
        "[on_window_restore_mismatch] window_id={} entity={:?} \
         monitor: {} vs {}, size: {} vs {}, mode: {:?} vs {:?}",
        event.window_id,
        event.entity,
        event.expected_monitor,
        event.actual_monitor,
        event.expected_size,
        event.actual_size,
        event.expected_mode,
        event.actual_mode,
    );

    restored_states.states.insert(
        event.entity,
        CachedRestoredState {
            position:       event.expected_position,
            width:          event.expected_size.x,
            height:         event.expected_size.y,
            logical_width:  event.expected_logical_size.x,
            logical_height: event.expected_logical_size.y,
            monitor_index:  event.expected_monitor,
            mode:           event.expected_mode,
        },
    );

    mismatch_states.states.insert(
        event.entity,
        CachedMismatchState {
            expected_position:     event.expected_position,
            actual_position:       event.actual_position,
            expected_size:         event.expected_size,
            actual_size:           event.actual_size,
            expected_logical_size: event.expected_logical_size,
            actual_logical_size:   event.actual_logical_size,
            expected_mode:         event.expected_mode,
            actual_mode:           event.actual_mode,
            expected_monitor:      event.expected_monitor,
            actual_monitor:        event.actual_monitor,
            expected_scale:        event.expected_scale,
            actual_scale:          event.actual_scale,
        },
    );

    commands.insert_resource(WindowRestoreMismatchReceived {
        expected_monitor: event.expected_monitor,
        actual_monitor:   event.actual_monitor,
        expected_size:    event.expected_size,
        actual_size:      event.actual_size,
        expected_mode:    event.expected_mode,
        actual_mode:      event.actual_mode,
    });
    settled_count.count += 1;
}