winit_runtime/
lib.rs

1/*
2 * Created on Sat Aug 05 2023
3 *
4 * Copyright (c) storycraft. Licensed under the MIT Licence.
5 */
6
7//! # wm: Async runtime over winit's eventloop
8//!
9//! ## Features
10//! 1. Alloc free async timer
11//! 2. Zero cost event dispatching
12//! 3. Spawn ui tasks anywhere. Tasks run in eventloop's thread concurrently
13
14use executor::{executor_handle, with_eventloop_target};
15use futures_lite::Future;
16use task::Task;
17
18pub mod executor;
19pub mod timer;
20
21pub use async_task as task;
22use winit::{
23    error::OsError,
24    event::{DeviceEvent, DeviceId, WindowEvent},
25    window::{Window, WindowBuilder, WindowId},
26};
27
28/// Spawn and run new task, running on runtime thread
29/// 
30/// See [`ExecutorHandle::spawn`]
31#[inline]
32pub fn spawn_ui_task<Fut>(fut: Fut) -> Task<Fut::Output>
33where
34    Fut: Future + Send + 'static,
35    Fut::Output: Send,
36{
37    executor_handle().spawn(fut)
38}
39
40/// Spawn and run new task, on runtime thread
41/// 
42/// See [`ExecutorHandle::spawn_local`]
43#[inline]
44pub fn spawn_local_ui_task<Fut>(fut: Fut) -> Task<Fut::Output>
45where
46    Fut: Future + 'static,
47    Fut::Output: 'static,
48{
49    executor_handle().spawn_local(fut)
50}
51
52/// Exit event loop with exit code
53#[inline]
54pub async fn exit() -> ! {
55    executor_handle().exit().await
56}
57
58macro_rules! define_event {
59    (pub $name: ident: $($ty: tt)*) => {
60        pub fn $name() -> &'static event_source::EventSource!($($ty)*) {
61            static SOURCE: event_source::EventSource!($($ty)*) = event_source::EventSource::new();
62
63            &SOURCE
64        }
65    };
66}
67
68define_event!(pub window: (WindowId, &mut WindowEvent));
69
70define_event!(pub device: (DeviceId, &DeviceEvent));
71
72define_event!(pub resumed: ());
73
74define_event!(pub suspended: ());
75
76/// Create new window using given [`WindowBuilder`]
77/// 
78/// also see [`with_eventloop_target`]
79pub fn build_window(builder: WindowBuilder) -> Result<Window, OsError> {
80    with_eventloop_target(move |target| builder.build(target))
81}
82
83#[inline]
84/// Create new window with default configuration
85/// 
86/// This function shortcut for [`build_window(WindowBuilder::new())`]
87pub fn create_window() -> Result<Window, OsError> {
88    build_window(WindowBuilder::new())
89}
90
91pub use executor::run;