Add support for graceful exits in Application

- `Settings` now contains an `exit_on_close_request` field
- `Application` has a new `should_exit` method
This commit is contained in:
Héctor Ramón Jiménez 2021-03-30 21:44:19 +02:00
parent 00de9d0c9b
commit 67db13ff7c
5 changed files with 57 additions and 9 deletions

View file

@ -91,6 +91,13 @@ pub trait Application: Program<Clipboard = Clipboard> {
fn scale_factor(&self) -> f64 {
1.0
}
/// Returns whether the [`Application`] should be terminated.
///
/// By default, it returns `false`.
fn should_exit(&self) -> bool {
false
}
}
/// Runs an [`Application`] with an executor, compositor, and the provided
@ -149,10 +156,11 @@ where
application,
compositor,
renderer,
window,
runtime,
debug,
receiver,
window,
settings.exit_on_close_request,
));
let mut context = task::Context::from_waker(task::noop_waker_ref());
@ -196,10 +204,11 @@ async fn run_instance<A, E, C>(
mut application: A,
mut compositor: C,
mut renderer: A::Renderer,
window: winit::window::Window,
mut runtime: Runtime<E, Proxy<A::Message>, A::Message>,
mut debug: Debug,
mut receiver: mpsc::UnboundedReceiver<winit::event::Event<'_, A::Message>>,
window: winit::window::Window,
exit_on_close_request: bool,
) where
A: Application + 'static,
E: Executor + 'static,
@ -279,6 +288,8 @@ async fn run_instance<A, E, C>(
// Update window
state.synchronize(&application, &window);
let should_exit = application.should_exit();
user_interface = ManuallyDrop::new(build_user_interface(
&mut application,
cache,
@ -286,6 +297,10 @@ async fn run_instance<A, E, C>(
state.logical_size(),
&mut debug,
));
if should_exit {
break;
}
}
debug.draw_started();
@ -358,7 +373,9 @@ async fn run_instance<A, E, C>(
event: window_event,
..
} => {
if requests_exit(&window_event, state.modifiers()) {
if requests_exit(&window_event, state.modifiers())
&& exit_on_close_request
{
break;
}