From ad553d5c6c4a8c64c33977acdfb086147027550c Mon Sep 17 00:00:00 2001 From: Marijn Suijten Date: Wed, 1 Nov 2023 15:45:50 +0100 Subject: [PATCH] ash-window/examples/winit: Demonstrate proper surface lifetime with `Suspended`/`Resumed` events --- ash-window/examples/winit.rs | 38 +++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/ash-window/examples/winit.rs b/ash-window/examples/winit.rs index 58b80ba9f..ed240c252 100644 --- a/ash-window/examples/winit.rs +++ b/ash-window/examples/winit.rs @@ -34,16 +34,9 @@ fn main() -> Result<(), Box> { .with_inner_size(PhysicalSize::::from((800, 600))) .build(&event_loop)?; - // Create a surface from winit window. - let surface = ash_window::create_surface( - &entry, - &instance, - window.display_handle()?, - window.window_handle()?, - None, - )?; + // Load the surface extensions let surface_fn = ash::extensions::khr::Surface::new(&entry, &instance); - println!("surface: {surface:?}"); + let mut surface = None; let _ = event_loop.run(move |event, elwp| match event { winit::event::Event::WindowEvent { @@ -62,6 +55,33 @@ fn main() -> Result<(), Box> { elwp.exit(); } Event::LoopExiting => { + // This will be the last event before the loop terminates. + // TODO: How does this play with Suspended? + // https://github.com/rust-windowing/winit/issues/3206 + if let Some(surface) = surface.take() { + surface_fn.destroy_surface(surface, None); + } + } + Event::Resumed => { + // Create a surface from winit window. + let s = ash_window::create_surface( + &entry, + &instance, + window.display_handle().unwrap(), + window.window_handle().unwrap(), + None, + ) + .unwrap(); + println!("surface: {s:?}"); + assert!( + surface.replace(s).is_none(), + "Surface must not yet exist when Resumed is called" + ); + } + Event::Suspended => { + let surface = surface + .take() + .expect("Surface must have been created in Resumed"); surface_fn.destroy_surface(surface, None); } _ => {}