#callback #winit #events #helper #flattened #function #logic

winit_event_helper

Simplified winit event handling using callback functions

9 releases (4 breaking)

0.5.0 Feb 11, 2023
0.4.2 Jan 21, 2023
0.3.1 Oct 25, 2022
0.2.1 Sep 30, 2022
0.1.0 Aug 15, 2022

#691 in Math

MIT license

67KB
1.5K SLoC

winit_event_helper

Latest Version API

winit_event_helper is a crate for flattened winit event handling using callback functions without taking over the main loop.

Usage

winit_event_helper comes with the EventHelper struct, which handles all the callbacks and various miscellaneous things.

Pass your events to EventHelper::update and run your application logic when it returns true.

You can add callbacks for specific winit events with the Callbacks struct.

Example

use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::WindowBuilder;
use winit_event_helper::*;

struct Data {
    counter: usize,
}

fn main() {
    let event_loop = EventLoop::new();
    let _window = WindowBuilder::new().build(&event_loop).unwrap();
    
    let mut eh = EventHelper::new(Data { counter: 0 });
    let mut callbacks = Callbacks::<Data>::empty();

    // is called whenever one of the given inputs was just pressed
    callbacks
        .window
        .inputs
        .just_pressed_all([GenericInput::from(MouseButton::Left), KeyCode::Space.into()], |eh| {
            eh.counter += 1
        });
    
    event_loop.run(move |event, _, control_flow| {
        // feed the events to the [EventHelper] struct
        // returns true when it receives [Event::MainEventsCleared]
        if !eh.update(&callbacks, &event) {
            return;
        }

        // exits the application when the key combination CTRL + ESC has been released
        if eh.data.window.inputs.just_released_combination([KeyCode::Escape], Modifiers::CTRL) {
            *control_flow = ControlFlow::Exit;
        }

        println!("{}", eh.counter);

        // do stuff
    })
}

Dependencies

~3–16MB
~171K SLoC