bevy_window/
system.rs

1use crate::{ClosingWindow, PrimaryWindow, Window, WindowCloseRequested};
2
3use bevy_app::AppExit;
4use bevy_ecs::prelude::*;
5
6/// Exit the application when there are no open windows.
7///
8/// This system is added by the [`WindowPlugin`] in the default configuration.
9/// To disable this behavior, set `close_when_requested` (on the [`WindowPlugin`]) to `false`.
10/// Ensure that you read the caveats documented on that field if doing so.
11///
12/// [`WindowPlugin`]: crate::WindowPlugin
13pub fn exit_on_all_closed(mut app_exit_events: EventWriter<AppExit>, windows: Query<&Window>) {
14    if windows.is_empty() {
15        bevy_utils::tracing::info!("No windows are open, exiting");
16        app_exit_events.send(AppExit::Success);
17    }
18}
19
20/// Exit the application when the primary window has been closed
21///
22/// This system is added by the [`WindowPlugin`]
23///
24/// [`WindowPlugin`]: crate::WindowPlugin
25pub fn exit_on_primary_closed(
26    mut app_exit_events: EventWriter<AppExit>,
27    windows: Query<(), (With<Window>, With<PrimaryWindow>)>,
28) {
29    if windows.is_empty() {
30        bevy_utils::tracing::info!("Primary window was closed, exiting");
31        app_exit_events.send(AppExit::Success);
32    }
33}
34
35/// Close windows in response to [`WindowCloseRequested`] (e.g.  when the close button is pressed).
36///
37/// This system is added by the [`WindowPlugin`] in the default configuration.
38/// To disable this behavior, set `close_when_requested` (on the [`WindowPlugin`]) to `false`.
39/// Ensure that you read the caveats documented on that field if doing so.
40///
41/// [`WindowPlugin`]: crate::WindowPlugin
42pub fn close_when_requested(
43    mut commands: Commands,
44    mut closed: EventReader<WindowCloseRequested>,
45    closing: Query<Entity, With<ClosingWindow>>,
46) {
47    // This was inserted by us on the last frame so now we can despawn the window
48    for window in closing.iter() {
49        commands.entity(window).despawn();
50    }
51    // Mark the window as closing so we can despawn it on the next frame
52    for event in closed.read() {
53        // When spamming the window close button on windows (other platforms too probably)
54        // we may receive a `WindowCloseRequested` for a window we've just despawned in the above
55        // loop.
56        commands.entity(event.window).try_insert(ClosingWindow);
57    }
58}