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
//! Observers, run conditions, and plugin builder.
//!
//! All window-lifecycle logic lives here. [`build_plugin`] is called from the
//! thin `Plugin` impls in `lib.rs`.

use std::path::PathBuf;

use bevy::prelude::*;
use bevy::window::PrimaryWindow;
use bevy_kana::ToI32;
use bevy_kana::ToU32;

use super::ManagedWindow;
use super::ManagedWindowPersistence;
use super::WindowKey;
use super::constants::DEFAULT_SCALE_FACTOR;
use super::constants::PRIMARY_WINDOW_KEY;
use super::monitors;
use super::monitors::CurrentMonitor;
use super::monitors::MonitorPlugin;
use super::monitors::Monitors;
use super::platform::Platform;
use super::restore_plan;
use super::state;
use super::systems;
use super::types::ManagedWindowRegistry;
use super::types::RestoreWindowConfig;
use super::types::SavedWindowMode;
use super::types::TargetPosition;
use super::types::WindowState;
use super::types::WinitInfo;
use super::types::X11FrameCompensated;

/// Hide the primary window when created, before winit creates the OS window.
///
/// Uses an observer on `PrimaryWindow` component addition, so it works regardless
/// of plugin order. The window will be shown after restore completes or immediately
/// if no saved state.
///
/// Note: We observe `Add<PrimaryWindow>` rather than `Add<Window>` because when
/// `Window` is added, `PrimaryWindow` may not exist yet. By observing `PrimaryWindow`,
/// we know the `Window` component already exists on the entity.
fn hide_window_on_creation(add: On<Add, PrimaryWindow>, mut windows: Query<&mut Window>) {
    debug!(
        "[hide_window_on_creation] Observer fired for entity {:?}",
        add.entity
    );
    if let Ok(mut window) = windows.get_mut(add.entity) {
        debug!("[hide_window_on_creation] Setting window.visible = false");
        window.visible = false;
    }
}

/// Observer: register a `ManagedWindow` name, deduplicate if needed, and save initial state if
/// needed.
fn on_managed_window_added(
    add: On<Add, ManagedWindow>,
    mut managed: Query<&mut ManagedWindow>,
    mut registry: ResMut<ManagedWindowRegistry>,
    config: Res<RestoreWindowConfig>,
    monitors: Res<Monitors>,
    windows: Query<&Window>,
    primary_query: Query<(), With<PrimaryWindow>>,
) {
    let entity = add.entity;
    let Ok(mut managed_window) = managed.get_mut(entity) else {
        return;
    };
    let name = managed_window.name.clone();

    // Primary window is managed automatically — reject explicit `ManagedWindow` on it
    if primary_query.get(entity).is_ok() {
        warn!(
            "[on_managed_window_added] `ManagedWindow` cannot be added to the primary window (entity {entity:?}). \
             The primary window is managed automatically under the key \"{key}\".",
            key = PRIMARY_WINDOW_KEY,
        );
        return;
    }

    let unique_name = if registry.names.contains(&name) {
        debug_assert!(false, "Duplicate ManagedWindow name: \"{name}\"");
        let mut suffix = 2;
        loop {
            let candidate = format!("{name}-{suffix}");
            if !registry.names.contains(&candidate) {
                break candidate;
            }
            suffix += 1;
        }
    } else {
        name.clone()
    };

    if unique_name != name {
        warn!(
            "[on_managed_window_added] Duplicate ManagedWindow name: \"{name}\" — renamed to \"{unique_name}\" for entity {entity:?}"
        );
        managed_window.name.clone_from(&unique_name);
    }

    registry.names.insert(unique_name.clone());
    registry.entities.insert(entity, unique_name.clone());
    debug!(
        "[on_managed_window_added] Registered managed window \"{unique_name}\" on entity {entity:?}"
    );

    // If no saved state exists for this window, save its current position/size immediately
    let existing = state::load_all_states(&config.path);
    let already_saved = existing
        .as_ref()
        .is_some_and(|s| s.contains_key(&WindowKey::Managed(unique_name.clone())));

    if !already_saved && let Ok(window) = windows.get(entity) {
        let monitor = match window.position {
            WindowPosition::At(pos) => {
                *monitors.monitor_for_window(pos, window.physical_width(), window.physical_height())
            },
            _ => *monitors.first(),
        };
        let logical_position = match window.position {
            WindowPosition::At(pos) => {
                let logical_x = (f64::from(pos.x) / monitor.scale).round().to_i32();
                let logical_y = (f64::from(pos.y) / monitor.scale).round().to_i32();
                Some((logical_x, logical_y))
            },
            _ => None,
        };
        let window_state = WindowState {
            logical_position,
            logical_width: window.width().to_u32(),
            logical_height: window.height().to_u32(),
            monitor_scale: monitor.scale,
            monitor_index: monitor.index,
            mode: SavedWindowMode::Windowed,
            app_name: String::new(),
        };

        let mut states = existing.unwrap_or_default();
        states.insert(WindowKey::Managed(unique_name.clone()), window_state);
        state::save_all_states(&config.path, &states);
        debug!("[on_managed_window_added] Saved initial state for \"{unique_name}\"");
    }
}

/// Observer: unregister a `ManagedWindow` name when removed, and update state file if `ActiveOnly`.
fn on_managed_window_removed(
    remove: On<Remove, ManagedWindow>,
    mut registry: ResMut<ManagedWindowRegistry>,
    config: Res<RestoreWindowConfig>,
    persistence: Res<ManagedWindowPersistence>,
    monitors: Res<Monitors>,
    all_windows: Query<
        (
            Entity,
            &Window,
            Option<&CurrentMonitor>,
            Option<&ManagedWindow>,
        ),
        Or<(With<PrimaryWindow>, With<ManagedWindow>)>,
    >,
    primary_q: Query<(), With<PrimaryWindow>>,
) {
    let entity = remove.entity;
    if let Some(name) = registry.entities.remove(&entity) {
        // If `ActiveOnly`, rebuild state from all remaining active windows.
        // The removed entity's `ManagedWindow` is being removed, so the query
        // naturally excludes it — but guard against it just in case.
        if *persistence == ManagedWindowPersistence::ActiveOnly {
            systems::save_active_window_state(
                &config,
                &monitors,
                &all_windows,
                &primary_q,
                Some(entity),
            );
            debug!(
                "[on_managed_window_removed] Rebuilt state file without \"{name}\" (ActiveOnly)"
            );
        }

        registry.names.remove(&name);
        debug!(
            "[on_managed_window_removed] Unregistered managed window \"{name}\" from entity {entity:?}"
        );
    }
}

/// When `ManagedWindowPersistence` switches to `ActiveOnly`, immediately rebuild the state
/// file from the currently-active windows so that any previously-remembered-but-closed
/// window entries are pruned.
fn on_persistence_changed(
    persistence: Res<ManagedWindowPersistence>,
    config: Res<RestoreWindowConfig>,
    monitors: Res<Monitors>,
    all_windows: Query<
        (
            Entity,
            &Window,
            Option<&CurrentMonitor>,
            Option<&ManagedWindow>,
        ),
        Or<(With<PrimaryWindow>, With<ManagedWindow>)>,
    >,
    primary_q: Query<(), With<PrimaryWindow>>,
) {
    if *persistence == ManagedWindowPersistence::ActiveOnly {
        systems::save_active_window_state(&config, &monitors, &all_windows, &primary_q, None);
        debug!("[on_persistence_changed] Rebuilt state file for ActiveOnly mode");
    }
}

/// Observer: hide a managed window on creation and load its saved state.
fn on_managed_window_load(
    add: On<Add, ManagedWindow>,
    mut commands: Commands,
    managed: Query<&ManagedWindow>,
    monitors: Res<Monitors>,
    winit_info: Option<Res<WinitInfo>>,
    config: Res<RestoreWindowConfig>,
    mut windows: Query<&mut Window>,
    primary_monitor: Query<&CurrentMonitor, With<PrimaryWindow>>,
    platform: Res<Platform>,
) {
    let entity = add.entity;
    let Ok(managed_window) = managed.get(entity) else {
        return;
    };
    let name = &managed_window.name;

    // Hide window during restore (on Linux X11 with frame extent compensation, don't hide)
    if let Ok(mut window) = windows.get_mut(entity)
        && platform.should_hide_on_startup()
    {
        window.visible = false;
    }

    // Check the startup snapshot — not the file, which may have been modified by
    // `on_managed_window_added` saving initial state for brand-new windows.
    let key = WindowKey::Managed((*name).clone());
    let Some(saved_state) = config.loaded_states.get(&key).cloned() else {
        debug!("[on_managed_window_load] No saved state for \"{name}\", showing window");
        if let Ok(mut window) = windows.get_mut(entity) {
            window.visible = true;
        }
        return;
    };

    debug!(
        "[on_managed_window_load] Loaded state for \"{name}\": position={:?} logical_size={}x{} monitor_scale={} monitor={} mode={:?}",
        saved_state.logical_position,
        saved_state.logical_width,
        saved_state.logical_height,
        saved_state.monitor_scale,
        saved_state.monitor_index,
        saved_state.mode
    );

    let Some(winit_info) = winit_info else {
        debug!("[on_managed_window_load] WinitInfo not available, showing window for \"{name}\"");
        if let Ok(mut window) = windows.get_mut(entity) {
            window.visible = true;
        }
        return;
    };

    if monitors.is_empty() {
        debug!("[on_managed_window_load] No monitors available, showing window for \"{name}\"");
        if let Ok(mut window) = windows.get_mut(entity) {
            window.visible = true;
        }
        return;
    }

    // The window will be created on the focused window's monitor (the primary window's
    // monitor), so use that scale as starting_scale for scale factor compensation.
    let primary_scale = primary_monitor
        .iter()
        .next()
        .map_or(DEFAULT_SCALE_FACTOR, |cm| cm.scale);

    restore_managed_window(
        entity,
        &saved_state,
        &monitors,
        &winit_info,
        &mut commands,
        primary_scale,
        *platform,
    );
}

/// Compute the target position for a managed window from saved state.
///
/// Inserts a `TargetPosition` component but does NOT modify `Window.position` or
/// `Window.resolution`. The actual restore is deferred to `restore_windows`, which
/// gates on the winit window existing (via `WINIT_WINDOWS`). This ensures
/// `create_windows` → `set_scale_factor_and_apply_to_physical_size()` runs first,
/// preventing the physical size from being doubled on high-DPI displays.
fn restore_managed_window(
    entity: Entity,
    saved_state: &WindowState,
    monitors: &Monitors,
    winit_info: &WinitInfo,
    commands: &mut Commands,
    primary_scale: f64,
    platform: Platform,
) {
    let (target_info, fallback_position, used_fallback) =
        restore_plan::resolve_target_monitor_and_position(
            saved_state.monitor_index,
            saved_state.logical_position,
            monitors,
        );
    if used_fallback {
        warn!(
            "[restore_managed_window] Target monitor {} not found, falling back to monitor 0",
            saved_state.monitor_index
        );
    }

    let decoration = winit_info.decoration();

    // The window is created on the focused window's monitor (the primary window's monitor)
    // without explicit positioning. Its starting scale matches the primary monitor, not the
    // target monitor.
    let target = restore_plan::compute_target_position(
        saved_state,
        target_info,
        fallback_position,
        decoration,
        primary_scale,
        platform,
    );

    debug!(
        "[restore_managed_window] saved_pos={:?} clamped_pos={:?} target_scale={} logical={}x{} physical={}x{} monitor={} mon_pos=({},{}) mon_size=({},{})",
        saved_state.logical_position,
        target.position,
        target.target_scale,
        target.logical_width,
        target.logical_height,
        target.width,
        target.height,
        target.target_monitor_index,
        target_info.position.x,
        target_info.position.y,
        target_info.size.x,
        target_info.size.y,
    );

    let is_fullscreen = saved_state.mode.is_fullscreen();
    commands.entity(entity).insert(target);

    // Insert `X11FrameCompensated` for platforms that don't need compensation.
    // For fullscreen modes, skip frame compensation — frame extents are irrelevant
    // and delaying restore gives the compositor time to revert position changes.
    if is_fullscreen || !platform.needs_frame_compensation() {
        commands.entity(entity).insert(X11FrameCompensated);
    }
}

/// Run condition: returns true if any entity has a `TargetPosition` component.
fn has_restoring_windows(q: Query<(), With<TargetPosition>>) -> bool { !q.is_empty() }

/// Run condition: returns true if no entity has a `TargetPosition` component.
fn no_restoring_windows(q: Query<(), With<TargetPosition>>) -> bool { q.is_empty() }

/// The run conditions allow us to separate the initial primary window restore from
/// subsequent positions saves - which we dont' want to do until AFTER we've done
/// the initial restore.
pub(crate) fn build_plugin(app: &mut App, path: PathBuf, persistence: ManagedWindowPersistence) {
    let platform = Platform::detect();
    app.insert_resource(platform);

    // Hide primary window to prevent flash at default position.
    // Two cases to handle:
    // 1. Window already exists (WindowManagerPlugin added after DefaultPlugins) - hide immediately
    // 2. Window doesn't exist yet (WindowManagerPlugin added before DefaultPlugins) - use observer
    //
    // EXCEPTION: On Linux X11 with frame extent compensation (workaround-winit-4445),
    // we cannot hide the window because the compensation system needs to query
    // _NET_FRAME_EXTENTS, which requires the window to be visible/mapped.
    let should_hide = platform.should_hide_on_startup();

    if should_hide {
        let mut query = app
            .world_mut()
            .query_filtered::<&mut Window, With<PrimaryWindow>>();
        if let Some(mut window) = query.iter_mut(app.world_mut()).next() {
            debug!("[build_plugin] Window already exists, hiding immediately");
            window.visible = false;
        } else {
            debug!("[build_plugin] Window doesn't exist yet, registering observer");
            app.add_observer(hide_window_on_creation);
        }
    } else {
        debug!("[build_plugin] Linux X11: skipping window hide for frame extent compensation");
    }

    #[cfg(target_os = "macos")]
    super::macos_tabbing_fix::init(app);

    #[cfg(all(target_os = "windows", feature = "workaround-winit-4341"))]
    super::windows_dpi_fix::init(app);

    app.add_plugins(MonitorPlugin)
        .insert_resource(RestoreWindowConfig {
            path,
            loaded_states: std::collections::HashMap::new(),
        })
        .insert_resource(persistence)
        .init_resource::<ManagedWindowRegistry>()
        .add_observer(on_managed_window_added)
        .add_observer(on_managed_window_removed)
        .add_observer(on_managed_window_load)
        .add_systems(PreStartup, {
            #[cfg(target_os = "linux")]
            {
                // X11 fullscreen: move window to target monitor before first event loop.
                // Must be chained (not .after()) so apply_deferred runs between
                // load_target_position and move_to_target_monitor — otherwise the
                // TargetPosition component inserted via deferred commands won't exist yet.
                (
                    systems::init_winit_info,
                    systems::load_target_position,
                    systems::move_to_target_monitor,
                )
                    .chain()
                    .after(monitors::init_monitors)
            }
            #[cfg(not(target_os = "linux"))]
            {
                (systems::init_winit_info, systems::load_target_position)
                    .chain()
                    .after(monitors::init_monitors)
            }
        });

    // X11 frame extent compensation (Linux + W6 + X11 only)
    // Runs until all restoring windows have the X11FrameCompensated component
    #[cfg(all(target_os = "linux", feature = "workaround-winit-4445"))]
    app.add_systems(
        Update,
        super::x11_frame_extents::compensate_target_position
            .run_if(has_restoring_windows)
            .run_if(|p: Res<Platform>| p.is_x11()),
    );

    // Restore windows - processes all entities with `TargetPosition` + `X11FrameCompensated`
    app.add_systems(
        Update,
        (
            systems::restore_windows,
            systems::check_restore_settling.after(systems::restore_windows),
        )
            .run_if(has_restoring_windows),
    );

    // Unified monitor detection + save window state
    app.add_systems(
        Update,
        (
            systems::update_current_monitor,
            systems::save_window_state
                .run_if(no_restoring_windows)
                .after(systems::update_current_monitor),
            on_persistence_changed
                .run_if(resource_changed::<ManagedWindowPersistence>)
                .run_if(no_restoring_windows)
                .after(systems::update_current_monitor),
        ),
    );
}