Skip to main content

sim_logic/ui/
pointer_button.rs

1use crate::input::{Action, ActionEdge, ButtonState, InputControl, MouseButton};
2
3mod events;
4pub use events::{PointerButtonCancellation, PointerButtonEvent, PointerButtonOutcome};
5
6#[derive(Debug, Clone, Copy)]
7enum Capture<T> {
8    Idle,
9    Outside,
10    Target(T),
11    Suppressed,
12}
13
14/// Tracks press-to-release ownership for one physical mouse button.
15///
16/// The caller selects an eligible target at each edge's pointer position, then
17/// feeds the complete ordered [`crate::input::FrameInput::edges`] sequence once.
18/// Never also feed its retained FixedInput copies: replaying a completed pair
19/// can confirm a second click. Keyboard aliases and other mouse buttons cannot
20/// disturb this controller. A press outside all eligible targets cannot become
21/// a click merely by releasing over a button later.
22///
23/// This is a headless state machine, not a widget renderer, drag-motion stream,
24/// OS pointer grab, keyboard-focus tree, or global input-consumption service.
25/// Processing allocates no internal storage and registers no callbacks. Target
26/// equality uses the caller's `Eq` implementation, whose costs remain its own.
27///
28/// Target liveness and overlap priority belong to the caller. Invalidate capture
29/// with [`Self::cancel`] when the target is removed, disabled or made ineligible.
30/// Use generation-qualified IDs such as [`crate::identity::LogicEntity`] for ECS
31/// targets. Prefer a World-local Resource recreated on replacement; a persistent
32/// controller must be cancelled at world changes and continue receiving release
33/// boundaries. Keeping a controller in an inactive world can miss its release.
34#[derive(Debug)]
35pub struct PointerButton<T: Copy + Eq> {
36    button: MouseButton,
37    capture: Capture<T>,
38}
39
40impl<T: Copy + Eq> PointerButton<T> {
41    /// Creates an idle controller without allocating or requiring a renderer.
42    /// Only action edges from this physical mouse button are interpreted.
43    pub const fn new(button: MouseButton) -> Self {
44        Self {
45            button,
46            capture: Capture::Idle,
47        }
48    }
49
50    /// Returns the configured physical mouse button, independent of action names.
51    pub const fn button(&self) -> MouseButton {
52        self.button
53    }
54
55    /// Returns the original pressed target while it still owns the gesture.
56    /// Use this for held styling, not as proof that the pointer is still inside.
57    pub const fn captured(&self) -> Option<T> {
58        match self.capture {
59            Capture::Target(target) => Some(target),
60            _ => None,
61        }
62    }
63
64    /// Invalidates a captured target and returns it for caller-owned cleanup.
65    ///
66    /// Its remaining matching mouse edges stay claimed until release. A removed
67    /// or disabled button therefore cannot transfer an in-progress UI gesture
68    /// to the gameplay beneath it, even if the same target value reappears.
69    /// Without capture this does nothing. It neither invents an input token nor
70    /// emits an event; the caller knows why it explicitly invalidated the target.
71    pub fn cancel(&mut self) -> Option<T> {
72        let target = self.captured()?;
73        self.capture = Capture::Suppressed;
74        Some(target)
75    }
76
77    /// Interprets one ordered edge using its caller-selected eligible hit target.
78    ///
79    /// Compute `hit` from this edge's sample, not the frame's latest pointer.
80    /// Unknown or out-of-viewport samples cannot capture or confirm even if
81    /// `hit` is Some. Normal release over the captured target clicks; release
82    /// elsewhere or runtime cancellation ends capture without confirmation.
83    /// Multiple pairs in one frame are processed in their supplied order.
84    ///
85    /// No snapshot is consumed. Inspect [`PointerButtonOutcome::claimed`] before
86    /// forwarding this edge to gameplay. FixedUpdate precedes FrameUpdate;
87    /// routing here cannot undo a game action already applied in FixedUpdate.
88    /// Route competing actions together, or queue accepted gameplay intents for
89    /// a later fixed tick. This helper does not change the runtime schedule.
90    pub fn process<A: Action>(
91        &mut self,
92        edge: ActionEdge<A>,
93        hit: Option<T>,
94    ) -> PointerButtonOutcome<T> {
95        if edge.control() != InputControl::MouseButton(self.button) {
96            return outcome(false, None);
97        }
98        match edge.state() {
99            ButtonState::Pressed => match self.capture {
100                Capture::Target(_) | Capture::Suppressed => outcome(true, None),
101                Capture::Outside => outcome(false, None),
102                Capture::Idle => {
103                    if let Some((target, pointer)) = hit.zip(edge.pointer())
104                        && pointer.is_inside_viewport()
105                    {
106                        self.capture = Capture::Target(target);
107                        outcome(
108                            true,
109                            Some(PointerButtonEvent::Pressed {
110                                target,
111                                pointer,
112                                intent: edge.intent(),
113                            }),
114                        )
115                    } else {
116                        self.capture = Capture::Outside;
117                        outcome(false, None)
118                    }
119                }
120            },
121            ButtonState::Released => {
122                let capture = std::mem::replace(&mut self.capture, Capture::Idle);
123                match capture {
124                    Capture::Idle | Capture::Outside => outcome(false, None),
125                    Capture::Suppressed => outcome(true, None),
126                    Capture::Target(target) => {
127                        let reason = if let Some(reason) = edge.cancellation_reason() {
128                            PointerButtonCancellation::Input(reason)
129                        } else if let Some(pointer) = edge.pointer() {
130                            if pointer.is_inside_viewport() && hit == Some(target) {
131                                return outcome(
132                                    true,
133                                    Some(PointerButtonEvent::Clicked {
134                                        target,
135                                        pointer,
136                                        intent: edge.intent(),
137                                    }),
138                                );
139                            }
140                            PointerButtonCancellation::ReleasedOutside
141                        } else {
142                            PointerButtonCancellation::MissingPointer
143                        };
144                        outcome(
145                            true,
146                            Some(PointerButtonEvent::Cancelled {
147                                target,
148                                reason,
149                                intent: edge.intent(),
150                            }),
151                        )
152                    }
153                }
154            }
155        }
156    }
157}
158
159fn outcome<T>(claimed: bool, event: Option<PointerButtonEvent<T>>) -> PointerButtonOutcome<T> {
160    PointerButtonOutcome { claimed, event }
161}