gapp-winit 0.12.1

Abstract event loop library for winit-based applications with OpenGL and wgpu backends, integrating gapp traits for clean separation of input, update, render, and present
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
#![deny(missing_docs)]

/*!
An abstract event loop library for winit-based applications with support for OpenGL (glutin) and wgpu backends.
It cleanly separates input handling, updates, rendering, and presenting via traits and manages a fixed-timestep FPS loop.

# Features

- `opengl`: Enables OpenGL support.
- `wgpu`: Enables wgpu support (recommended).

# Usage

Implement `WindowInput<I, R>`, `Present<R>`, `Render<R>` (from gapp), and `Update` (from gapp) for your app.
Create a `Windows<R>` collection with your backend-specific `WindowData`, then call `run()`.

See [the template](https://gitlab.com/porky11/gapp-template) for reference. It can be used as a starting point.
*/

use std::collections::HashMap;
#[cfg(feature = "wgpu")]
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use std::time::{Duration, Instant};
#[cfg(target_arch = "wasm32")]
use web_time::{Duration, Instant};

pub use gapp::{Render, Update};

#[cfg(feature = "opengl")]
#[cfg(not(target_arch = "wasm32"))]
use glutin::{
    context::PossiblyCurrentContext,
    prelude::*,
    surface::{Surface, WindowSurface},
};
#[cfg(not(target_arch = "wasm32"))]
use winit::dpi::PhysicalSize;
use winit::{
    event::WindowEvent,
    event_loop::ActiveEventLoop,
    window::{Window, WindowId},
};

/// Trait for custom input handling.
///
/// Called for **every** `WindowEvent`, **after** possible internal handling.
/// Handle events like `CloseRequested`, `KeyboardInput`, etc. here.
/// Call `event_loop.exit()` to quit the app.
/// The `windows` parameter provides mutable access to all managed windows and their renderers.
pub trait WindowInput<C, R> {
    /// Processes a `WindowEvent`.
    ///
    /// # Arguments
    ///
    /// - `window_id`: The ID of the window that received the event.
    /// - `event`: The incoming `WindowEvent`.
    /// - `event_loop`: Reference to the active event loop for control (e.g., `exit()`).
    /// - `context`: Custom context to represent input state.
    /// - `windows`: Mutable access to all managed windows and their renderers.
    fn input(
        &mut self,
        window_id: WindowId,
        event: &WindowEvent,
        event_loop: &ActiveEventLoop,
        context: &mut C,
        windows: &mut Windows<R>,
    );
}

/// Platform- and backend-specific window data for OpenGL.
#[cfg(feature = "opengl")]
pub struct WindowData {
    /// The winit window.
    pub window: Window,
    /// The GL context (glutin).
    #[cfg(not(target_arch = "wasm32"))]
    pub context: PossiblyCurrentContext,
    /// The GL surface (glutin).
    #[cfg(not(target_arch = "wasm32"))]
    pub surface: Surface<WindowSurface>,
}

#[cfg(feature = "opengl")]
#[cfg(not(target_arch = "wasm32"))]
impl WindowData {
    /// Creates a window with a current OpenGL context and surface via glutin.
    ///
    /// Picks a config with an alpha channel, preferring transparency and multisampling, then makes
    /// the context current on the new surface. Build your GL renderer afterward from
    /// `window_data.context.display()` (e.g. via `get_proc_address`). All fields are public, so
    /// callers needing different config selection can construct `WindowData` manually instead.
    #[allow(clippy::expect_used)]
    pub fn new_opengl(
        event_loop: &ActiveEventLoop,
        attributes: winit::window::WindowAttributes,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        use glutin::{
            config::ConfigTemplateBuilder,
            context::{ContextApi, ContextAttributesBuilder},
            display::GetGlDisplay,
            surface::SurfaceAttributesBuilder,
        };
        use glutin_winit::DisplayBuilder;
        use raw_window_handle::HasWindowHandle;
        use std::num::NonZeroU32;

        let template = ConfigTemplateBuilder::new().with_alpha_size(8);
        let display_builder = DisplayBuilder::new().with_window_attributes(Some(attributes));

        let (window, gl_config) = display_builder.build(event_loop, template, |configs| {
            configs
                .reduce(|accum, config| {
                    let prefer_config = config.supports_transparency().unwrap_or(false)
                        & !accum.supports_transparency().unwrap_or(false);
                    if prefer_config || config.num_samples() > accum.num_samples() {
                        config
                    } else {
                        accum
                    }
                })
                .expect("no OpenGL configurations available")
        })?;

        let window = window.ok_or("display builder returned no window")?;
        let raw_handle = window.window_handle()?.as_raw();
        let gl_display = gl_config.display();

        let context_attributes = ContextAttributesBuilder::new().build(Some(raw_handle));
        let fallback_attributes = ContextAttributesBuilder::new()
            .with_context_api(ContextApi::Gles(None))
            .build(Some(raw_handle));

        let context = unsafe {
            gl_display
                .create_context(&gl_config, &context_attributes)
                .or_else(|_| gl_display.create_context(&gl_config, &fallback_attributes))?
        };

        let size = window.inner_size();
        let width = NonZeroU32::new(size.width.max(1)).ok_or("zero window width")?;
        let height = NonZeroU32::new(size.height.max(1)).ok_or("zero window height")?;
        let surface_attributes =
            SurfaceAttributesBuilder::<WindowSurface>::new().build(raw_handle, width, height);
        let surface = unsafe { gl_display.create_window_surface(&gl_config, &surface_attributes)? };

        let context = context.make_current(&surface)?;

        Ok(Self {
            window,
            context,
            surface,
        })
    }
}

/// Platform- and backend-specific window data for wgpu.
#[cfg(feature = "wgpu")]
pub struct WindowData {
    /// The wgpu device.
    pub device: wgpu::Device,
    /// The wgpu queue.
    pub queue: wgpu::Queue,
    /// Current surface configuration (updated on resize).
    pub surface_config: wgpu::SurfaceConfiguration,
    /// The wgpu surface (with `'static` lifetime for compatibility).
    pub surface: wgpu::Surface<'static>,
    /// Arc-wrapped winit window (thread-safe).
    pub window: Arc<Window>,
}

#[cfg(feature = "wgpu")]
impl WindowData {
    /// Creates a window and its wgpu device, queue, surface, and configuration.
    ///
    /// Picks the instance backends and adapter from the environment, requests a device with
    /// WebGL2-downlevel limits (portable across native and `wasm32`), and configures the surface
    /// with a non-sRGB format. All fields are public, so callers can adjust the result afterward
    /// (e.g. add `TextureUsages::COPY_SRC` for screenshots, then reconfigure the surface).
    ///
    /// On native targets, drive the returned future with a blocking executor (e.g. `pollster`).
    pub async fn new_wgpu(
        event_loop: &ActiveEventLoop,
        attributes: winit::window::WindowAttributes,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let window = Arc::new(event_loop.create_window(attributes)?);

        let instance = wgpu::util::new_instance_with_webgpu_detection(wgpu::InstanceDescriptor {
            backends: wgpu::Backends::from_env().unwrap_or_default(),
            flags: wgpu::InstanceFlags::from_build_config().with_env(),
            ..wgpu::InstanceDescriptor::new_without_display_handle()
        })
        .await;

        let surface = instance.create_surface(window.clone())?;

        let adapter =
            wgpu::util::initialize_adapter_from_env_or_default(&instance, Some(&surface)).await?;

        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor {
                required_limits: wgpu::Limits::downlevel_webgl2_defaults()
                    .using_resolution(adapter.limits()),
                ..Default::default()
            })
            .await?;

        let size = window.inner_size();
        let mut surface_config = surface
            .get_default_config(&adapter, size.width.max(1), size.height.max(1))
            .ok_or("surface is not supported by the adapter")?;

        let capabilities = surface.get_capabilities(&adapter);
        surface_config.format = capabilities
            .formats
            .iter()
            .find(|format| !format.is_srgb())
            .copied()
            .unwrap_or(capabilities.formats[0]);
        surface.configure(&device, &surface_config);

        Ok(Self {
            device,
            queue,
            surface_config,
            surface,
            window,
        })
    }
}

/// Collection of windows with their associated renderers.
pub struct Windows<R> {
    map: HashMap<WindowId, (WindowData, R)>,
}

impl<R> Windows<R> {
    /// Creates an empty window collection.
    pub fn new() -> Self {
        Self {
            map: HashMap::new(),
        }
    }

    /// Inserts a window and its renderer. Returns the `WindowId`.
    pub fn insert(&mut self, window_data: WindowData, renderer: R) -> WindowId {
        let id = window_data.window.id();
        self.map.insert(id, (window_data, renderer));
        id
    }

    /// Removes a window by ID, returning its data and renderer if present.
    pub fn remove(&mut self, id: &WindowId) -> Option<(WindowData, R)> {
        self.map.remove(id)
    }

    /// Returns a reference to the window data and renderer for the given ID.
    pub fn get(&self, id: &WindowId) -> Option<&(WindowData, R)> {
        self.map.get(id)
    }

    /// Returns a mutable reference to the window data and renderer for the given ID.
    pub fn get_mut(&mut self, id: &WindowId) -> Option<&mut (WindowData, R)> {
        self.map.get_mut(id)
    }

    /// Returns `true` if there are no windows.
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Returns the number of windows.
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Iterates over all windows.
    pub fn iter(&self) -> impl Iterator<Item = (&WindowId, &(WindowData, R))> {
        self.map.iter()
    }

    /// Iterates mutably over all windows.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&WindowId, &mut (WindowData, R))> {
        self.map.iter_mut()
    }
}

impl<R> Default for Windows<R> {
    fn default() -> Self {
        Self::new()
    }
}

/// Trait for presenting the rendered frame.
///
/// Called after `application.render()` in `RedrawRequested` events.
pub trait Present<R> {
    /// Presents the frame to the surface.
    ///
    /// # Arguments
    ///
    /// - `renderer`: Mutable renderer (e.g., for swapchain submit).
    /// - `window_data`: Backend-specific data (surface/context).
    fn present(&self, renderer: &mut R, window_data: &WindowData);
}

type WindowFactory<R> = Box<dyn FnOnce(&ActiveEventLoop) -> Windows<R>>;

struct AppState<I, R, E> {
    application: E,
    timestep: Duration,
    create_windows: Option<WindowFactory<R>>,
    windows: Option<Windows<R>>,
    input_context: I,
    prev_time: Instant,
}

impl<I: 'static, R: 'static, E> winit::application::ApplicationHandler for AppState<I, R, E>
where
    E: WindowInput<I, R> + Present<R> + Render<R> + Update,
{
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if self.windows.is_some() {
            return;
        }
        if let Some(create_windows) = self.create_windows.take() {
            self.windows = Some(create_windows(event_loop));
            self.prev_time = Instant::now();
        }
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        window_id: WindowId,
        event: WindowEvent,
    ) {
        let Some(windows) = &mut self.windows else {
            return;
        };

        #[cfg(not(target_arch = "wasm32"))]
        if let WindowEvent::Resized(PhysicalSize { width, height }) = &event {
            let width = (*width).max(1);
            let height = (*height).max(1);
            if let Some((window_data, _)) = windows.get_mut(&window_id) {
                #[cfg(feature = "opengl")]
                if let (Ok(non_zero_width), Ok(non_zero_height)) =
                    (width.try_into(), height.try_into())
                {
                    window_data.surface.resize(
                        &window_data.context,
                        non_zero_width,
                        non_zero_height,
                    );
                }
                #[cfg(feature = "wgpu")]
                {
                    window_data.surface_config.width = width;
                    window_data.surface_config.height = height;
                    window_data
                        .surface
                        .configure(&window_data.device, &window_data.surface_config);
                }
            }
        }

        self.application.input(
            window_id,
            &event,
            event_loop,
            &mut self.input_context,
            windows,
        );

        if matches!(event, WindowEvent::RedrawRequested)
            && let Some((window_data, renderer)) = windows.get_mut(&window_id)
        {
            self.application.render(renderer);
            self.application.present(renderer, window_data);
        }
    }

    fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
        let Some(windows) = &self.windows else {
            return;
        };

        self.application.update(self.timestep.as_secs_f32());

        #[cfg(not(target_arch = "wasm32"))]
        {
            let frame_duration = self.prev_time.elapsed();
            if frame_duration < self.timestep {
                std::thread::sleep(self.timestep - frame_duration);
            }
        }

        for (_, (window_data, _)) in windows.iter() {
            window_data.window.request_redraw();
        }

        self.prev_time = Instant::now();
    }

    fn exiting(&mut self, _event_loop: &ActiveEventLoop) {}
}

/// Starts the main event loop with a fixed timestep.
///
/// Manages winit events and calls app traits in the correct order:
/// - `input()` after every `WindowEvent` (after internal resize/redraw handling).
/// - `update(timestep)` with fixed timestep in `about_to_wait`.
/// - `render()` + `present()` on `RedrawRequested` (per window).
///
/// **Important notes:**
/// - App (`E`) and states must be `'static` (moved into closure).
/// - Automatic resize handling (clamped to min 1px size).
/// - No automatic close handling: implement in `input()`.
/// - Redraw is requested for all windows on each frame.
/// - The `create_windows` closure is called once in `resumed()`.
///
/// # Type Parameters
///
/// - `I`: Input context type (for `WindowInput`).
/// - `R`: Renderer type.
/// - `E`: App type (must implement `WindowInput<I,R> + Present<R> + Render<R> + Update + 'static`).
pub fn run<
    I: 'static,
    R: 'static,
    E: WindowInput<I, R> + Present<R> + Render<R> + Update + 'static,
>(
    application: E,
    event_loop: winit::event_loop::EventLoop<()>,
    fps: u64,
    create_windows: impl FnOnce(&ActiveEventLoop) -> Windows<R> + 'static,
    input_context: I,
) {
    let timestep = Duration::from_nanos(1_000_000_000 / fps);

    let mut state = AppState {
        application,
        timestep,
        create_windows: Some(Box::new(create_windows)),
        windows: None,
        input_context,
        prev_time: Instant::now(),
    };

    let _ = event_loop.run_app(&mut state);
}