Skip to main content

wgame_app/
lib.rs

1//! A cooperative event-loop runtime for windows, tasks, and timers.
2//!
3//! Work runs on the event-loop thread: blocking CPU work also blocks input and
4//! rendering. Awaiting file I/O or timers yields control. A [`Runtime`] handle is
5//! local to this thread.
6//! Expired timers schedule another task poll even when there are no window or
7//! input events; idle applications can use timers without continuous redraws.
8//!
9//! [`spawn`] creates a single-consumer [`Task`]. Use [`Task::handle`] for shared
10//! cancellation and [`Task::cancel_on_drop`] for work owned by a window or scope.
11//! [`WindowedTask`] similarly separates its result from its cancellation handle.
12//! See those types for cancellation and suspension behavior.
13//!
14//! Native builds require an appropriate backend (`x11`/`wayland` on Linux, `std` on
15//! Windows/macOS). Native and `web` runtime features cannot be enabled together.
16
17#![forbid(unsafe_code)]
18
19#[cfg(all(feature = "std", feature = "web"))]
20compile_error!("`std` and `web` enabled at once");
21
22mod app;
23mod executor;
24pub mod output;
25pub mod runtime;
26pub mod time;
27pub mod window;
28mod windowed_task;
29
30pub use crate::{
31    app::App,
32    runtime::{Runtime, ScopedTask, Task, TaskHandle, sleep, spawn},
33    window::Window,
34    windowed_task::{WindowError, WindowTaskHandle, WindowedTask, create_windowed_task},
35};
36pub use wgame_app_input::{Event, Input};
37pub use winit::{
38    dpi::{LogicalSize, PhysicalSize as Size},
39    window::{Window as RawWindow, WindowAttributes},
40};
41pub mod input {
42    pub use wgame_app_input::{Event, Input, event, keyboard};
43}
44
45use std::{cell::RefCell, fmt::Debug, rc::Rc};
46
47/// Trait for main function return types.
48pub trait MainResult {
49    fn try_unwrap(self);
50}
51
52impl MainResult for () {
53    fn try_unwrap(self) {}
54}
55
56impl<E: Debug> MainResult for Result<(), E> {
57    fn try_unwrap(self) {
58        self.unwrap()
59    }
60}
61
62/// Runs an application with the given async function.
63pub fn run_app<R, F>(app_fn: F)
64where
65    R: MainResult + 'static,
66    F: AsyncFnOnce() -> R + 'static,
67{
68    log::info!("Running App");
69    let app = App::new().unwrap();
70    let task = app.runtime().create_task(app_fn());
71    app.run().unwrap();
72    task.output()
73        .try_take()
74        .unwrap()
75        .expect("Main task has been interrupted")
76        .try_unwrap();
77}
78
79/// Runs an application with a single window.
80#[allow(clippy::await_holding_refcell_ref)]
81pub async fn app_with_single_window<R, F>(window_fn: F) -> R
82where
83    R: MainResult + 'static,
84    F: AsyncFnMut(Window) -> R + 'static,
85{
86    let window_fn = Rc::new(RefCell::new(window_fn));
87    loop {
88        let window_fn = window_fn.clone();
89        let result = create_windowed_task(
90            &Runtime::current(),
91            WindowAttributes::default(),
92            async move |window| {
93                log::info!("Window created");
94                let result = (window_fn.borrow_mut())(window).await;
95                log::info!("Window closed");
96                result
97            },
98        )
99        .await;
100        match result {
101            Ok(x) => break x,
102            Err(e) => match e {
103                WindowError::Creation(e) => panic!("Cannot create main window: {e}"),
104                WindowError::Terminated => panic!("Main window terminated"),
105                WindowError::Suspended => log::info!("Suspended"),
106            },
107        }
108    }
109}
110
111/// Entry point for standard library builds.
112#[cfg(feature = "std")]
113#[allow(clippy::unit_arg)]
114pub fn entry<R, F>(app_fn: F)
115where
116    R: MainResult + 'static,
117    F: AsyncFnOnce() -> R + 'static,
118{
119    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
120
121    run_app(app_fn).try_unwrap();
122}
123
124/// Entry point for web builds.
125#[cfg(feature = "web")]
126#[allow(clippy::unit_arg)]
127pub fn entry<R, F>(app_fn: F)
128where
129    R: MainResult + 'static,
130    F: AsyncFnOnce() -> R + 'static,
131{
132    console_error_panic_hook::set_once();
133    console_log::init_with_level(log::Level::Info).unwrap();
134
135    run_app(app_fn).try_unwrap();
136}
137
138/// Entry point for builds without either `std` or `web` feature.
139#[cfg(all(not(feature = "std"), not(feature = "web")))]
140pub fn entry<R, F>(_app_fn: F)
141where
142    R: MainResult + 'static,
143    F: AsyncFnOnce() -> R + 'static,
144{
145    compile_error!("Enable a native backend (x11/wayland/android/std) or web");
146}
147
148/// Macro to generate a main function for an application.
149#[macro_export]
150macro_rules! app_main {
151    ($app_fn:expr) => {
152        fn main() {
153            $crate::entry($app_fn);
154        }
155    };
156}
157
158/// Macro to generate a main function for a windowed application.
159#[macro_export]
160macro_rules! window_main {
161    ($window_fn:expr) => {
162        fn main() {
163            $crate::entry(async || $crate::app_with_single_window($window_fn).await);
164        }
165    };
166}