run_on_demand/
run_on_demand.rs1#![allow(clippy::single_match)]
2
3#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform,))]
5fn main() -> Result<(), Box<dyn std::error::Error>> {
6 use std::time::Duration;
7
8 use winit::application::ApplicationHandler;
9 use winit::event::WindowEvent;
10 use winit::event_loop::{ActiveEventLoop, EventLoop};
11 use winit::platform::run_on_demand::EventLoopExtRunOnDemand;
12 use winit::window::{Window, WindowId};
13
14 #[path = "util/fill.rs"]
15 mod fill;
16
17 #[derive(Default)]
18 struct App {
19 idx: usize,
20 window_id: Option<WindowId>,
21 window: Option<Window>,
22 }
23
24 impl ApplicationHandler for App {
25 fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
26 if let Some(window) = self.window.as_ref() {
27 window.request_redraw();
28 }
29 }
30
31 fn resumed(&mut self, event_loop: &ActiveEventLoop) {
32 let window_attributes = Window::default_attributes()
33 .with_title("Fantastic window number one!")
34 .with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0));
35 let window = event_loop.create_window(window_attributes).unwrap();
36 self.window_id = Some(window.id());
37 self.window = Some(window);
38 }
39
40 fn window_event(
41 &mut self,
42 event_loop: &ActiveEventLoop,
43 window_id: WindowId,
44 event: WindowEvent,
45 ) {
46 if event == WindowEvent::Destroyed && self.window_id == Some(window_id) {
47 println!(
48 "--------------------------------------------------------- Window {} Destroyed",
49 self.idx
50 );
51 self.window_id = None;
52 event_loop.exit();
53 return;
54 }
55
56 let window = match self.window.as_mut() {
57 Some(window) => window,
58 None => return,
59 };
60
61 match event {
62 WindowEvent::CloseRequested => {
63 println!(
64 "--------------------------------------------------------- Window {} \
65 CloseRequested",
66 self.idx
67 );
68 fill::cleanup_window(window);
69 self.window = None;
70 },
71 WindowEvent::RedrawRequested => {
72 fill::fill_window(window);
73 },
74 _ => (),
75 }
76 }
77 }
78
79 tracing_subscriber::fmt::init();
80
81 let mut event_loop = EventLoop::new().unwrap();
82
83 let mut app = App { idx: 1, ..Default::default() };
84 event_loop.run_app_on_demand(&mut app)?;
85
86 println!("--------------------------------------------------------- Finished first loop");
87 println!("--------------------------------------------------------- Waiting 5 seconds");
88 std::thread::sleep(Duration::from_secs(5));
89
90 app.idx += 1;
91 event_loop.run_app_on_demand(&mut app)?;
92 println!("--------------------------------------------------------- Finished second loop");
93 Ok(())
94}
95
96#[cfg(not(any(windows_platform, macos_platform, x11_platform, wayland_platform,)))]
97fn main() {
98 println!("This example is not supported on this platform");
99}