ferravex_play/input/
mod.rs

1//! Bounded action mapping shared by platform hosts. Digital edges and accumulated
2//! motion survive until consumed; frames and fixed simulation ticks are separate.
3use std::sync::atomic::{AtomicUsize, Ordering};
4
5mod config;
6#[cfg(test)]
7mod tests;
8pub use config::{
9    AppliedConfig, BindingConflict, ConfigBinding, ConfigError, ConfigValidation, ControlSettings,
10    DecodedConfig, MAX_CONFIG_BYTES, MAX_CONFIG_CONFLICTS, SavedAction, decode_config,
11};
12pub mod touch;
13pub const MAX_ACTIONS: usize = 256;
14pub const MAX_BINDINGS: usize = 64;
15pub const MAX_ACTIVE_CODES: usize = 1024;
16pub const MAX_CONTEXTS: usize = 16;
17pub const MAX_CONTEXT_DEPTH: usize = 8;
18#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
19pub enum InputCode {
20    Key(u16),
21    Mouse(u8),
22    PadButton(u8),
23    PadAxis(u8),
24    Touch(u8),
25    /// Relative logical-pixel motion, accumulated rather than held.
26    MouseDelta(u8),
27    TouchDelta(u8),
28    Wheel(u8),
29}
30impl InputCode {
31    pub fn is_delta(self) -> bool {
32        matches!(
33            self,
34            Self::MouseDelta(_) | Self::TouchDelta(_) | Self::Wheel(_)
35        )
36    }
37    pub fn valid(self) -> bool {
38        match self {
39            Self::Key(k) => k != 0,
40            Self::Mouse(b) => (1..=5).contains(&b),
41            Self::PadButton(b) => b < 32,
42            Self::PadAxis(a) => a < 16,
43            Self::Touch(t) => t < 64,
44            Self::MouseDelta(a) | Self::Wheel(a) => a < 2,
45            Self::TouchDelta(a) => a < 16,
46        }
47    }
48}
49#[derive(Clone, Copy, Debug, PartialEq)]
50pub struct Binding {
51    pub code: InputCode,
52    pub scale: f32,
53    pub deadzone: f32,
54}
55impl Binding {
56    pub fn digital(code: InputCode) -> Self {
57        Self {
58            code,
59            scale: 1.,
60            deadzone: 0.,
61        }
62    }
63    fn valid(self) -> bool {
64        self.code.valid()
65            && self.scale.is_finite()
66            && self.deadzone.is_finite()
67            && (0. ..=0.99).contains(&self.deadzone)
68            && (!self.code.is_delta() || self.deadzone == 0.)
69    }
70}
71#[derive(Clone, Copy, Default, Debug, PartialEq)]
72pub struct Action {
73    pub value: f32,
74    pub pressed: bool,
75    pub released: bool,
76}
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum ActionKind {
79    Axis,
80    Button,
81    Delta,
82}
83/// An opaque action identity owned by one [`ActionMap`].
84///
85/// Resolve a name once with [`ActionMap::action_handle`], or register with
86/// [`ActionMap::named_action_handle`], then sample without string lookups. Copies
87/// refer to the same action and share its pending edges and motion; a handle is
88/// not an independent input subscription.
89///
90/// Handles survive moves of their map, new registrations, rebinding, config
91/// application, focus changes and context changes. Entries cannot be removed.
92/// Replacing or dropping the map makes its handles stale: even an identically
93/// configured replacement rejects them with [`InputError::InvalidHandle`].
94/// Handles are process-local identities, not save/replay IDs; persist action
95/// names instead. Legacy `usize` IDs do not carry this ownership protection.
96///
97/// ```
98/// use ferravex_play::input::{ActionKind, ActionMap, Binding, ContextId, InputCode};
99///
100/// let mut input = ActionMap::default();
101/// input.named_action_handle(
102///     "jump", ActionKind::Button, ContextId::GLOBAL,
103///     vec![Binding::digital(InputCode::Key(32))],
104/// )?;
105/// let jump = input.action_handle("jump").expect("registered action");
106/// input.feed(InputCode::Key(32), 1.0);
107/// assert!(input.peek_handle(jump)?.pressed); // Preview does not consume.
108/// assert!(input.consume_tick_handle(jump)?.pressed);
109/// let next_tick = input.consume_tick_handle(jump)?;
110/// assert_eq!(next_tick.value, 1.0); // A held button stays down.
111/// assert!(!next_tick.pressed); // Its edge fires on only one tick.
112/// # Ok::<(), ferravex_play::input::InputError>(())
113/// ```
114#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
115pub struct ActionHandle {
116    map_id: usize,
117    index: usize,
118}
119
120/// A rejected atomic group read. Neither input nor caller output is changed.
121///
122/// Checks run in this order: handle count, output capacity, then handles in
123/// caller order. The count includes duplicates and is bounded by [`MAX_ACTIONS`].
124/// This separate error leaves the legacy [`InputError`] variants unchanged.
125///
126/// ```
127/// use ferravex_play::input::{Action, ActionMap, ActionSnapshotError};
128/// let mut input = ActionMap::default();
129/// let id = input.action(vec![]);
130/// let handle = input.handle_from_id(id).unwrap();
131/// let mut other = ActionMap::default();
132/// let id = other.action(vec![]);
133/// let foreign = other.handle_from_id(id).unwrap();
134/// let sentinel = Action { value: 0.5, ..Action::default() };
135/// let mut output = [sentinel; 2];
136/// assert_eq!(input.consume_tick_handles_into(&[handle, foreign], &mut output),
137///     Err(ActionSnapshotError::InvalidHandle { index: 1 }));
138/// assert_eq!(output, [sentinel; 2]);
139/// ```
140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141pub enum ActionSnapshotError {
142    /// More than [`MAX_ACTIONS`] handles were requested.
143    TooManyHandles { count: usize },
144    /// The output cannot hold one snapshot per requested handle.
145    OutputTooSmall { required: usize, available: usize },
146    /// The handle at this zero-based position is foreign, stale or out of bounds.
147    InvalidHandle { index: usize },
148}
149impl std::fmt::Display for ActionSnapshotError {
150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151        write!(f, "action snapshot: {self:?}")
152    }
153}
154impl std::error::Error for ActionSnapshotError {}
155
156/// Borrowed metadata for building hints from an action's current bindings.
157///
158/// Obtain this view from [`ActionMap::action_descriptor`] or
159/// [`ActionMap::action_descriptors`]. Names and bindings borrow the map without
160/// allocating or consuming input. Reacquire the view after rebinding, applying
161/// a config or changing contexts; the borrow prevents concurrent map mutation.
162/// Keep the [`ActionHandle`] if a longer-lived identity is needed.
163///
164/// ```
165/// use ferravex_play::input::{ActionKind, ActionMap, Binding, ContextMode, InputCode};
166///
167/// let mut input = ActionMap::default();
168/// let gameplay = input.create_context("gameplay")?;
169/// let jump = input.named_action_handle(
170///     "jump", ActionKind::Button, gameplay,
171///     vec![Binding::digital(InputCode::Key(32))],
172/// )?;
173/// input.push_context(gameplay, ContextMode::Exclusive)?;
174/// let hint = input.action_descriptor(jump)?;
175/// assert_eq!(hint.handle, jump);
176/// assert_eq!(hint.name, Some("jump"));
177/// assert_eq!(hint.kind, ActionKind::Button);
178/// assert_eq!(hint.context, gameplay);
179/// assert_eq!(hint.context_name, "gameplay");
180/// assert!(hint.context_active);
181/// assert_eq!(hint.bindings[0].code, InputCode::Key(32));
182/// # Ok::<(), ferravex_play::input::InputError>(())
183/// ```
184#[derive(Clone, Copy, Debug, PartialEq)]
185pub struct ActionDescriptor<'a> {
186    /// Identity owned by the map that produced this view, including for unnamed actions.
187    pub handle: ActionHandle,
188    /// Registered name, or `None` for legacy unnamed actions.
189    pub name: Option<&'a str>,
190    /// How the action interprets its bindings and consumes input.
191    pub kind: ActionKind,
192    /// Context used to gate this action in its owning map.
193    pub context: ContextId,
194    /// Registered context name; global actions use `"global"`.
195    pub context_name: &'a str,
196    /// Whether the context stack enables this action. Global actions are always
197    /// active. This does not indicate focus, held-button suppression, a connected
198    /// device or whether the action has any bindings.
199    pub context_active: bool,
200    /// Current bindings, validated for this action's kind on registration,
201    /// rebinding or config application. At most [`MAX_BINDINGS`] entries, in
202    /// authored order, including duplicates and zero scales. An empty slice
203    /// means unbound. Inspection does not filter by device availability.
204    pub bindings: &'a [Binding],
205}
206
207// Never recycle identities: handles may outlive their map. Relaxed ordering is
208// enough because this counter allocates identities, not shared input state.
209static NEXT_MAP_ID: AtomicUsize = AtomicUsize::new(1);
210
211#[derive(Clone, Copy, Debug, PartialEq, Eq)]
212pub struct ContextId(u8);
213impl ContextId {
214    /// Global actions remain active below every stack entry.
215    pub const GLOBAL: Self = Self(0);
216}
217#[derive(Clone, Copy, Debug, PartialEq, Eq)]
218pub enum ContextMode {
219    Exclusive,
220    Passthrough,
221}
222#[derive(Clone, Copy, Debug, PartialEq, Eq)]
223pub enum InputError {
224    InvalidName,
225    DuplicateName,
226    InvalidBinding,
227    InvalidHandle,
228    ActionCapacity,
229    BindingCapacity,
230    ContextCapacity,
231    ContextDepth,
232    InvalidContext,
233    InvalidTouch,
234    TouchCapacity,
235    InvalidConfig,
236    ConfigVersion,
237    ConfigChecksum,
238}
239impl std::fmt::Display for InputError {
240    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
241        write!(f, "input: {self:?}")
242    }
243}
244impl std::error::Error for InputError {}
245fn valid_name(name: &str) -> bool {
246    !name.is_empty()
247        && name.len() <= 64
248        && name
249            .bytes()
250            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_-.".contains(&b))
251}
252struct Entry {
253    name: Option<String>,
254    kind: ActionKind,
255    context: ContextId,
256    bindings: Box<[Binding]>,
257    state: Action,
258    suppressed: bool,
259}
260/// Registration/rebinding may allocate. Feeds, consumption and context changes
261/// reuse bounded storage. [`ActionHandle`] access checks map ownership and bounds
262/// in constant time without allocating. Legacy `usize` access remains available.
263pub struct ActionMap {
264    map_id: usize,
265    entries: Vec<Entry>,
266    values: Vec<(InputCode, f32)>,
267    contexts: Vec<String>,
268    stack: Vec<(ContextId, ContextMode)>,
269}
270impl Default for ActionMap {
271    fn default() -> Self {
272        // Atomic::try_update is newer than the workspace Rust 1.88 minimum.
273        #[allow(deprecated)]
274        let map_id = NEXT_MAP_ID
275            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
276            .expect("action map identity space exhausted");
277        Self {
278            map_id,
279            entries: Vec::new(),
280            values: Vec::with_capacity(MAX_ACTIVE_CODES),
281            contexts: vec!["global".into()],
282            stack: Vec::with_capacity(MAX_CONTEXT_DEPTH),
283        }
284    }
285}
286impl ActionMap {
287    pub fn action(&mut self, bindings: Vec<Binding>) -> usize {
288        self.try_action(bindings)
289            .expect("valid actions within capacities")
290    }
291    pub fn try_action(&mut self, bindings: Vec<Binding>) -> Option<usize> {
292        self.insert(None, ActionKind::Axis, ContextId::GLOBAL, bindings)
293            .ok()
294    }
295    pub fn named_action(
296        &mut self,
297        name: &str,
298        kind: ActionKind,
299        context: ContextId,
300        bindings: Vec<Binding>,
301    ) -> Result<usize, InputError> {
302        if !valid_name(name) {
303            return Err(InputError::InvalidName);
304        }
305        if self.action_id(name).is_some() {
306            return Err(InputError::DuplicateName);
307        }
308        self.insert(Some(name.to_string()), kind, context, bindings)
309    }
310    /// Register a named action and return its ownership-checked handle.
311    ///
312    /// Names, bindings, capacity and contexts follow [`Self::named_action`]. A
313    /// failed registration leaves existing actions and handles unchanged.
314    ///
315    /// ```
316    /// use ferravex_play::input::{ActionKind, ActionMap, ContextId};
317    /// let mut input = ActionMap::default();
318    /// let jump = input.named_action_handle("jump", ActionKind::Button, ContextId::GLOBAL, vec![])?;
319    /// assert_eq!(input.action_handle("jump"), Some(jump));
320    /// # Ok::<(), ferravex_play::input::InputError>(())
321    /// ```
322    pub fn named_action_handle(
323        &mut self,
324        name: &str,
325        kind: ActionKind,
326        context: ContextId,
327        bindings: Vec<Binding>,
328    ) -> Result<ActionHandle, InputError> {
329        let index = self.named_action(name, kind, context, bindings)?;
330        Ok(ActionHandle {
331            map_id: self.map_id,
332            index,
333        })
334    }
335    fn insert(
336        &mut self,
337        name: Option<String>,
338        kind: ActionKind,
339        context: ContextId,
340        bindings: Vec<Binding>,
341    ) -> Result<usize, InputError> {
342        if self.entries.len() >= MAX_ACTIONS {
343            return Err(InputError::ActionCapacity);
344        }
345        if context.0 as usize >= self.contexts.len() {
346            return Err(InputError::InvalidContext);
347        }
348        validate_bindings(kind, &bindings)?;
349        let id = self.entries.len();
350        self.entries.push(Entry {
351            name,
352            kind,
353            context,
354            bindings: bindings.into_boxed_slice(),
355            state: Action::default(),
356            suppressed: false,
357        });
358        self.recompute();
359        Ok(id)
360    }
361    pub fn action_id(&self, name: &str) -> Option<usize> {
362        self.entries
363            .iter()
364            .position(|e| e.name.as_deref() == Some(name))
365    }
366    /// Resolve an exact registered name once; missing names return `None`.
367    ///
368    /// This lookup scans registered names. Subsequent [`Self::peek_handle`] and
369    /// [`Self::consume_tick_handle`] calls use constant-time validated indexing.
370    /// Resolution also works while the action's context is inactive. See
371    /// [`ActionHandle`] for a complete sampling example.
372    pub fn action_handle(&self, name: &str) -> Option<ActionHandle> {
373        self.action_id(name).and_then(|id| self.handle_from_id(id))
374    }
375    /// Convert an existing in-bounds index into a handle owned by this map.
376    ///
377    /// For migration of legacy/unnamed registrations. A raw index has no owner;
378    /// this cannot detect an index copied from another map. Pass an index from
379    /// this map, or prefer [`Self::action_handle`] for named lookup.
380    ///
381    /// ```
382    /// use ferravex_play::input::ActionMap;
383    /// let mut input = ActionMap::default();
384    /// let id = input.action(vec![]);
385    /// let handle = input.handle_from_id(id).unwrap();
386    /// assert_eq!(input.peek_handle(handle)?, input.peek(id));
387    /// assert!(input.handle_from_id(usize::MAX).is_none());
388    /// # Ok::<(), ferravex_play::input::InputError>(())
389    /// ```
390    pub fn handle_from_id(&self, id: usize) -> Option<ActionHandle> {
391        self.entries.get(id).map(|_| ActionHandle {
392            map_id: self.map_id,
393            index: id,
394        })
395    }
396    fn validate_handle(&self, handle: ActionHandle) -> Result<usize, InputError> {
397        if handle.map_id != self.map_id || handle.index >= self.entries.len() {
398            Err(InputError::InvalidHandle)
399        } else {
400            Ok(handle.index)
401        }
402    }
403    pub fn named_actions(&self) -> impl Iterator<Item = (usize, &str, ActionKind, ContextId)> {
404        self.entries
405            .iter()
406            .enumerate()
407            .filter_map(|(id, e)| e.name.as_deref().map(|name| (id, name, e.kind, e.context)))
408    }
409    pub fn bindings(&self, id: usize) -> Option<&[Binding]> {
410        self.entries.get(id).map(|e| e.bindings.as_ref())
411    }
412    /// Inspect bindings without allocating or consuming pending input.
413    ///
414    /// Stale/foreign handles return [`InputError::InvalidHandle`]. See
415    /// [`Self::try_rebind_handle`] for a usage example.
416    pub fn bindings_handle(&self, handle: ActionHandle) -> Result<&[Binding], InputError> {
417        let id = self.validate_handle(handle)?;
418        Ok(self.entries[id].bindings.as_ref())
419    }
420    /// Inspect metadata and current bindings using an ownership-checked handle.
421    ///
422    /// Stale or foreign handles return [`InputError::InvalidHandle`], even if
423    /// their index/name matches an action here. Inactive and unbound actions are
424    /// valid. This does not allocate, consume edges/motion or alter suppression.
425    /// Work is bounded by the context stack, not the number of actions.
426    ///
427    /// ```
428    /// use ferravex_play::input::{ActionKind, ActionMap, Binding, ContextId, InputCode};
429    /// let mut input = ActionMap::default();
430    /// let jump = input.named_action_handle("jump", ActionKind::Button, ContextId::GLOBAL, vec![])?;
431    /// assert!(input.action_descriptor(jump)?.bindings.is_empty());
432    /// input.try_rebind_handle(jump, vec![Binding::digital(InputCode::Key(74))])?;
433    /// assert_eq!(input.action_descriptor(jump)?.bindings[0].code, InputCode::Key(74));
434    /// # Ok::<(), ferravex_play::input::InputError>(())
435    /// ```
436    pub fn action_descriptor(
437        &self,
438        handle: ActionHandle,
439    ) -> Result<ActionDescriptor<'_>, InputError> {
440        let id = self.validate_handle(handle)?;
441        Ok(self.descriptor_at(id, self.active_mask()))
442    }
443    /// Enumerate all actions in registration order without allocating or consuming input.
444    ///
445    /// Includes unnamed, inactive and unbound actions, up to [`MAX_ACTIONS`]. Each
446    /// descriptor carries a handle owned by this map and a borrowed slice of its
447    /// validated bindings. Filter on [`ActionDescriptor::context_active`] for
448    /// context-aware hints, or keep inactive actions for a controls editor.
449    ///
450    /// ```
451    /// use ferravex_play::input::{ActionKind, ActionMap, Binding, ContextId, InputCode};
452    /// let mut input = ActionMap::default();
453    /// let jump = input.named_action_handle(
454    ///     "jump", ActionKind::Button, ContextId::GLOBAL,
455    ///     vec![Binding::digital(InputCode::Key(32))],
456    /// )?;
457    /// input.feed(InputCode::Key(32), 1.0);
458    /// for hint in input.action_descriptors().filter(|hint| hint.context_active) {
459    ///     assert_eq!(hint.handle, jump);
460    ///     for binding in hint.bindings {
461    ///         assert_eq!(binding.code, InputCode::Key(32));
462    ///     }
463    /// }
464    /// assert!(input.consume_tick_handle(jump)?.pressed); // Hints leave the edge queued.
465    /// # Ok::<(), ferravex_play::input::InputError>(())
466    /// ```
467    pub fn action_descriptors(
468        &self,
469    ) -> impl ExactSizeIterator<Item = ActionDescriptor<'_>> + DoubleEndedIterator + '_ {
470        let active = self.active_mask();
471        (0..self.entries.len()).map(move |id| self.descriptor_at(id, active))
472    }
473    fn descriptor_at(&self, id: usize, active: u16) -> ActionDescriptor<'_> {
474        let entry = &self.entries[id];
475        ActionDescriptor {
476            handle: ActionHandle {
477                map_id: self.map_id,
478                index: id,
479            },
480            name: entry.name.as_deref(),
481            kind: entry.kind,
482            context: entry.context,
483            context_name: &self.contexts[entry.context.0 as usize],
484            context_active: active & (1 << entry.context.0) != 0,
485            bindings: &entry.bindings,
486        }
487    }
488    pub fn create_context(&mut self, name: &str) -> Result<ContextId, InputError> {
489        if !valid_name(name) {
490            return Err(InputError::InvalidName);
491        }
492        if self.contexts.iter().any(|n| n == name) {
493            return Err(InputError::DuplicateName);
494        }
495        if self.contexts.len() >= MAX_CONTEXTS {
496            return Err(InputError::ContextCapacity);
497        }
498        let id = ContextId(self.contexts.len() as u8);
499        self.contexts.push(name.to_string());
500        Ok(id)
501    }
502    pub fn context(&self, name: &str) -> Option<ContextId> {
503        self.contexts
504            .iter()
505            .position(|n| n == name)
506            .map(|n| ContextId(n as u8))
507    }
508    pub fn push_context(&mut self, id: ContextId, mode: ContextMode) -> Result<(), InputError> {
509        if id == ContextId::GLOBAL
510            || id.0 as usize >= self.contexts.len()
511            || self.stack.iter().any(|v| v.0 == id)
512        {
513            return Err(InputError::InvalidContext);
514        }
515        if self.stack.len() >= MAX_CONTEXT_DEPTH {
516            return Err(InputError::ContextDepth);
517        }
518        let old = self.active_mask();
519        self.stack.push((id, mode));
520        self.transition(old);
521        Ok(())
522    }
523    pub fn pop_context(&mut self) -> Option<ContextId> {
524        let old = self.active_mask();
525        let id = self.stack.pop()?.0;
526        self.transition(old);
527        Some(id)
528    }
529    pub fn clear_contexts(&mut self) {
530        let old = self.active_mask();
531        self.stack.clear();
532        self.transition(old);
533    }
534    /// Replace the stack with one exclusive context, or clear gameplay contexts.
535    /// Repeating the active setting does not discard edges or suppress input.
536    pub fn set_context(&mut self, id: Option<ContextId>) -> Result<(), InputError> {
537        if id.is_some_and(|id| id == ContextId::GLOBAL || id.0 as usize >= self.contexts.len()) {
538            return Err(InputError::InvalidContext);
539        }
540        if id.is_none() && self.stack.is_empty()
541            || self.stack.len() == 1
542                && id == Some(self.stack[0].0)
543                && self.stack[0].1 == ContextMode::Exclusive
544        {
545            return Ok(());
546        }
547        let old = self.active_mask();
548        self.stack.clear();
549        if let Some(id) = id {
550            self.stack.push((id, ContextMode::Exclusive));
551        }
552        self.transition(old);
553        Ok(())
554    }
555    fn active_mask(&self) -> u16 {
556        let mut mask = 1;
557        for &(id, mode) in self.stack.iter().rev() {
558            mask |= 1 << id.0;
559            if mode == ContextMode::Exclusive {
560                break;
561            }
562        }
563        mask
564    }
565    fn transition(&mut self, old: u16) {
566        let new = self.active_mask();
567        for entry in &mut self.entries {
568            let was = old & (1 << entry.context.0) != 0;
569            let active = new & (1 << entry.context.0) != 0;
570            if was != active {
571                // UI/capture edges must never leak back into gameplay. A held
572                // button must go neutral before a newly activated context sees it.
573                entry.state.pressed = false;
574                entry.state.released = false;
575                if entry.kind == ActionKind::Delta {
576                    entry.state.value = 0.;
577                }
578                if active && entry.kind == ActionKind::Button {
579                    entry.suppressed = raw_value(entry, &self.values).abs() >= 0.5;
580                }
581            }
582        }
583        self.recompute();
584    }
585    pub fn rebind(&mut self, id: usize, bindings: Vec<Binding>) -> bool {
586        self.try_rebind(id, bindings).is_ok()
587    }
588    pub fn try_rebind(&mut self, id: usize, bindings: Vec<Binding>) -> Result<(), InputError> {
589        let entry = self.entries.get_mut(id).ok_or(InputError::InvalidHandle)?;
590        validate_bindings(entry.kind, &bindings)?;
591        entry.bindings = bindings.into_boxed_slice();
592        entry.state = Action::default();
593        entry.suppressed =
594            entry.kind == ActionKind::Button && raw_value(entry, &self.values).abs() >= 0.5;
595        self.recompute();
596        Ok(())
597    }
598    /// Rebind only if the handle belongs to this map and the bindings are valid.
599    ///
600    /// Failure leaves bindings and pending input unchanged. Success preserves
601    /// the handle and follows [`Self::try_rebind`]: pending input is reset, and
602    /// already held buttons must release before triggering the new binding.
603    ///
604    /// ```
605    /// use ferravex_play::input::{ActionKind, ActionMap, Binding, ContextId, InputCode};
606    /// let mut input = ActionMap::default();
607    /// let jump = input.named_action_handle("jump", ActionKind::Button, ContextId::GLOBAL, vec![])?;
608    /// input.try_rebind_handle(jump, vec![Binding::digital(InputCode::Key(32))])?;
609    /// assert_eq!(input.bindings_handle(jump)?[0].code, InputCode::Key(32));
610    /// # Ok::<(), ferravex_play::input::InputError>(())
611    /// ```
612    pub fn try_rebind_handle(
613        &mut self,
614        handle: ActionHandle,
615        bindings: Vec<Binding>,
616    ) -> Result<(), InputError> {
617        let id = self.validate_handle(handle)?;
618        self.try_rebind(id, bindings)
619    }
620    /// Held values normalize to [-1,1]. Relative codes delegate to feed_delta.
621    /// Unknown/overflowing/nonfinite physical data cannot grow the map without bound.
622    pub fn feed(&mut self, code: InputCode, value: f32) {
623        if !code.valid() {
624            return;
625        }
626        if code.is_delta() {
627            self.feed_delta(code, value);
628            return;
629        }
630        let value = if value.is_finite() {
631            value.clamp(-1., 1.)
632        } else {
633            0.
634        };
635        match self.values.binary_search_by_key(&code, |v| v.0) {
636            Ok(i) => {
637                if self.values[i].1 == value {
638                    return;
639                }
640                if value == 0. {
641                    self.values.remove(i);
642                } else {
643                    self.values[i].1 = value;
644                }
645            }
646            Err(i) => {
647                if value == 0. || self.values.len() >= MAX_ACTIVE_CODES {
648                    return;
649                }
650                self.values.insert(i, (code, value));
651            }
652        }
653        self.recompute();
654    }
655    /// Motion accumulates across render frames with no simulation ticks. Consuming
656    /// one delta action does not erase another action bound to the same source.
657    pub fn feed_delta(&mut self, code: InputCode, value: f32) {
658        if !code.valid() || !code.is_delta() || !value.is_finite() || value == 0. {
659            return;
660        }
661        let active = self.active_mask();
662        for entry in &mut self.entries {
663            if entry.kind != ActionKind::Delta || active & (1 << entry.context.0) == 0 {
664                continue;
665            }
666            let delta = entry
667                .bindings
668                .iter()
669                .filter(|b| b.code == code)
670                .map(|b| f64::from(b.scale) * f64::from(value))
671                .sum::<f64>();
672            let was = entry.state.value.abs() > 0.000001;
673            entry.state.value = (f64::from(entry.state.value) + delta).clamp(-1e6, 1e6) as f32;
674            let down = entry.state.value.abs() > 0.000001;
675            entry.state.pressed |= down && !was;
676            entry.state.released |= !down && was;
677        }
678    }
679    fn recompute(&mut self) {
680        let active = self.active_mask();
681        for entry in &mut self.entries {
682            if entry.kind == ActionKind::Delta {
683                continue;
684            }
685            let raw = raw_value(entry, &self.values);
686            if entry.suppressed && raw.abs() < 0.5 {
687                entry.suppressed = false;
688            }
689            let mut value = if active & (1 << entry.context.0) != 0 && !entry.suppressed {
690                raw
691            } else {
692                0.
693            };
694            if entry.kind == ActionKind::Button {
695                value = if value.abs() >= 0.5 {
696                    value.signum()
697                } else {
698                    0.
699                };
700            }
701            let down = value.abs() > 0.001;
702            let was = entry.state.value.abs() > 0.001;
703            entry.state.pressed |= down && !was;
704            entry.state.released |= !down && was;
705            entry.state.value = value;
706        }
707    }
708    pub fn peek(&self, id: usize) -> Action {
709        self.entries.get(id).map_or(Action::default(), |e| e.state)
710    }
711    /// Read a snapshot without clearing edges or accumulated motion.
712    ///
713    /// Stale/foreign handles return [`InputError::InvalidHandle`], distinct from
714    /// a valid neutral action. Context masking and held-button suppression are
715    /// identical to [`Self::peek`]; validity does not depend on context activity.
716    /// See [`ActionHandle`] for an example.
717    pub fn peek_handle(&self, handle: ActionHandle) -> Result<Action, InputError> {
718        let id = self.validate_handle(handle)?;
719        Ok(self.entries[id].state)
720    }
721    pub fn consume_tick(&mut self, id: usize) -> Action {
722        let Some(entry) = self.entries.get_mut(id) else {
723            return Action::default();
724        };
725        let state = entry.state;
726        entry.state.pressed = false;
727        entry.state.released = false;
728        if entry.kind == ActionKind::Delta {
729            entry.state.value = 0.;
730        }
731        state
732    }
733    /// Sample one action for a simulation tick, clearing its queued edges.
734    ///
735    /// Held axis/button values persist. Delta values are cleared. A press and
736    /// release between ticks are both returned once, including through copied
737    /// handles or mixed legacy/typed access: consumption is per action, not per
738    /// handle. Other actions bound to the same source retain their own input.
739    /// Stale/foreign handles return [`InputError::InvalidHandle`] without
740    /// consuming anything. See [`ActionHandle`] for an example.
741    pub fn consume_tick_handle(&mut self, handle: ActionHandle) -> Result<Action, InputError> {
742        let id = self.validate_handle(handle)?;
743        Ok(self.consume_tick(id))
744    }
745    /// Snapshot a fixed group without consuming edges or relative motion.
746    ///
747    /// Duplicate handles receive identical snapshots. All handles must belong
748    /// to this map, including inactive/unbound actions. At most [`MAX_ACTIONS`]
749    /// handles (counting duplicates) are accepted; an empty group is valid.
750    /// No allocation occurs. See [`Self::peek_handles_into`] for caller storage.
751    ///
752    /// ```
753    /// use ferravex_play::input::{ActionMap, Binding, InputCode};
754    /// let mut input = ActionMap::default();
755    /// let id = input.action(vec![Binding::digital(InputCode::Key(32))]);
756    /// let jump = input.handle_from_id(id).unwrap();
757    /// input.feed(InputCode::Key(32), 1.0);
758    /// let [a, b] = input.peek_handles([jump, jump])?;
759    /// assert_eq!(a, b);
760    /// assert!(input.consume_tick_handle(jump)?.pressed);
761    /// # Ok::<(), Box<dyn std::error::Error>>(())
762    /// ```
763    pub fn peek_handles<const N: usize>(
764        &self,
765        handles: [ActionHandle; N],
766    ) -> Result<[Action; N], ActionSnapshotError> {
767        let mut output = [Action::default(); N];
768        self.peek_handles_into(&handles, &mut output)?;
769        Ok(output)
770    }
771    /// Copy snapshots into `output[..handles.len()]`, preserving its tail.
772    ///
773    /// Prevalidates the count, output capacity and **every** handle before any
774    /// output write. On error the entire output and all input remain unchanged.
775    /// Duplicates, context masking and held suppression follow [`Self::peek_handles`].
776    /// Work is O(handle count), bounded by [`MAX_ACTIONS`], without allocation.
777    /// A larger output buffer is allowed, including for an empty request.
778    ///
779    /// ```
780    /// use ferravex_play::input::{Action, ActionMap};
781    /// let mut input = ActionMap::default();
782    /// let id = input.action(vec![]);
783    /// let handle = input.handle_from_id(id).unwrap();
784    /// let sentinel = Action { value: 0.5, pressed: true, released: true };
785    /// let mut output = [sentinel; 2];
786    /// input.peek_handles_into(&[handle], &mut output)?;
787    /// assert_eq!(output, [Action::default(), sentinel]);
788    /// # Ok::<(), ferravex_play::input::ActionSnapshotError>(())
789    /// ```
790    pub fn peek_handles_into(
791        &self,
792        handles: &[ActionHandle],
793        output: &mut [Action],
794    ) -> Result<(), ActionSnapshotError> {
795        self.validate_snapshot(handles, output.len())?;
796        for (handle, slot) in handles.iter().zip(output) {
797            *slot = self.entries[handle.index].state;
798        }
799        Ok(())
800    }
801    /// Capture a fixed group for one **executed** simulation tick.
802    ///
803    /// Like renderer `PlayerInput::take_tick`, every duplicate receives the same
804    /// pre-consumption snapshot. Only requested actions are consumed; held
805    /// axis/button values persist while pressed/released edges and delta values
806    /// clear. Other actions, even on the same source, retain their own input.
807    /// Edges coalesce into flags, not a tap count. Context/focus/suppression
808    /// policy is unchanged from [`Self::consume_tick_handle`].
809    ///
810    /// The count (at most [`MAX_ACTIONS`], including duplicates) and every handle
811    /// are validated before consuming anything. Empty groups succeed. There is
812    /// no allocation or host/time polling. Share the returned array across tick
813    /// systems; consume again only for the next executed tick. Zero-tick frames
814    /// must only feed/preview input, so pending taps and motion survive.
815    ///
816    /// This runnable host-loop recipe injects two zero-tick frames followed by a
817    /// catch-up batch. Issued steps may exceed executed updates if gameplay ends;
818    /// consumption belongs after the decision to execute each update.
819    ///
820    /// ```
821    /// use ferravex_play::input::{ActionKind, ActionMap, Binding, ContextId, InputCode};
822    /// let mut input = ActionMap::default();
823    /// let jump = input.named_action_handle("jump", ActionKind::Button,
824    ///     ContextId::GLOBAL, vec![Binding::digital(InputCode::Key(32))])?;
825    /// let pan = input.named_action_handle("pan", ActionKind::Delta,
826    ///     ContextId::GLOBAL, vec![Binding::digital(InputCode::MouseDelta(0))])?;
827    /// let mut executed = 0;
828    /// let mut requests = 0;
829    /// let mut motion = 0.0;
830    /// let mut playing = true;
831    /// // (host button level, relative motion, issued fixed steps)
832    /// for (level, delta, issued) in [(1.0, 3.0, 0), (0.0, 5.0, 0), (0.0, 0.0, 3)] {
833    ///     input.feed(InputCode::Key(32), level);
834    ///     input.feed_delta(InputCode::MouseDelta(0), delta);
835    ///     for _ in 0..issued {
836    ///         if !playing { break; }
837    ///         let [jump, pan] = input.consume_tick_handles([jump, pan])?;
838    ///         // Share these values with rules/animation; emit feedback only if accepted.
839    ///         requests += u32::from(jump.pressed);
840    ///         motion += pan.value;
841    ///         executed += 1;
842    ///         if executed == 2 { playing = false; }
843    ///     }
844    /// }
845    /// assert_eq!((executed, requests, motion), (2, 1, 8.0));
846    /// # Ok::<(), Box<dyn std::error::Error>>(())
847    /// ```
848    pub fn consume_tick_handles<const N: usize>(
849        &mut self,
850        handles: [ActionHandle; N],
851    ) -> Result<[Action; N], ActionSnapshotError> {
852        let mut output = [Action::default(); N];
853        self.consume_tick_handles_into(&handles, &mut output)?;
854        Ok(output)
855    }
856    /// Capture a tick group in caller storage, preserving the unused output tail.
857    ///
858    /// The complete count, output capacity and every handle are checked before
859    /// **any** input/output mutation. On error nothing changes. On success all
860    /// snapshots are copied before clearing any input, so duplicates match
861    /// [`Self::consume_tick_handles`]. O(handle count) work and no allocation.
862    ///
863    /// ```
864    /// use ferravex_play::input::{Action, ActionMap, Binding, InputCode};
865    /// let mut input = ActionMap::default();
866    /// let id = input.action(vec![Binding::digital(InputCode::Key(32))]);
867    /// let jump = input.handle_from_id(id).unwrap();
868    /// input.feed(InputCode::Key(32), 1.0);
869    /// input.feed(InputCode::Key(32), 0.0);
870    /// let mut output = [Action::default(); 2];
871    /// input.consume_tick_handles_into(&[jump, jump], &mut output)?;
872    /// assert_eq!(output[0], output[1]);
873    /// assert!(output[0].pressed && output[0].released);
874    /// assert_eq!(input.peek_handle(jump)?, Action::default());
875    /// # Ok::<(), Box<dyn std::error::Error>>(())
876    /// ```
877    pub fn consume_tick_handles_into(
878        &mut self,
879        handles: &[ActionHandle],
880        output: &mut [Action],
881    ) -> Result<(), ActionSnapshotError> {
882        self.peek_handles_into(handles, output)?;
883        // Copy every state before clearing any. Re-clearing a duplicate is
884        // idempotent, avoiding a search, scratch allocation or quadratic work.
885        for handle in handles {
886            self.consume_tick(handle.index);
887        }
888        Ok(())
889    }
890    fn validate_snapshot(
891        &self,
892        handles: &[ActionHandle],
893        output_len: usize,
894    ) -> Result<(), ActionSnapshotError> {
895        if handles.len() > MAX_ACTIONS {
896            return Err(ActionSnapshotError::TooManyHandles {
897                count: handles.len(),
898            });
899        }
900        if output_len < handles.len() {
901            return Err(ActionSnapshotError::OutputTooSmall {
902                required: handles.len(),
903                available: output_len,
904            });
905        }
906        for (index, &handle) in handles.iter().enumerate() {
907            self.validate_handle(handle)
908                .map_err(|_| ActionSnapshotError::InvalidHandle { index })?;
909        }
910        Ok(())
911    }
912    pub fn physical_value(&self, code: InputCode) -> f32 {
913        self.values
914            .binary_search_by_key(&code, |v| v.0)
915            .ok()
916            .map_or(0., |i| self.values[i].1)
917    }
918    pub fn active_codes(&self) -> usize {
919        self.values.len()
920    }
921    /// Discard queued edges/motion and require already held buttons to release.
922    /// Axes can resume at their current level without a synthetic press.
923    pub fn suppress_held(&mut self) {
924        for entry in &mut self.entries {
925            entry.state.pressed = false;
926            entry.state.released = false;
927            if entry.kind == ActionKind::Delta {
928                entry.state.value = 0.;
929            }
930            if entry.kind == ActionKind::Button {
931                entry.suppressed = raw_value(entry, &self.values).abs() >= 0.5;
932            }
933        }
934        self.recompute();
935        for entry in &mut self.entries {
936            entry.state.pressed = false;
937            entry.state.released = false;
938        }
939    }
940    /// Neutralize held values and discard queued presses/motion on focus loss.
941    pub fn lose_focus(&mut self) {
942        self.values.clear();
943        for e in &mut self.entries {
944            let released = e.kind != ActionKind::Delta && e.state.value.abs() > 0.001;
945            e.state = Action {
946                value: 0.,
947                pressed: false,
948                released,
949            };
950            e.suppressed = false;
951        }
952    }
953}
954#[cfg(test)]
955#[test]
956fn journey400_291_corrupt_late_index_rejects_without_input_or_output_mutation() {
957    let mut map = ActionMap::default();
958    let id = map.action(vec![Binding::digital(InputCode::Key(1))]);
959    let handle = map.handle_from_id(id).unwrap();
960    // Only internal tests can construct an in-map, out-of-bounds handle.
961    let corrupt = ActionHandle {
962        map_id: map.map_id,
963        index: usize::MAX,
964    };
965    map.feed(InputCode::Key(1), 1.);
966    let before = map.peek(id);
967    let mut output = [Action::default(); 3];
968    let expected = Err(ActionSnapshotError::InvalidHandle { index: 2 });
969    assert_eq!(
970        map.peek_handles_into(&[handle, handle, corrupt], &mut output),
971        expected
972    );
973    assert_eq!(output, [Action::default(); 3]);
974    assert_eq!(
975        map.consume_tick_handles_into(&[handle, handle, corrupt], &mut output),
976        expected
977    );
978    assert_eq!(output, [Action::default(); 3]);
979    assert_eq!(map.peek(id), before);
980}
981
982fn validate_bindings(kind: ActionKind, bindings: &[Binding]) -> Result<(), InputError> {
983    if bindings.len() > MAX_BINDINGS {
984        return Err(InputError::BindingCapacity);
985    }
986    if bindings
987        .iter()
988        .any(|b| !b.valid() || b.code.is_delta() != (kind == ActionKind::Delta))
989    {
990        return Err(InputError::InvalidBinding);
991    }
992    Ok(())
993}
994fn raw_value(entry: &Entry, values: &[(InputCode, f32)]) -> f32 {
995    entry
996        .bindings
997        .iter()
998        .map(|b| {
999            let raw = values
1000                .binary_search_by_key(&b.code, |v| v.0)
1001                .ok()
1002                .map_or(0., |i| f64::from(values[i].1));
1003            let dead = f64::from(b.deadzone);
1004            if raw.abs() <= dead {
1005                0.
1006            } else {
1007                raw.signum() * (raw.abs() - dead) / (1. - dead) * f64::from(b.scale)
1008            }
1009        })
1010        .sum::<f64>()
1011        .clamp(-1., 1.) as f32
1012}
1013
1014#[cfg(test)]
1015mod journey200_051 {
1016    use super::*;
1017
1018    #[test]
1019    fn descriptors_borrow_all_metadata_and_preserve_binding_order() {
1020        let mut map = ActionMap::default();
1021        assert_eq!(map.action_descriptors().len(), 0);
1022        assert_eq!(map.action_descriptors().next_back(), None);
1023        let game = map.create_context("game").unwrap();
1024        let axis_bindings = vec![
1025            Binding {
1026                code: InputCode::PadAxis(0),
1027                scale: -2.,
1028                deadzone: 0.25,
1029            },
1030            Binding::digital(InputCode::Key(65)),
1031            Binding::digital(InputCode::Key(65)),
1032            Binding {
1033                code: InputCode::Touch(63),
1034                scale: 0.,
1035                deadzone: 0.,
1036            },
1037        ];
1038        let legacy = map.action(axis_bindings.clone());
1039        let jump = map
1040            .named_action_handle(
1041                "jump",
1042                ActionKind::Button,
1043                game,
1044                vec![
1045                    Binding::digital(InputCode::Mouse(1)),
1046                    Binding::digital(InputCode::PadButton(0)),
1047                ],
1048            )
1049            .unwrap();
1050        let look = map
1051            .named_action_handle(
1052                "look",
1053                ActionKind::Delta,
1054                ContextId::GLOBAL,
1055                vec![
1056                    Binding::digital(InputCode::MouseDelta(0)),
1057                    Binding::digital(InputCode::TouchDelta(1)),
1058                    Binding::digital(InputCode::Wheel(1)),
1059                ],
1060            )
1061            .unwrap();
1062        let unbound = map
1063            .named_action_handle("unbound", ActionKind::Button, ContextId::GLOBAL, vec![])
1064            .unwrap();
1065
1066        let mut descriptors = map.action_descriptors();
1067        assert_eq!(descriptors.len(), 4);
1068        let axis = descriptors.next().unwrap();
1069        assert_eq!(axis.handle, map.handle_from_id(legacy).unwrap());
1070        assert_eq!(axis.name, None);
1071        assert_eq!(axis.kind, ActionKind::Axis);
1072        assert_eq!(axis.context, ContextId::GLOBAL);
1073        assert_eq!(axis.context_name, "global");
1074        assert!(axis.context_active);
1075        assert_eq!(axis.bindings, axis_bindings);
1076        assert!(std::ptr::eq(axis.bindings, map.bindings(legacy).unwrap()));
1077
1078        let last = descriptors.next_back().unwrap();
1079        assert_eq!(last.handle, unbound);
1080        assert!(last.bindings.is_empty());
1081        assert!(last.context_active);
1082        assert_eq!(descriptors.len(), 2);
1083        let button = descriptors.next().unwrap();
1084        assert_eq!(button, map.action_descriptor(jump).unwrap());
1085        assert_eq!(button.name, Some("jump"));
1086        assert_eq!(button.kind, ActionKind::Button);
1087        assert_eq!(button.context, game);
1088        assert_eq!(button.context_name, "game");
1089        assert!(!button.context_active);
1090        assert!(std::ptr::eq(
1091            button.bindings,
1092            map.bindings_handle(jump).unwrap()
1093        ));
1094        let delta = descriptors.next().unwrap();
1095        assert_eq!(delta.handle, look);
1096        assert_eq!(delta.kind, ActionKind::Delta);
1097        assert_eq!(delta.bindings, map.bindings_handle(look).unwrap());
1098        assert_eq!(descriptors.len(), 0);
1099        assert_eq!(descriptors.next(), None);
1100    }
1101
1102    #[test]
1103    fn descriptor_lookup_rejects_foreign_stale_and_out_of_bounds_handles() {
1104        let mut original = ActionMap::default();
1105        let original_id = original.action(vec![Binding::digital(InputCode::Key(32))]);
1106        let old = original.action_descriptors().next().unwrap().handle;
1107        let mut replacement = ActionMap::default();
1108        let replacement_id = replacement.action(vec![Binding::digital(InputCode::Key(32))]);
1109        assert_eq!(original_id, replacement_id);
1110        let current = replacement.action_descriptors().next().unwrap().handle;
1111        replacement.feed(InputCode::Key(32), 1.);
1112        assert_eq!(
1113            replacement.action_descriptor(old),
1114            Err(InputError::InvalidHandle)
1115        );
1116        assert_eq!(
1117            original.action_descriptor(current),
1118            Err(InputError::InvalidHandle)
1119        );
1120        original = replacement;
1121        assert_eq!(
1122            original.action_descriptor(old),
1123            Err(InputError::InvalidHandle)
1124        );
1125        let mut moved = Box::new(original);
1126        moved.action(vec![]);
1127        assert_eq!(moved.action_descriptor(current).unwrap().handle, current);
1128        for index in [2, usize::MAX] {
1129            let invalid = ActionHandle {
1130                map_id: moved.map_id,
1131                index,
1132            };
1133            assert_eq!(
1134                moved.action_descriptor(invalid),
1135                Err(InputError::InvalidHandle)
1136            );
1137        }
1138        assert!(moved.consume_tick_handle(current).unwrap().pressed);
1139    }
1140
1141    #[test]
1142    fn descriptors_follow_context_stack_without_changing_held_suppression() {
1143        let mut map = ActionMap::default();
1144        let game = map.create_context("game").unwrap();
1145        let hud = map.create_context("hud").unwrap();
1146        let menu = map.create_context("menu").unwrap();
1147        let tooltip = map.create_context("tooltip").unwrap();
1148        for (name, context) in [
1149            ("pause", ContextId::GLOBAL),
1150            ("jump", game),
1151            ("hint", hud),
1152            ("accept", menu),
1153            ("dismiss", tooltip),
1154        ] {
1155            map.named_action_handle(
1156                name,
1157                ActionKind::Button,
1158                context,
1159                vec![Binding::digital(InputCode::Key(32))],
1160            )
1161            .unwrap();
1162        }
1163        let active_names = |map: &ActionMap| {
1164            map.action_descriptors()
1165                .filter(|d| d.context_active)
1166                .map(|d| d.name.unwrap().to_owned())
1167                .collect::<Vec<_>>()
1168        };
1169        let jump = map.action_handle("jump").unwrap();
1170        assert_eq!(active_names(&map), ["pause"]);
1171        map.feed(InputCode::Key(32), 1.);
1172        map.push_context(game, ContextMode::Exclusive).unwrap();
1173        assert_eq!(active_names(&map), ["pause", "jump"]);
1174        assert!(map.action_descriptor(jump).unwrap().context_active);
1175        assert_eq!(map.consume_tick_handle(jump).unwrap(), Action::default());
1176        map.push_context(hud, ContextMode::Passthrough).unwrap();
1177        assert_eq!(active_names(&map), ["pause", "jump", "hint"]);
1178        map.push_context(menu, ContextMode::Exclusive).unwrap();
1179        assert_eq!(active_names(&map), ["pause", "accept"]);
1180        map.push_context(tooltip, ContextMode::Passthrough).unwrap();
1181        assert_eq!(active_names(&map), ["pause", "accept", "dismiss"]);
1182        map.pop_context();
1183        map.pop_context();
1184        assert_eq!(active_names(&map), ["pause", "jump", "hint"]);
1185        assert_eq!(map.consume_tick_handle(jump).unwrap(), Action::default());
1186        map.feed(InputCode::Key(32), 0.);
1187        map.feed(InputCode::Key(32), 1.);
1188        let pending = map.peek_handle(jump).unwrap();
1189        assert!(pending.pressed);
1190        assert_eq!(active_names(&map), ["pause", "jump", "hint"]);
1191        assert_eq!(map.consume_tick_handle(jump).unwrap(), pending);
1192        map.suppress_held();
1193        assert_eq!(active_names(&map), ["pause", "jump", "hint"]);
1194        assert_eq!(map.consume_tick_handle(jump).unwrap(), Action::default());
1195        map.lose_focus();
1196        assert_eq!(active_names(&map), ["pause", "jump", "hint"]);
1197        map.clear_contexts();
1198        assert_eq!(active_names(&map), ["pause"]);
1199        map.set_context(Some(menu)).unwrap();
1200        assert_eq!(active_names(&map), ["pause", "accept"]);
1201    }
1202
1203    #[test]
1204    fn hint_reads_leave_zero_tick_taps_and_accumulated_motion_for_one_tick() {
1205        let mut map = ActionMap::default();
1206        let jump = map
1207            .named_action_handle(
1208                "jump",
1209                ActionKind::Button,
1210                ContextId::GLOBAL,
1211                vec![Binding::digital(InputCode::Key(32))],
1212            )
1213            .unwrap();
1214        let look = map
1215            .named_action_handle(
1216                "look",
1217                ActionKind::Delta,
1218                ContextId::GLOBAL,
1219                vec![Binding::digital(InputCode::MouseDelta(0))],
1220            )
1221            .unwrap();
1222        map.feed(InputCode::Key(32), 1.);
1223        map.feed(InputCode::Key(32), 0.);
1224        for motion in [3., 5.] {
1225            map.feed_delta(InputCode::MouseDelta(0), motion);
1226            for hint in map.action_descriptors() {
1227                assert_eq!(map.action_descriptor(hint.handle).unwrap(), hint);
1228            }
1229        }
1230        let tap = Action {
1231            value: 0.,
1232            pressed: true,
1233            released: true,
1234        };
1235        assert_eq!(map.consume_tick_handle(jump).unwrap(), tap);
1236        let delta = map.consume_tick_handle(look).unwrap();
1237        assert_eq!(delta.value, 8.);
1238        assert!(delta.pressed);
1239        assert_eq!(map.consume_tick_handle(jump).unwrap(), Action::default());
1240        assert_eq!(map.consume_tick_handle(look).unwrap(), Action::default());
1241    }
1242
1243    #[test]
1244    fn descriptors_track_rebinding_and_config_without_changing_identity() {
1245        let mut map = ActionMap::default();
1246        let original = Binding::digital(InputCode::Key(32));
1247        let jump = map
1248            .named_action_handle(
1249                "jump",
1250                ActionKind::Button,
1251                ContextId::GLOBAL,
1252                vec![original],
1253            )
1254            .unwrap();
1255        let saved = map.encode_config(ControlSettings::default()).unwrap();
1256        let remapped = [
1257            Binding::digital(InputCode::PadButton(0)),
1258            Binding::digital(InputCode::Key(74)),
1259        ];
1260        map.try_rebind_handle(jump, remapped.to_vec()).unwrap();
1261        assert_eq!(map.action_descriptor(jump).unwrap().bindings, remapped);
1262        map.feed(InputCode::Key(74), 1.);
1263        let pending = map.peek_handle(jump).unwrap();
1264        for (bindings, error) in [
1265            (
1266                vec![Binding::digital(InputCode::Key(0))],
1267                InputError::InvalidBinding,
1268            ),
1269            (
1270                vec![Binding {
1271                    scale: f32::NAN,
1272                    ..original
1273                }],
1274                InputError::InvalidBinding,
1275            ),
1276            (
1277                vec![Binding::digital(InputCode::MouseDelta(0))],
1278                InputError::InvalidBinding,
1279            ),
1280            (
1281                vec![original; MAX_BINDINGS + 1],
1282                InputError::BindingCapacity,
1283            ),
1284        ] {
1285            assert_eq!(map.try_rebind_handle(jump, bindings), Err(error));
1286            let hint = map.action_descriptor(jump).unwrap();
1287            assert_eq!(hint.handle, jump);
1288            assert_eq!(hint.bindings, remapped);
1289            assert_eq!(map.peek_handle(jump).unwrap(), pending);
1290        }
1291        assert!(map.apply_config(b"invalid").is_err());
1292        assert_eq!(map.action_descriptor(jump).unwrap().bindings, remapped);
1293        assert_eq!(map.peek_handle(jump).unwrap(), pending);
1294        map.feed(InputCode::Key(32), 1.);
1295        map.apply_config(&saved).unwrap();
1296        assert_eq!(map.action_handle("jump"), Some(jump));
1297        assert_eq!(map.action_descriptor(jump).unwrap().bindings, &[original]);
1298        assert_eq!(map.consume_tick_handle(jump).unwrap(), Action::default());
1299        map.feed(InputCode::Key(32), 0.);
1300        map.feed(InputCode::Key(32), 1.);
1301        assert!(map.action_descriptor(jump).unwrap().context_active);
1302        assert!(map.consume_tick_handle(jump).unwrap().pressed);
1303        map.try_rebind_handle(jump, vec![]).unwrap();
1304        assert!(map.action_descriptor(jump).unwrap().bindings.is_empty());
1305    }
1306
1307    #[test]
1308    fn enumeration_observes_existing_action_binding_and_context_bounds() {
1309        let mut map = ActionMap::default();
1310        let mut context = ContextId::GLOBAL;
1311        for i in 1..MAX_CONTEXTS {
1312            context = map.create_context(&format!("context_{i}")).unwrap();
1313        }
1314        let bindings = vec![Binding::digital(InputCode::Key(32)); MAX_BINDINGS];
1315        for i in 0..MAX_ACTIONS {
1316            map.named_action_handle(
1317                &format!("action_{i}"),
1318                ActionKind::Button,
1319                context,
1320                bindings.clone(),
1321            )
1322            .unwrap();
1323        }
1324        assert_eq!(
1325            map.named_action_handle("overflow", ActionKind::Button, context, vec![]),
1326            Err(InputError::ActionCapacity)
1327        );
1328        assert_eq!(map.action_descriptors().len(), MAX_ACTIONS);
1329        assert!(map.action_descriptors().all(|d| !d.context_active));
1330        map.set_context(Some(context)).unwrap();
1331        for (i, descriptor) in map.action_descriptors().enumerate() {
1332            assert_eq!(descriptor.name, Some(format!("action_{i}").as_str()));
1333            assert_eq!(descriptor.handle, map.handle_from_id(i).unwrap());
1334            assert!(descriptor.context_active);
1335            assert_eq!(descriptor.bindings.len(), MAX_BINDINGS);
1336            assert_eq!(descriptor.bindings, bindings);
1337        }
1338    }
1339}