pteropus/src/native/mod.rs

80 lines
2.3 KiB
Rust

use std::{rc::Rc, sync::Arc};
use crate::mvu::{self, MvuApp, Size2i};
use {
futures::executor::block_on,
winit::{
application::ApplicationHandler,
dpi::PhysicalSize,
event::WindowEvent,
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
window::{Window, WindowId},
},
};
struct AppHost<A, M> {
window: Option<Arc<Window>>,
app: A,
model: Rc<M>,
}
impl<A, M> AppHost<A, M> {
fn new(app: A, model: Rc<M>) -> Self {
Self {
window: None,
app,
model,
}
}
}
impl<A, M> ApplicationHandler for AppHost<A, M>
where
A: MvuApp<M>,
{
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
let window = Arc::new(
event_loop
.create_window(Window::default_attributes())
.unwrap(),
);
let instance = wgpu::Instance::default();
let surface = instance.create_surface(Arc::clone(&window)).unwrap();
let PhysicalSize { width, height } = window.inner_size();
self.window = Some(window);
block_on(self.app.init(&instance, surface, Size2i { width, height }));
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
match event {
WindowEvent::Resized(new_size) => block_on(self.app.resize(Size2i {
width: new_size.width,
height: new_size.height,
})),
WindowEvent::CloseRequested => {
println!("The close button was pressed; stopping");
event_loop.exit();
}
WindowEvent::RedrawRequested => block_on(self.app.view(self.model.clone())).unwrap(),
WindowEvent::DroppedFile(file_path) => {
self.model = block_on(
self.app
.update(self.model.clone(), mvu::Event::OpenTestFile(file_path)),
)
}
_ => (),
}
}
}
pub fn run<A, M>(app: A, model: Rc<M>)
where
A: MvuApp<M>,
{
env_logger::init();
let event_loop = EventLoop::new().unwrap();
event_loop.set_control_flow(ControlFlow::Poll);
let mut app_host = AppHost::new(app, model);
event_loop.run_app(&mut app_host).unwrap();
}