winit_app/application.rs
1//! Module to help create a new `winit` application.
2//!
3//! # Example
4//!
5//! ```
6//! use winit::{event::WindowEvent, window::WindowAttributes};
7//! use winit_app::Application;
8//!
9//! fn launch_app() -> Result<(), Box<dyn std::error::Error>> {
10//! let winit_app = Application::new();
11//!
12//! winit_app.run(
13//! WindowAttributes::default().with_title("Sample"),
14//! |app_window_event| match app_window_event {
15//! _ => {
16//! // TODO: Handle those events
17//! }
18//! },
19//! )?;
20//! Ok(())
21//! }
22//! ```
23
24use winit::{
25 event_loop::{ControlFlow, EventLoop},
26 window::WindowAttributes,
27};
28
29use crate::{
30 WinitAppResult,
31 app_listener::{AppListener, AppWindowEvent},
32};
33
34/// Create a new `winit` application.
35///
36/// # Example
37///
38/// ```
39/// use winit::{event::WindowEvent, window::WindowAttributes};
40/// use winit_app::Application;
41///
42/// fn launch_app() -> Result<(), Box<dyn std::error::Error>> {
43/// let winit_app = Application::new();
44///
45/// winit_app.run(
46/// WindowAttributes::default().with_title("Sample"),
47/// |app_window_event| match app_window_event {
48/// _ => {
49/// // TODO: Handle those events
50/// }
51/// },
52/// )?;
53/// Ok(())
54/// }
55/// ```
56#[derive(Default)]
57pub struct Application {
58 control_flow: ControlFlow,
59}
60
61impl<'a> Application {
62 pub fn new() -> Self {
63 Self {
64 control_flow: ControlFlow::Wait,
65 }
66 }
67
68 /// Sets the control flow of this application
69 ///
70 /// `ControlFlow::Poll` continuously runs the event loop, even if the OS hasn't
71 /// dispatched any events. This is ideal for games and similar applications.
72 ///
73 /// `ControlFlow::Wait` pauses the event loop if no events are available to process.
74 /// This is ideal for non-game applications that only update in response to user
75 /// input, and uses significantly less power/CPU time than ControlFlow::Poll.
76 pub fn with_control_flow(&mut self, control_flow: ControlFlow) -> &Self {
77 self.control_flow = control_flow;
78 self
79 }
80
81 pub fn run<F>(&'a self, window_attributes: WindowAttributes, listener: F) -> WinitAppResult<()>
82 where
83 F: FnMut(AppWindowEvent) + 'static,
84 {
85 // Create a new event loop.
86 let event_loop = EventLoop::new()?;
87
88 // Configure settings before launching.
89 event_loop.set_control_flow(self.control_flow);
90
91 let app_listener = AppListener::new(window_attributes, listener);
92 // Launch and begin running the event loop.
93 event_loop.run_app(app_listener)?;
94
95 Ok(())
96 }
97}