spectrusty_utils/
keyboard.rs

1/*
2    Copyright (C) 2020-2022  Rafal Michalski
3
4    This file is part of SPECTRUSTY, a Rust library for building emulators.
5
6    For the full copyright notice, see the lib.rs file.
7*/
8//! Keyboard related utilities.
9//!
10//! To make use of one of the event loop dependent implementation of the keyboard utilities add one of the
11//! available features to the `[dependencies]` section in the Cargo configuration file.
12use spectrusty::peripherals::{
13    joystick::{JoystickInterface, Directions}
14};
15
16#[cfg(feature = "minifb")]
17pub mod minifb;
18
19#[cfg(feature = "sdl2")]
20pub mod sdl2;
21
22#[cfg(feature = "winit")]
23pub mod winit;
24
25#[cfg(feature = "web-sys")]
26pub mod web_sys;
27
28/// Updates the state of the joystick device via [JoystickInterface] from a key down or up event.
29///
30/// Returns `true` if the state of the joystick device was updated.
31/// Returns `false` if the `key` didn't correspond to any of the keys mapped to joystick directions
32/// or its fire button or if `get_joy` returns `None`.
33///
34/// * `key` is the key code.
35/// * `pressed` indicates if the `key` was pressed (`true`) or released (`false`).
36/// * `fire_key` is the key code for the `FIRE` button.
37/// * `key_to_dir` is a function that returns the joystick direction flags with a single direction
38///   bit set if a `key` is one of ← → ↑ ↓ keys.
39/// * `get_joy` should return a mutable reference to the [JoystickInterface] implementation instance
40///   if such instance is available.
41pub fn update_joystick_from_key_event<'a, K, J, D, F>(
42            key: K,
43            pressed: bool,
44            fire_key: K,
45            key_to_dir: D,
46            get_joy: F
47        ) -> bool
48    where K: PartialEq + Copy,
49          J: 'a + JoystickInterface + ?Sized,
50          D: FnOnce(K) -> Directions,
51          F: FnOnce() -> Option<&'a mut J>
52{
53    let directions = key_to_dir(key);
54    if !directions.is_empty() {
55        if let Some(joy) = get_joy() {
56            let mut cur_dirs = joy.get_directions();
57            cur_dirs.set(directions, pressed);
58            joy.set_directions(cur_dirs);
59            return true
60        }
61    }
62    else if key == fire_key {
63        if let Some(joy) = get_joy() {
64            joy.fire(0, pressed);
65            return true
66        }
67    }
68    false
69}