Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure clean exit #13236

Merged
merged 2 commits into from
May 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 5 additions & 5 deletions crates/bevy_render/src/view/window/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use bevy_ecs::{entity::EntityHashMap, prelude::*};
use bevy_utils::warn_once;
use bevy_utils::{default, tracing::debug, HashSet};
use bevy_window::{
CompositeAlphaMode, PresentMode, PrimaryWindow, RawHandleWrapper, Window, WindowClosed,
CompositeAlphaMode, PresentMode, PrimaryWindow, RawHandleWrapper, Window, WindowClosing,
};
use std::{
num::NonZeroU32,
Expand Down Expand Up @@ -117,7 +117,7 @@ impl DerefMut for ExtractedWindows {
fn extract_windows(
mut extracted_windows: ResMut<ExtractedWindows>,
screenshot_manager: Extract<Res<ScreenshotManager>>,
mut closed: Extract<EventReader<WindowClosed>>,
mut closing: Extract<EventReader<WindowClosing>>,
windows: Extract<Query<(Entity, &Window, &RawHandleWrapper, Option<&PrimaryWindow>)>>,
mut removed: Extract<RemovedComponents<RawHandleWrapper>>,
mut window_surfaces: ResMut<WindowSurfaces>,
Expand Down Expand Up @@ -177,9 +177,9 @@ fn extract_windows(
}
}

for closed_window in closed.read() {
extracted_windows.remove(&closed_window.window);
window_surfaces.remove(&closed_window.window);
for closing_window in closing.read() {
extracted_windows.remove(&closing_window.window);
window_surfaces.remove(&closing_window.window);
}
for removed_window in removed.read() {
extracted_windows.remove(&removed_window);
Expand Down
14 changes: 14 additions & 0 deletions crates/bevy_window/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,20 @@ pub struct WindowClosed {
pub window: Entity,
}

/// An event that is sent whenever a window is closing. This will be sent when
/// after a [`WindowCloseRequested`] event is received and the window is in the process of closing.
#[derive(Event, Debug, Clone, PartialEq, Eq, Reflect)]
#[reflect(Debug, PartialEq)]
#[cfg_attr(
feature = "serialize",
derive(serde::Serialize, serde::Deserialize),
reflect(Serialize, Deserialize)
)]
pub struct WindowClosing {
/// Window that has been requested to close and is the process of closing.
pub window: Entity,
}

/// An event that is sent whenever a window is destroyed by the underlying window system.
///
/// Note that if your application only has a single window, this event may be your last chance to
Expand Down
2 changes: 2 additions & 0 deletions crates/bevy_window/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ impl Plugin for WindowPlugin {
#[allow(deprecated)]
app.add_event::<WindowResized>()
.add_event::<WindowCreated>()
.add_event::<WindowClosing>()
.add_event::<WindowClosed>()
.add_event::<WindowCloseRequested>()
.add_event::<WindowDestroyed>()
Expand Down Expand Up @@ -139,6 +140,7 @@ impl Plugin for WindowPlugin {
.register_type::<RequestRedraw>()
.register_type::<WindowCreated>()
.register_type::<WindowCloseRequested>()
.register_type::<WindowClosing>()
.register_type::<WindowClosed>()
.register_type::<CursorMoved>()
.register_type::<CursorEntered>()
Expand Down
15 changes: 12 additions & 3 deletions crates/bevy_window/src/system.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{PrimaryWindow, Window, WindowCloseRequested};
use crate::{ClosingWindow, PrimaryWindow, Window, WindowCloseRequested};

use bevy_app::AppExit;
use bevy_ecs::prelude::*;
Expand Down Expand Up @@ -39,8 +39,17 @@ pub fn exit_on_primary_closed(
/// Ensure that you read the caveats documented on that field if doing so.
///
/// [`WindowPlugin`]: crate::WindowPlugin
pub fn close_when_requested(mut commands: Commands, mut closed: EventReader<WindowCloseRequested>) {
pub fn close_when_requested(
mut commands: Commands,
mut closed: EventReader<WindowCloseRequested>,
closing: Query<Entity, With<ClosingWindow>>,
) {
// This was inserted by us on the last frame so now we can despawn the window
for window in closing.iter() {
commands.entity(window).despawn();
}
// Mark the window as closing so we can despawn it on the next frame
for event in closed.read() {
commands.entity(event.window).despawn();
commands.entity(event.window).insert(ClosingWindow);
}
}
5 changes: 5 additions & 0 deletions crates/bevy_window/src/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1171,6 +1171,11 @@ impl Default for EnabledButtons {
}
}

/// Marker component for a [`Window`] that has been requested to close and
/// is in the process of closing (on the next frame).
#[derive(Component)]
pub struct ClosingWindow;

#[cfg(test)]
mod tests {
use super::*;
Expand Down
5 changes: 5 additions & 0 deletions crates/bevy_winit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,11 @@ pub fn winit_runner(mut app: App) -> AppExit {
let mut winit_events = Vec::default();
// set up the event loop
let event_handler = move |event, event_loop: &EventLoopWindowTarget<UserEvent>| {
// The event loop is in the process of exiting, so don't deliver any new events
if event_loop.exiting() {
return;
}

handle_winit_event(
&mut app,
&mut runner_state,
Expand Down
16 changes: 12 additions & 4 deletions crates/bevy_winit/src/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,16 @@ use bevy_ecs::{
};
use bevy_utils::tracing::{error, info, warn};
use bevy_window::{
RawHandleWrapper, Window, WindowClosed, WindowCreated, WindowMode, WindowResized,
ClosingWindow, RawHandleWrapper, Window, WindowClosed, WindowClosing, WindowCreated,
WindowMode, WindowResized,
};

use winit::{
dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize},
event_loop::EventLoopWindowTarget,
};

use bevy_ecs::query::With;
#[cfg(target_arch = "wasm32")]
use winit::platform::web::WindowExtWebSys;

Expand Down Expand Up @@ -97,18 +99,24 @@ pub fn create_windows<F: QueryFilter + 'static>(
}

pub(crate) fn despawn_windows(
closing: Query<Entity, With<ClosingWindow>>,
mut closed: RemovedComponents<Window>,
window_entities: Query<&Window>,
mut close_events: EventWriter<WindowClosed>,
mut closing_events: EventWriter<WindowClosing>,
mut closed_events: EventWriter<WindowClosed>,
mut winit_windows: NonSendMut<WinitWindows>,
) {
for window in closing.iter() {
closing_events.send(WindowClosing { window });
}
for window in closed.read() {
info!("Closing window {:?}", window);
// Guard to verify that the window is in fact actually gone,
// rather than having the component added and removed in the same frame.
// rather than having the component added
// and removed in the same frame.
if !window_entities.contains(window) {
winit_windows.remove_window(window);
close_events.send(WindowClosed { window });
closed_events.send(WindowClosed { window });
}
}
}
Expand Down