mirror of
https://github.com/rust-windowing/winit.git
synced 2026-06-26 22:53:15 -04:00
This helps with portability and defines some top-level structure around the event loop, so in the future, backends can get an idea of what API to use. This also changes the API to be object safe by using `dyn` throughout.
84 lines
2.6 KiB
Rust
84 lines
2.6 KiB
Rust
//! Simple winit window example.
|
|
|
|
use std::error::Error;
|
|
|
|
use winit::application::ApplicationHandler;
|
|
use winit::event::WindowEvent;
|
|
use winit::event_loop::{ActiveEventLoop, EventLoop, EventLoopProvider};
|
|
#[cfg(web_platform)]
|
|
use winit::platform::web::WindowAttributesExtWeb;
|
|
use winit::window::{Window, WindowAttributes, WindowId};
|
|
|
|
#[path = "util/fill.rs"]
|
|
mod fill;
|
|
#[path = "util/tracing.rs"]
|
|
mod tracing;
|
|
|
|
#[derive(Default, Debug)]
|
|
struct App {
|
|
window: Option<Box<dyn Window>>,
|
|
}
|
|
|
|
impl ApplicationHandler for App {
|
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
|
#[cfg(not(web_platform))]
|
|
let window_attributes = WindowAttributes::default();
|
|
#[cfg(web_platform)]
|
|
let window_attributes = WindowAttributes::default().with_append(true);
|
|
self.window = match event_loop.create_window(window_attributes) {
|
|
Ok(window) => Some(window),
|
|
Err(err) => {
|
|
eprintln!("error creating window: {err}");
|
|
event_loop.exit();
|
|
return;
|
|
},
|
|
}
|
|
}
|
|
|
|
fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, _: WindowId, event: WindowEvent) {
|
|
println!("{event:?}");
|
|
match event {
|
|
WindowEvent::CloseRequested => {
|
|
println!("Close was requested; stopping");
|
|
event_loop.exit();
|
|
},
|
|
WindowEvent::SurfaceResized(_) => {
|
|
self.window.as_ref().expect("resize event without a window").request_redraw();
|
|
},
|
|
WindowEvent::RedrawRequested => {
|
|
// Redraw the application.
|
|
//
|
|
// It's preferable for applications that do not render continuously to render in
|
|
// this event rather than in AboutToWait, since rendering in here allows
|
|
// the program to gracefully handle redraws requested by the OS.
|
|
|
|
let window = self.window.as_ref().expect("redraw request without a window");
|
|
|
|
// Notify that you're about to draw.
|
|
window.pre_present_notify();
|
|
|
|
// Draw.
|
|
fill::fill_window(window.as_ref());
|
|
|
|
// For contiguous redraw loop you can request a redraw from here.
|
|
// window.request_redraw();
|
|
},
|
|
_ => (),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn main() -> Result<(), Box<dyn Error>> {
|
|
#[cfg(web_platform)]
|
|
console_error_panic_hook::set_once();
|
|
|
|
tracing::init();
|
|
|
|
let event_loop = EventLoop::new()?;
|
|
|
|
// For alternative loop run options see `pump_events` and `run_on_demand` examples.
|
|
event_loop.run_app(App::default())?;
|
|
|
|
Ok(())
|
|
}
|