bevy_app/terminal_ctrl_c_handler.rs
1use core::sync::atomic::{AtomicU8, Ordering};
2
3use alloc::{boxed::Box, vec::Vec};
4use std::sync::Mutex;
5
6use bevy_ecs::message::MessageWriter;
7
8use crate::{App, AppExit, Plugin, Update};
9
10pub use ctrlc;
11
12/// Indicates that all [`App`]'s should exit.
13static SHOULD_EXIT: AtomicU8 = AtomicU8::new(0);
14
15/// Handlers run when the app is asked to exit via `Ctrl+C`.
16static ON_EXIT_HANDLERS: Mutex<Vec<Box<dyn Fn() + Send>>> = Mutex::new(Vec::new());
17
18/// Gracefully handles `Ctrl+C` by emitting a [`AppExit`] event. This plugin is part of the `DefaultPlugins`.
19///
20/// ```no_run
21/// # use bevy_app::{App, NoopPluginGroup as MinimalPlugins, PluginGroup, TerminalCtrlCHandlerPlugin};
22/// fn main() {
23/// App::new()
24/// .add_plugins(MinimalPlugins)
25/// .add_plugins(TerminalCtrlCHandlerPlugin)
26/// .run();
27/// }
28/// ```
29///
30/// If you want to setup your own `Ctrl+C` handler, you should call the
31/// [`TerminalCtrlCHandlerPlugin::gracefully_exit`] function in your handler if you want bevy to gracefully exit.
32/// ```no_run
33/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, TerminalCtrlCHandlerPlugin, ctrlc};
34/// fn main() {
35/// // Your own `Ctrl+C` handler
36/// ctrlc::set_handler(move || {
37/// // Other clean up code ...
38///
39/// TerminalCtrlCHandlerPlugin::gracefully_exit();
40/// });
41///
42/// App::new()
43/// .add_plugins(DefaultPlugins)
44/// .run();
45/// }
46/// ```
47#[derive(Default)]
48pub struct TerminalCtrlCHandlerPlugin;
49
50impl TerminalCtrlCHandlerPlugin {
51 /// When called the first time, it sends the [`AppExit`] event to all apps using
52 /// this plugin to make them gracefully exit.
53 ///
54 /// If called more than once, it exits immediately.
55 pub fn gracefully_exit() {
56 if SHOULD_EXIT.fetch_add(1, Ordering::SeqCst) > 0 {
57 log::error!("Received more than one ctrl+c. Skipping graceful shutdown.");
58 std::process::exit(Self::EXIT_CODE.into());
59 };
60
61 if let Ok(handlers) = ON_EXIT_HANDLERS.lock() {
62 for handler in handlers.iter() {
63 handler();
64 }
65 }
66 }
67
68 /// Registers a `handler` that is invoked when `Ctrl+C` is received.
69 ///
70 /// This can be used to e.g. waking a sleeping event loop so it can observe the [`AppExit`].
71 pub fn register_exit_handler(handler: impl Fn() + Send + 'static) {
72 if let Ok(mut handlers) = ON_EXIT_HANDLERS.lock() {
73 handlers.push(Box::new(handler));
74 }
75 }
76
77 /// Sends a [`AppExit`] event when the user presses `Ctrl+C` on the terminal.
78 pub fn exit_on_flag(mut app_exit_writer: MessageWriter<AppExit>) {
79 if SHOULD_EXIT.load(Ordering::Relaxed) > 0 {
80 app_exit_writer.write(AppExit::from_code(Self::EXIT_CODE));
81 }
82 }
83
84 const EXIT_CODE: u8 = 130;
85}
86
87impl Plugin for TerminalCtrlCHandlerPlugin {
88 fn build(&self, app: &mut App) {
89 let result = ctrlc::try_set_handler(move || {
90 Self::gracefully_exit();
91 });
92 match result {
93 Ok(()) => {}
94 Err(ctrlc::Error::MultipleHandlers) => {
95 log::info!("Skipping installing `Ctrl+C` handler as one was already installed. Please call `TerminalCtrlCHandlerPlugin::gracefully_exit` in your own `Ctrl+C` handler if you want Bevy to gracefully exit on `Ctrl+C`.");
96 }
97 Err(err) => log::warn!("Failed to set `Ctrl+C` handler: {err}"),
98 }
99
100 app.add_systems(Update, TerminalCtrlCHandlerPlugin::exit_on_flag);
101 }
102}