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
use crate::BindTarget;
use egui::{InputState, Key, Modifiers, PointerButton};
use std::ops::Deref;

/// Bind target that can be either a [`egui::Key`] or a [`egui::PointerButton`]
#[derive(Debug, Clone)]
pub enum KeyOrPointer {
    /// Key bind
    Key(Key),
    /// Pointer bind
    Pointer(PointerButton),
}

impl BindTarget for KeyOrPointer {
    const IS_KEY: bool = true;
    const IS_POINTER: bool = true;
    const CLEARABLE: bool = false;

    fn set_key(&mut self, key: Key, _: Modifiers) {
        *self = Self::Key(key);
    }

    fn set_pointer(&mut self, button: PointerButton, _: Modifiers) {
        *self = Self::Pointer(button);
    }

    fn clear(&mut self) {
        unimplemented!()
    }

    fn format(&self) -> String {
        match self {
            Self::Key(k) => k.format(),
            Self::Pointer(p) => p.format(),
        }
    }

    fn down(&self, input: impl Deref<Target = InputState>) -> bool {
        match self {
            Self::Key(k) => k.down(input),
            Self::Pointer(p) => p.down(input),
        }
    }

    fn pressed(&self, input: impl Deref<Target = InputState>) -> bool {
        match self {
            Self::Key(k) => k.pressed(input),
            Self::Pointer(p) => p.pressed(input),
        }
    }

    fn released(&self, input: impl Deref<Target = InputState>) -> bool {
        match self {
            Self::Key(k) => k.released(input),
            Self::Pointer(p) => p.released(input),
        }
    }
}

impl BindTarget for Option<KeyOrPointer> {
    const IS_KEY: bool = true;
    const IS_POINTER: bool = true;
    const CLEARABLE: bool = true;

    fn set_key(&mut self, key: Key, _: Modifiers) {
        *self = Some(KeyOrPointer::Key(key));
    }

    fn set_pointer(&mut self, button: PointerButton, _: Modifiers) {
        *self = Some(KeyOrPointer::Pointer(button));
    }

    fn clear(&mut self) {
        *self = None
    }

    fn format(&self) -> String {
        match self {
            Some(KeyOrPointer::Key(k)) => k.format(),
            Some(KeyOrPointer::Pointer(p)) => p.format(),
            None => "None".into(),
        }
    }

    fn down(&self, input: impl Deref<Target = InputState>) -> bool {
        self.as_ref().map(|v| v.down(input)).unwrap_or(false)
    }

    fn pressed(&self, input: impl Deref<Target = InputState>) -> bool {
        self.as_ref().map(|v| v.pressed(input)).unwrap_or(false)
    }

    fn released(&self, input: impl Deref<Target = InputState>) -> bool {
        self.as_ref().map(|v| v.released(input)).unwrap_or(false)
    }
}