Skip to content

Commit

Permalink
Handle Ctrl+C in the terminal properly
Browse files Browse the repository at this point in the history
  • Loading branch information
SarthakSingh31 committed Jun 25, 2024
1 parent 158ccc6 commit 214f06a
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 2 deletions.
3 changes: 3 additions & 0 deletions crates/bevy_app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ bevy_tasks = { path = "../bevy_tasks", version = "0.14.0-dev" }
downcast-rs = "1.2.0"
thiserror = "1.0"

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
ctrlc = "3.4.4"

[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen = { version = "0.2" }
web-sys = { version = "0.3", features = ["Window"] }
Expand Down
2 changes: 2 additions & 0 deletions crates/bevy_app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ mod plugin;
mod plugin_group;
mod schedule_runner;
mod sub_app;
mod terminal_ctrl_c_handler;

pub use app::*;
pub use bevy_derive::DynamicPlugin;
Expand All @@ -23,6 +24,7 @@ pub use plugin::*;
pub use plugin_group::*;
pub use schedule_runner::*;
pub use sub_app::*;
pub use terminal_ctrl_c_handler::*;

#[allow(missing_docs)]
pub mod prelude {
Expand Down
78 changes: 78 additions & 0 deletions crates/bevy_app/src/terminal_ctrl_c_handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
use std::sync::atomic::{AtomicBool, Ordering};

use bevy_ecs::event::EventWriter;

use crate::{App, AppExit, Plugin, Update};

pub use ctrlc;

#[cfg(not(target_arch = "wasm32"))]
/// Indicates that all [`App`]'s should exit.
static SHOULD_EXIT: AtomicBool = AtomicBool::new(false);

/// Gracefully handles `Ctrl+C` by emitting a [`AppExit`] event. This plugin is part of the `DefaultPlugins`.
///
/// ```no_run
/// # use bevy_app::{App, NoopPluginGroup as MinimalPlugins, PluginGroup, TerminalCtrlCHandlerPlugin};
/// fn main() {
/// App::new()
/// .add_plugins(MinimalPlugins)
/// .add_plugins(TerminalCtrlCHandlerPlugin)
/// .run();
/// }
/// ```
///
/// If you want to setup your own `Ctrl+C` handler, you should call the
/// [`TerminalCtrlCHandlerPlugin::gracefully_exit`] function in your handler if you want bevy to gracefully exit.
/// ```no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, TerminalCtrlCHandlerPlugin, ctrlc};
/// fn main() {
/// // Your own `Ctrl+C` handler
/// ctrlc::set_handler(move || {
/// // Other clean up code ...
///
/// TerminalCtrlCHandlerPlugin::gracefully_exit();
/// });
///
/// App::new()
/// .add_plugins(DefaultPlugins)
/// .run();
/// }
/// ```
#[derive(Default)]
pub struct TerminalCtrlCHandlerPlugin;

#[cfg(not(target_arch = "wasm32"))]
impl TerminalCtrlCHandlerPlugin {
/// When called all apps with this plugin will get the [`AppExit`] event and gracefully exit.
pub fn gracefully_exit() {
SHOULD_EXIT.store(true, Ordering::Relaxed);
}

/// Sends a [`AppExit`] event when the user presses `Ctrl+C` on the terminal.
fn exit_on_flag(mut events: EventWriter<AppExit>) {
if SHOULD_EXIT.load(Ordering::Relaxed) {
events.send(AppExit::from_code(130));
}
}
}

impl Plugin for TerminalCtrlCHandlerPlugin {
fn build(&self, app: &mut App) {
#[cfg(not(target_arch = "wasm32"))]
{
let result = ctrlc::try_set_handler(move || {
Self::gracefully_exit();
});
match result {
Ok(()) => {}
Err(ctrlc::Error::MultipleHandlers) => {
bevy_utils::tracing::info!("`Ctrl+C` handler was already set somewhere else");
}
Err(err) => bevy_utils::tracing::warn!("Failed to set `Ctrl+C` handler: {}", err),
}

app.add_systems(Update, TerminalCtrlCHandlerPlugin::exit_on_flag);
}
}
}
1 change: 1 addition & 0 deletions crates/bevy_internal/src/default_plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ impl PluginGroup for DefaultPlugins {
let mut group = PluginGroupBuilder::start::<Self>();
group = group
.add(bevy_app::PanicHandlerPlugin)
.add(bevy_app::TerminalCtrlCHandlerPlugin)
.add(bevy_log::LogPlugin::default())
.add(bevy_core::TaskPoolPlugin::default())
.add(bevy_core::TypeRegistrationPlugin)
Expand Down
4 changes: 2 additions & 2 deletions examples/3d/3d_scene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

use bevy::prelude::*;

fn main() {
fn main() -> AppExit {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
.run()
}

/// set up a simple 3D scene
Expand Down

0 comments on commit 214f06a

Please sign in to comment.