pump_events/
pump_events.rs

1#![allow(clippy::single_match)]
2
3// Limit this example to only compatible platforms.
4#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform, android_platform,))]
5fn main() -> std::process::ExitCode {
6    use std::process::ExitCode;
7    use std::thread::sleep;
8    use std::time::Duration;
9
10    use winit::application::ApplicationHandler;
11    use winit::event::WindowEvent;
12    use winit::event_loop::{ActiveEventLoop, EventLoop};
13    use winit::platform::pump_events::{EventLoopExtPumpEvents, PumpStatus};
14    use winit::window::{Window, WindowId};
15
16    #[path = "util/fill.rs"]
17    mod fill;
18
19    #[derive(Default)]
20    struct PumpDemo {
21        window: Option<Window>,
22    }
23
24    impl ApplicationHandler for PumpDemo {
25        fn resumed(&mut self, event_loop: &ActiveEventLoop) {
26            let window_attributes = Window::default_attributes().with_title("A fantastic window!");
27            self.window = Some(event_loop.create_window(window_attributes).unwrap());
28        }
29
30        fn window_event(
31            &mut self,
32            event_loop: &ActiveEventLoop,
33            _window_id: WindowId,
34            event: WindowEvent,
35        ) {
36            println!("{event:?}");
37
38            let window = match self.window.as_ref() {
39                Some(window) => window,
40                None => return,
41            };
42
43            match event {
44                WindowEvent::CloseRequested => event_loop.exit(),
45                WindowEvent::RedrawRequested => {
46                    fill::fill_window(window);
47                    window.request_redraw();
48                },
49                _ => (),
50            }
51        }
52    }
53
54    let mut event_loop = EventLoop::new().unwrap();
55
56    tracing_subscriber::fmt::init();
57
58    let mut app = PumpDemo::default();
59
60    loop {
61        let timeout = Some(Duration::ZERO);
62        let status = event_loop.pump_app_events(timeout, &mut app);
63
64        if let PumpStatus::Exit(exit_code) = status {
65            break ExitCode::from(exit_code as u8);
66        }
67
68        // Sleep for 1/60 second to simulate application work
69        //
70        // Since `pump_events` doesn't block it will be important to
71        // throttle the loop in the app somehow.
72        println!("Update()");
73        sleep(Duration::from_millis(16));
74    }
75}
76
77#[cfg(any(ios_platform, web_platform, orbital_platform))]
78fn main() {
79    println!("This platform doesn't support pump_events.");
80}