ferravex_play/input/
config.rs

1//! Versioned controls only. Checksums detect accidental corruption; hosts own storage.
2use super::*;
3use ferravex_math::Vec2;
4pub const MAX_CONFIG_BYTES: usize = 256 * 1024;
5#[derive(Clone, Copy, Debug, PartialEq)]
6pub struct ControlSettings {
7    /// Radians per normalized viewport-width/height mouse delta.
8    pub mouse_sensitivity: f32,
9    /// Radians per logical display pixel for a touch-look region.
10    pub touch_sensitivity: f32,
11    /// Radians/second for a fully deflected right stick.
12    pub pad_look: Vec2,
13    pub pad_deadzone: f32,
14    pub pad_curve: f32,
15    pub invert_y: bool,
16    pub gamepad: u8,
17}
18impl Default for ControlSettings {
19    fn default() -> Self {
20        Self {
21            mouse_sensitivity: 1.9,
22            touch_sensitivity: 0.004,
23            pad_look: Vec2::new(2.5, 2.),
24            pad_deadzone: 0.18,
25            pad_curve: 1.,
26            invert_y: false,
27            gamepad: 0,
28        }
29    }
30}
31impl ControlSettings {
32    pub fn valid(self) -> bool {
33        self.mouse_sensitivity.is_finite()
34            && (0.01..=20.).contains(&self.mouse_sensitivity)
35            && self.touch_sensitivity.is_finite()
36            && (0.00005..=0.1).contains(&self.touch_sensitivity)
37            && self.pad_look.is_finite()
38            && self.pad_look.min_element() >= 0.
39            && self.pad_look.max_element() <= 20.
40            && self.pad_deadzone.is_finite()
41            && (0. ..=0.95).contains(&self.pad_deadzone)
42            && self.pad_curve.is_finite()
43            && (0.25..=4.).contains(&self.pad_curve)
44            && self.gamepad < 4
45    }
46    /// Radial response preserves direction and bounds diagonals to the unit disk.
47    pub fn stick(self, raw: Vec2) -> Vec2 {
48        if !self.valid() || !raw.is_finite() {
49            return Vec2::ZERO;
50        }
51        let raw = raw.clamp(Vec2::splat(-1.), Vec2::ONE);
52        let length = raw.length();
53        if length <= self.pad_deadzone || length < 1e-8 {
54            return Vec2::ZERO;
55        }
56        raw / length
57            * ((length.min(1.) - self.pad_deadzone) / (1. - self.pad_deadzone)).powf(self.pad_curve)
58    }
59}
60#[derive(Clone, Debug, PartialEq)]
61pub struct SavedAction {
62    pub name: String,
63    pub bindings: Vec<Binding>,
64}
65#[derive(Clone, Debug, PartialEq)]
66pub struct DecodedConfig {
67    pub settings: ControlSettings,
68    pub actions: Vec<SavedAction>,
69}
70#[derive(Clone, Copy, Debug, PartialEq)]
71pub struct AppliedConfig {
72    pub settings: ControlSettings,
73    pub matched: usize,
74    pub unknown: usize,
75}
76
77/// Maximum number of shared-source pairs retained by [`ActionMap::validate_config`].
78pub const MAX_CONFIG_CONFLICTS: usize = 256;
79
80/// A binding's location in a proposed configuration, including host-owned context.
81///
82/// IDs are local to the inspected map; names are stable registration names.
83/// `binding_index` addresses imported bindings for a matched action, or retained
84/// live bindings for an omitted/unnamed action. See [`ActionMap::validate_config`].
85#[derive(Clone, Debug, PartialEq, Eq)]
86pub struct ConfigBinding {
87    pub action_id: usize,
88    pub action_name: Option<String>,
89    pub action_kind: ActionKind,
90    pub context: ContextId,
91    pub context_name: String,
92    pub binding_index: usize,
93}
94
95/// Two nonzero-scale bindings using the same source in currently active contexts.
96///
97/// This includes duplicate bindings within one action. Different scales and
98/// deadzones still share a source; intentional sharing can use the permissive
99/// [`ActionMap::apply_config`]. See [`ActionMap::validate_config`] for an example.
100#[derive(Clone, Debug, PartialEq, Eq)]
101pub struct BindingConflict {
102    pub code: InputCode,
103    pub first: ConfigBinding,
104    pub second: ConfigBinding,
105}
106
107/// Non-mutating preview of a valid file merged with this host's registrations.
108///
109/// Reports at most [`MAX_CONFIG_CONFLICTS`] pairs in source-code, action-ID, then
110/// binding-index order. `conflicts_truncated` means additional pairs exist, not
111/// that validation of the file was skipped. See [`ActionMap::validate_config`].
112#[derive(Clone, Debug, PartialEq)]
113pub struct ConfigValidation {
114    pub applied: AppliedConfig,
115    /// Retired/unrecognized names, in file order; their bindings are ignored.
116    pub unknown_actions: Vec<String>,
117    pub conflicts: Vec<BindingConflict>,
118    pub conflicts_truncated: bool,
119}
120
121/// A config decoding, host compatibility, or strict-import rejection.
122///
123/// [`ActionMap::validate_config`] returns conflicts in a successful preview;
124/// only [`ActionMap::apply_config_checked`] returns `Conflicts`. The boxed report
125/// bounds the size of this error while preserving diagnostics for the caller.
126#[derive(Clone, Debug, PartialEq)]
127pub enum ConfigError {
128    /// The existing decoder rejected the file, before host matching.
129    Input(InputError),
130    /// A decoded binding uses a delta source for a held action, or vice versa.
131    IncompatibleBinding(ConfigBinding),
132    /// Strict import rejected shared sources in the current active contexts.
133    Conflicts(Box<ConfigValidation>),
134}
135impl std::fmt::Display for ConfigError {
136    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137        match self {
138            Self::Input(error) => write!(f, "{error}"),
139            Self::IncompatibleBinding(binding) => write!(
140                f,
141                "input config: binding {} of action {:?} (id {}, {:?}) in context {:?} is incompatible",
142                binding.binding_index,
143                binding.action_name,
144                binding.action_id,
145                binding.action_kind,
146                binding.context_name,
147            ),
148            Self::Conflicts(report) => write!(
149                f,
150                "input config: {}{} active binding conflicts",
151                report.conflicts.len(),
152                if report.conflicts_truncated { "+" } else { "" },
153            ),
154        }
155    }
156}
157impl std::error::Error for ConfigError {
158    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
159        match self {
160            Self::Input(error) => Some(error),
161            _ => None,
162        }
163    }
164}
165fn checksum(bytes: &[u8]) -> u32 {
166    bytes.iter().fold(0x811c9dc5_u32, |h, b| {
167        (h ^ u32::from(*b)).wrapping_mul(0x01000193)
168    })
169}
170fn code_parts(code: InputCode) -> (u8, u16) {
171    match code {
172        InputCode::Key(n) => (0, n),
173        InputCode::Mouse(n) => (1, n as u16),
174        InputCode::PadButton(n) => (2, n as u16),
175        InputCode::PadAxis(n) => (3, n as u16),
176        InputCode::Touch(n) => (4, n as u16),
177        InputCode::MouseDelta(n) => (5, n as u16),
178        InputCode::TouchDelta(n) => (6, n as u16),
179        InputCode::Wheel(n) => (7, n as u16),
180    }
181}
182fn parse_code(tag: u8, n: u16) -> Result<InputCode, InputError> {
183    if tag != 0 && n > u8::MAX as u16 {
184        return Err(InputError::InvalidConfig);
185    }
186    let code = match tag {
187        0 => InputCode::Key(n),
188        1 => InputCode::Mouse(n as u8),
189        2 => InputCode::PadButton(n as u8),
190        3 => InputCode::PadAxis(n as u8),
191        4 => InputCode::Touch(n as u8),
192        5 => InputCode::MouseDelta(n as u8),
193        6 => InputCode::TouchDelta(n as u8),
194        7 => InputCode::Wheel(n as u8),
195        _ => return Err(InputError::InvalidConfig),
196    };
197    if code.valid() {
198        Ok(code)
199    } else {
200        Err(InputError::InvalidConfig)
201    }
202}
203impl ActionMap {
204    /// Save named mappings by stable action name; host registration order can change.
205    pub fn encode_config(&self, settings: ControlSettings) -> Result<Vec<u8>, InputError> {
206        if !settings.valid() {
207            return Err(InputError::InvalidConfig);
208        }
209        let count = self.entries.iter().filter(|e| e.name.is_some()).count();
210        let mut bytes = Vec::new();
211        bytes.extend_from_slice(b"FXIN");
212        bytes.extend_from_slice(&1_u16.to_le_bytes());
213        bytes.extend_from_slice(&(count as u16).to_le_bytes());
214        for v in [
215            settings.mouse_sensitivity,
216            settings.touch_sensitivity,
217            settings.pad_look.x,
218            settings.pad_look.y,
219            settings.pad_deadzone,
220            settings.pad_curve,
221        ] {
222            bytes.extend_from_slice(&v.to_le_bytes());
223        }
224        bytes.extend_from_slice(&[u8::from(settings.invert_y), settings.gamepad, 0, 0]);
225        for entry in &self.entries {
226            let Some(name) = &entry.name else {
227                continue;
228            };
229            bytes.extend_from_slice(&[name.len() as u8, entry.bindings.len() as u8]);
230            bytes.extend_from_slice(name.as_bytes());
231            for b in &entry.bindings {
232                let (tag, n) = code_parts(b.code);
233                bytes.push(tag);
234                bytes.extend_from_slice(&n.to_le_bytes());
235                bytes.extend_from_slice(&b.scale.to_le_bytes());
236                bytes.extend_from_slice(&b.deadzone.to_le_bytes());
237            }
238        }
239        let sum = checksum(&bytes);
240        bytes.extend_from_slice(&sum.to_le_bytes());
241        if bytes.len() > MAX_CONFIG_BYTES {
242            return Err(InputError::InvalidConfig);
243        }
244        Ok(bytes)
245    }
246    /// Validate the whole file before mutating mappings. Unknown retired action
247    /// names are counted/ignored; omitted new actions retain host defaults.
248    /// Shared sources remain allowed for compatibility. Use
249    /// [`Self::validate_config`] to preview them or [`Self::apply_config_checked`]
250    /// to reject conflicts in the current active contexts.
251    pub fn apply_config(&mut self, bytes: &[u8]) -> Result<AppliedConfig, InputError> {
252        let decoded = decode_config(bytes)?;
253        let applied = self
254            .validate_decoded(&decoded)
255            .map_err(|_| InputError::InvalidBinding)?;
256        self.commit_config(decoded);
257        Ok(applied)
258    }
259
260    /// Preview an import without changing bindings, contexts, held suppression,
261    /// pending edges, or accumulated motion. Settings are returned, never applied
262    /// to a platform host. The existing FXIN v1 format remains unchanged.
263    ///
264    /// All decoded bindings must be structurally valid; matched names must also
265    /// match the host's action kind, including inactive actions. Unknown names
266    /// are ignored, and omitted/unnamed actions keep their current bindings.
267    /// Conflicts are computed from that complete proposed mapping.
268    ///
269    /// Only contexts active under the **current** stack participate: global is
270    /// always active, exclusive contexts hide lower contexts, and passthrough
271    /// contexts allow overlap. Reuse across inactive contexts is legitimate for
272    /// this snapshot. Revalidate after changing the stack; this is not a promise
273    /// about future context combinations. Physical values and transient held
274    /// suppression do not affect diagnostics. Zero-scale bindings are ignored.
275    ///
276    /// This configuration-time operation allocates bounded scratch storage for
277    /// at most `MAX_ACTIONS * MAX_BINDINGS` bindings and retains at most
278    /// [`MAX_CONFIG_CONFLICTS`] diagnostic pairs. It does not run on input feeds.
279    ///
280    /// ```
281    /// use ferravex_play::input::{ActionKind, ActionMap, Binding, ContextId,
282    ///     ContextMode, ControlSettings, InputCode};
283    /// let mut map = ActionMap::default();
284    /// let game = map.create_context("game")?;
285    /// let menu = map.create_context("menu")?;
286    /// let space = Binding::digital(InputCode::Key(32));
287    /// map.named_action("jump", ActionKind::Button, game, vec![space])?;
288    /// map.named_action("accept", ActionKind::Button, menu, vec![space])?;
289    /// let bytes = map.encode_config(ControlSettings::default())?;
290    /// map.set_context(Some(game))?;
291    /// map.push_context(menu, ContextMode::Exclusive)?;
292    /// assert!(map.validate_config(&bytes)?.conflicts.is_empty());
293    /// map.pop_context();
294    /// map.push_context(menu, ContextMode::Passthrough)?;
295    /// let report = map.validate_config(&bytes)?;
296    /// assert_eq!(report.applied.matched, 2);
297    /// let conflict = &report.conflicts[0];
298    /// assert_eq!(conflict.code, InputCode::Key(32));
299    /// assert_eq!(conflict.first.action_name.as_deref(), Some("jump"));
300    /// assert_eq!(conflict.second.context_name, "menu");
301    /// # Ok::<(), Box<dyn std::error::Error>>(())
302    /// ```
303    pub fn validate_config(&self, bytes: &[u8]) -> Result<ConfigValidation, ConfigError> {
304        let decoded = decode_config(bytes).map_err(ConfigError::Input)?;
305        self.inspect_config(&decoded)
306    }
307
308    /// Import only if the entire file is valid, compatible, and has no active
309    /// binding conflicts. Any error leaves the map and all pending input intact.
310    ///
311    /// Uses the same current-context snapshot as [`Self::validate_config`],
312    /// including retained defaults and unnamed actions. Success follows
313    /// [`Self::apply_config`]: matched actions discard pending edges/motion,
314    /// held buttons require release, and omitted actions retain their state.
315    /// Hosts can deliberately accept shared sources using `apply_config`.
316    ///
317    /// ```
318    /// use ferravex_play::input::{ActionKind, ActionMap, Binding, ContextId,
319    ///     ControlSettings, InputCode};
320    /// let mut map = ActionMap::default();
321    /// let space = Binding::digital(InputCode::Key(32));
322    /// let jump = map.named_action("jump", ActionKind::Button, ContextId::GLOBAL, vec![space])?;
323    /// map.named_action("fire", ActionKind::Button, ContextId::GLOBAL, vec![space])?;
324    /// let bytes = map.encode_config(ControlSettings::default())?;
325    /// map.feed(InputCode::Key(32), 1.0);
326    /// assert!(map.apply_config_checked(&bytes).is_err());
327    /// assert!(map.consume_tick(jump).pressed); // Rejection preserved the edge.
328    /// # Ok::<(), ferravex_play::input::InputError>(())
329    /// ```
330    pub fn apply_config_checked(&mut self, bytes: &[u8]) -> Result<AppliedConfig, ConfigError> {
331        let decoded = decode_config(bytes).map_err(ConfigError::Input)?;
332        let report = self.inspect_config(&decoded)?;
333        if !report.conflicts.is_empty() {
334            return Err(ConfigError::Conflicts(Box::new(report)));
335        }
336        self.commit_config(decoded);
337        Ok(report.applied)
338    }
339
340    fn config_binding(&self, action_id: usize, binding_index: usize) -> ConfigBinding {
341        let entry = &self.entries[action_id];
342        ConfigBinding {
343            action_id,
344            action_name: entry.name.clone(),
345            action_kind: entry.kind,
346            context: entry.context,
347            context_name: self.contexts[entry.context.0 as usize].clone(),
348            binding_index,
349        }
350    }
351
352    // The decoder has already checked all scalar values and storage bounds.
353    // Host kind compatibility is the only remaining binding validity check.
354    fn validate_decoded(&self, decoded: &DecodedConfig) -> Result<AppliedConfig, ConfigBinding> {
355        let mut matched = 0;
356        for action in &decoded.actions {
357            if let Some(id) = self.action_id(&action.name) {
358                let delta = self.entries[id].kind == ActionKind::Delta;
359                if let Some(index) = action
360                    .bindings
361                    .iter()
362                    .position(|binding| binding.code.is_delta() != delta)
363                {
364                    return Err(self.config_binding(id, index));
365                }
366                matched += 1;
367            }
368        }
369        Ok(AppliedConfig {
370            settings: decoded.settings,
371            matched,
372            unknown: decoded.actions.len() - matched,
373        })
374    }
375
376    fn inspect_config(&self, decoded: &DecodedConfig) -> Result<ConfigValidation, ConfigError> {
377        let applied = self
378            .validate_decoded(decoded)
379            .map_err(ConfigError::IncompatibleBinding)?;
380        let mut report = ConfigValidation {
381            applied,
382            unknown_actions: Vec::new(),
383            conflicts: Vec::new(),
384            conflicts_truncated: false,
385        };
386        let mut proposed: Vec<&[Binding]> = self
387            .entries
388            .iter()
389            .map(|entry| entry.bindings.as_ref())
390            .collect();
391        for action in &decoded.actions {
392            if let Some(id) = self.action_id(&action.name) {
393                proposed[id] = &action.bindings;
394            } else {
395                report.unknown_actions.push(action.name.clone());
396            }
397        }
398
399        let active = self.active_mask();
400        let mut sources = Vec::new();
401        for (id, bindings) in proposed.iter().enumerate() {
402            if active & (1 << self.entries[id].context.0) == 0 {
403                continue;
404            }
405            for (index, binding) in bindings.iter().enumerate() {
406                if binding.scale != 0. {
407                    sources.push((binding.code, id, index));
408                }
409            }
410        }
411        sources.sort_unstable();
412        let mut start = 0;
413        'groups: while start < sources.len() {
414            let code = sources[start].0;
415            let mut end = start + 1;
416            while end < sources.len() && sources[end].0 == code {
417                end += 1;
418            }
419            for first in start..end {
420                for second in first + 1..end {
421                    if report.conflicts.len() == MAX_CONFIG_CONFLICTS {
422                        report.conflicts_truncated = true;
423                        break 'groups;
424                    }
425                    report.conflicts.push(BindingConflict {
426                        code,
427                        first: self.config_binding(sources[first].1, sources[first].2),
428                        second: self.config_binding(sources[second].1, sources[second].2),
429                    });
430                }
431            }
432            start = end;
433        }
434        Ok(report)
435    }
436
437    fn commit_config(&mut self, decoded: DecodedConfig) {
438        // Finish all allocation before touching live bindings or pending input.
439        let replacements: Vec<_> = decoded
440            .actions
441            .into_iter()
442            .filter_map(|action| {
443                self.action_id(&action.name)
444                    .map(|id| (id, action.bindings.into_boxed_slice()))
445            })
446            .collect();
447        if replacements.is_empty() {
448            return;
449        }
450        for (id, bindings) in replacements {
451            let entry = &mut self.entries[id];
452            entry.bindings = bindings;
453            entry.state = Action::default();
454            entry.suppressed =
455                entry.kind == ActionKind::Button && raw_value(entry, &self.values).abs() >= 0.5;
456        }
457        self.recompute();
458    }
459}
460struct Reader<'a> {
461    bytes: &'a [u8],
462    cursor: usize,
463}
464impl<'a> Reader<'a> {
465    fn take(&mut self, n: usize) -> Result<&'a [u8], InputError> {
466        let end = self
467            .cursor
468            .checked_add(n)
469            .ok_or(InputError::InvalidConfig)?;
470        let out = self
471            .bytes
472            .get(self.cursor..end)
473            .ok_or(InputError::InvalidConfig)?;
474        self.cursor = end;
475        Ok(out)
476    }
477    fn byte(&mut self) -> Result<u8, InputError> {
478        Ok(self.take(1)?[0])
479    }
480    fn word(&mut self) -> Result<u16, InputError> {
481        Ok(u16::from_le_bytes(self.take(2)?.try_into().unwrap()))
482    }
483    fn float(&mut self) -> Result<f32, InputError> {
484        Ok(f32::from_le_bytes(self.take(4)?.try_into().unwrap()))
485    }
486}
487pub fn decode_config(bytes: &[u8]) -> Result<DecodedConfig, InputError> {
488    if bytes.len() < 40 || bytes.len() > MAX_CONFIG_BYTES {
489        return Err(InputError::InvalidConfig);
490    }
491    let payload = &bytes[..bytes.len() - 4];
492    let sum = u32::from_le_bytes(bytes[bytes.len() - 4..].try_into().unwrap());
493    if checksum(payload) != sum {
494        return Err(InputError::ConfigChecksum);
495    }
496    let mut r = Reader {
497        bytes: payload,
498        cursor: 0,
499    };
500    if r.take(4)? != b"FXIN" {
501        return Err(InputError::InvalidConfig);
502    }
503    if r.word()? != 1 {
504        return Err(InputError::ConfigVersion);
505    }
506    let count = r.word()? as usize;
507    if count > MAX_ACTIONS {
508        return Err(InputError::ActionCapacity);
509    }
510    let mouse_sensitivity = r.float()?;
511    let touch_sensitivity = r.float()?;
512    let pad_look = Vec2::new(r.float()?, r.float()?);
513    let pad_deadzone = r.float()?;
514    let pad_curve = r.float()?;
515    let invert = r.byte()?;
516    let gamepad = r.byte()?;
517    if invert > 1 || r.word()? != 0 {
518        return Err(InputError::InvalidConfig);
519    }
520    let settings = ControlSettings {
521        mouse_sensitivity,
522        touch_sensitivity,
523        pad_look,
524        pad_deadzone,
525        pad_curve,
526        invert_y: invert == 1,
527        gamepad,
528    };
529    if !settings.valid() {
530        return Err(InputError::InvalidConfig);
531    }
532    let mut actions: Vec<SavedAction> = Vec::with_capacity(count);
533    for _ in 0..count {
534        let name_len = r.byte()? as usize;
535        let n = r.byte()? as usize;
536        if n > MAX_BINDINGS {
537            return Err(InputError::BindingCapacity);
538        }
539        let name = std::str::from_utf8(r.take(name_len)?).map_err(|_| InputError::InvalidName)?;
540        if !valid_name(name) {
541            return Err(InputError::InvalidName);
542        }
543        if actions.iter().any(|a| a.name == name) {
544            return Err(InputError::DuplicateName);
545        }
546        let mut bindings = Vec::with_capacity(n);
547        for _ in 0..n {
548            let tag = r.byte()?;
549            let code = parse_code(tag, r.word()?)?;
550            let binding = Binding {
551                code,
552                scale: r.float()?,
553                deadzone: r.float()?,
554            };
555            if !binding.valid() {
556                return Err(InputError::InvalidBinding);
557            }
558            bindings.push(binding);
559        }
560        actions.push(SavedAction {
561            name: name.to_string(),
562            bindings,
563        });
564    }
565    if r.cursor != payload.len() {
566        return Err(InputError::InvalidConfig);
567    }
568    Ok(DecodedConfig { settings, actions })
569}
570#[cfg(test)]
571mod tests {
572    use super::*;
573
574    #[derive(Debug, PartialEq)]
575    struct LiveState {
576        entries: Vec<(Vec<Binding>, Action, bool)>,
577        values: Vec<(InputCode, f32)>,
578        stack: Vec<(ContextId, ContextMode)>,
579    }
580    fn live_state(map: &ActionMap) -> LiveState {
581        LiveState {
582            entries: map
583                .entries
584                .iter()
585                .map(|entry| (entry.bindings.to_vec(), entry.state, entry.suppressed))
586                .collect(),
587            values: map.values.clone(),
588            stack: map.stack.clone(),
589        }
590    }
591
592    fn map() -> ActionMap {
593        let mut m = ActionMap::default();
594        m.named_action(
595            "jump",
596            ActionKind::Button,
597            ContextId::GLOBAL,
598            vec![Binding::digital(InputCode::Key(32))],
599        )
600        .unwrap();
601        m.named_action(
602            "look_x",
603            ActionKind::Delta,
604            ContextId::GLOBAL,
605            vec![Binding::digital(InputCode::MouseDelta(0))],
606        )
607        .unwrap();
608        m
609    }
610    fn resign(bytes: &mut [u8]) {
611        let n = bytes.len() - 4;
612        let sum = checksum(&bytes[..n]);
613        bytes[n..].copy_from_slice(&sum.to_le_bytes());
614    }
615    #[test]
616    fn roundtrip_uses_stable_names_and_preserves_new_defaults() {
617        let m = map();
618        let settings = ControlSettings {
619            invert_y: true,
620            pad_curve: 1.5,
621            ..Default::default()
622        };
623        let bytes = m.encode_config(settings).unwrap();
624        assert_eq!(decode_config(&bytes).unwrap().settings, settings);
625        let mut target = ActionMap::default();
626        let added = target
627            .named_action(
628                "new_action",
629                ActionKind::Axis,
630                ContextId::GLOBAL,
631                vec![Binding::digital(InputCode::Key(97))],
632            )
633            .unwrap();
634        let look = target
635            .named_action("look_x", ActionKind::Delta, ContextId::GLOBAL, vec![])
636            .unwrap();
637        let jump = target
638            .named_action("jump", ActionKind::Button, ContextId::GLOBAL, vec![])
639            .unwrap();
640        let result = target.apply_config(&bytes).unwrap();
641        assert_eq!(
642            result,
643            AppliedConfig {
644                settings,
645                matched: 2,
646                unknown: 0
647            }
648        );
649        assert_eq!(
650            target.bindings(look).unwrap()[0].code,
651            InputCode::MouseDelta(0)
652        );
653        assert_eq!(target.bindings(jump).unwrap()[0].code, InputCode::Key(32));
654        assert_eq!(target.bindings(added).unwrap()[0].code, InputCode::Key(97));
655    }
656    #[test]
657    fn malformed_and_incompatible_payloads_leave_live_bindings_untouched() {
658        let mut m = map();
659        let bytes = m.encode_config(ControlSettings::default()).unwrap();
660        for len in 0..bytes.len() {
661            assert!(decode_config(&bytes[..len]).is_err());
662        }
663        let mut corrupt = bytes.clone();
664        corrupt[10] ^= 1;
665        assert_eq!(m.apply_config(&corrupt), Err(InputError::ConfigChecksum));
666        let mut version = bytes.clone();
667        version[4] = 2;
668        resign(&mut version);
669        assert_eq!(m.apply_config(&version), Err(InputError::ConfigVersion));
670        let mut settings = bytes.clone();
671        settings[8..12].copy_from_slice(&f32::NAN.to_le_bytes());
672        resign(&mut settings);
673        assert!(m.apply_config(&settings).is_err());
674        let mut other = ActionMap::default();
675        other
676            .named_action(
677                "jump",
678                ActionKind::Delta,
679                ContextId::GLOBAL,
680                vec![Binding::digital(InputCode::MouseDelta(0))],
681            )
682            .unwrap();
683        assert!(
684            m.apply_config(&other.encode_config(ControlSettings::default()).unwrap())
685                .is_err()
686        );
687        assert_eq!(m.encode_config(ControlSettings::default()).unwrap(), bytes);
688    }
689    #[test]
690    fn unknown_actions_are_reported_without_discarding_settings() {
691        let bytes = map().encode_config(ControlSettings::default()).unwrap();
692        let mut empty = ActionMap::default();
693        let result = empty.apply_config(&bytes).unwrap();
694        assert_eq!((result.matched, result.unknown), (0, 2));
695    }
696    #[test]
697    fn conflicts_follow_exclusive_passthrough_and_global_context_activity() {
698        let mut map = ActionMap::default();
699        let game = map.create_context("game").unwrap();
700        let menu = map.create_context("menu").unwrap();
701        let key = Binding::digital(InputCode::Key(32));
702        let jump = map
703            .named_action("jump", ActionKind::Button, game, vec![key])
704            .unwrap();
705        let accept = map
706            .named_action("accept", ActionKind::Button, menu, vec![key])
707            .unwrap();
708        let bytes = map.encode_config(ControlSettings::default()).unwrap();
709        assert!(map.validate_config(&bytes).unwrap().conflicts.is_empty());
710        map.push_context(game, ContextMode::Exclusive).unwrap();
711        assert!(map.validate_config(&bytes).unwrap().conflicts.is_empty());
712        map.push_context(menu, ContextMode::Exclusive).unwrap();
713        assert!(map.validate_config(&bytes).unwrap().conflicts.is_empty());
714        map.apply_config_checked(&bytes).unwrap();
715        map.pop_context();
716        map.push_context(menu, ContextMode::Passthrough).unwrap();
717        map.feed(InputCode::Key(32), 1.);
718        let before = live_state(&map);
719        let report = map.validate_config(&bytes).unwrap();
720        assert_eq!(live_state(&map), before);
721        assert_eq!(report.conflicts.len(), 1);
722        assert!(!report.conflicts_truncated);
723        assert_eq!(
724            report.conflicts[0],
725            BindingConflict {
726                code: InputCode::Key(32),
727                first: ConfigBinding {
728                    action_id: jump,
729                    action_name: Some("jump".into()),
730                    action_kind: ActionKind::Button,
731                    context: game,
732                    context_name: "game".into(),
733                    binding_index: 0,
734                },
735                second: ConfigBinding {
736                    action_id: accept,
737                    action_name: Some("accept".into()),
738                    action_kind: ActionKind::Button,
739                    context: menu,
740                    context_name: "menu".into(),
741                    binding_index: 0,
742                },
743            }
744        );
745        assert_eq!(
746            map.apply_config_checked(&bytes),
747            Err(ConfigError::Conflicts(Box::new(report)))
748        );
749        assert_eq!(live_state(&map), before);
750
751        // Held-button suppression does not hide a mapping collision.
752        map.suppress_held();
753        assert_eq!(map.validate_config(&bytes).unwrap().conflicts.len(), 1);
754        let global = map
755            .named_action("global", ActionKind::Button, ContextId::GLOBAL, vec![key])
756            .unwrap();
757        map.set_context(Some(menu)).unwrap();
758        let report = map.validate_config(&bytes).unwrap();
759        assert_eq!(report.conflicts.len(), 1);
760        assert_eq!(report.conflicts[0].first.action_id, accept);
761        assert_eq!(report.conflicts[0].second.action_id, global);
762        assert_eq!(report.conflicts[0].second.context_name, "global");
763        map.clear_contexts();
764        assert!(map.validate_config(&bytes).unwrap().conflicts.is_empty());
765    }
766
767    #[test]
768    fn preview_merges_defaults_and_unnamed_actions_but_ignores_retired_names() {
769        let mut saved = ActionMap::default();
770        for name in ["jump", "retired"] {
771            saved
772                .named_action(
773                    name,
774                    ActionKind::Button,
775                    ContextId::GLOBAL,
776                    vec![Binding::digital(InputCode::Key(32))],
777                )
778                .unwrap();
779        }
780        let settings = ControlSettings {
781            invert_y: true,
782            ..Default::default()
783        };
784        let bytes = saved.encode_config(settings).unwrap();
785        let mut target = map();
786        let jump = target.action_id("jump").unwrap();
787        target
788            .try_rebind(jump, vec![Binding::digital(InputCode::Key(65))])
789            .unwrap();
790        let added = target
791            .named_action(
792                "new_action",
793                ActionKind::Button,
794                ContextId::GLOBAL,
795                vec![Binding::digital(InputCode::Key(32))],
796            )
797            .unwrap();
798        let unnamed = target.action(vec![Binding::digital(InputCode::Key(32))]);
799        target.feed(InputCode::Key(65), 1.);
800        target.feed(InputCode::Key(65), 0.);
801        target.feed_delta(InputCode::MouseDelta(0), 5.);
802        let before = live_state(&target);
803        let report = target.validate_config(&bytes).unwrap();
804        assert_eq!(
805            report.applied,
806            AppliedConfig {
807                settings,
808                matched: 1,
809                unknown: 1,
810            }
811        );
812        assert_eq!(report.unknown_actions, ["retired"]);
813        let pairs: Vec<_> = report
814            .conflicts
815            .iter()
816            .map(|conflict| (conflict.first.action_id, conflict.second.action_id))
817            .collect();
818        assert_eq!(pairs, [(jump, added), (jump, unnamed), (added, unnamed)]);
819        assert_eq!(report.conflicts[1].second.action_name, None);
820        assert_eq!(live_state(&target), before);
821        assert_eq!(
822            target.apply_config_checked(&bytes),
823            Err(ConfigError::Conflicts(Box::new(report.clone())))
824        );
825        assert_eq!(live_state(&target), before);
826        // Existing callers can intentionally accept the reported sharing.
827        assert_eq!(target.apply_config(&bytes).unwrap(), report.applied);
828        assert_eq!(target.bindings(jump).unwrap()[0].code, InputCode::Key(32));
829        assert_eq!(target.peek(target.action_id("look_x").unwrap()).value, 5.);
830    }
831
832    #[test]
833    fn late_incompatible_inactive_action_rejects_all_changes_with_location() {
834        let mut source = ActionMap::default();
835        source
836            .named_action(
837                "jump",
838                ActionKind::Button,
839                ContextId::GLOBAL,
840                vec![Binding::digital(InputCode::Key(82))],
841            )
842            .unwrap();
843        source
844            .named_action(
845                "look_x",
846                ActionKind::Axis,
847                ContextId::GLOBAL,
848                vec![Binding::digital(InputCode::Key(65))],
849            )
850            .unwrap();
851        let bytes = source.encode_config(ControlSettings::default()).unwrap();
852        let mut target = ActionMap::default();
853        let inactive = target.create_context("inactive").unwrap();
854        let look = target
855            .named_action(
856                "look_x",
857                ActionKind::Delta,
858                inactive,
859                vec![Binding::digital(InputCode::MouseDelta(0))],
860            )
861            .unwrap();
862        target
863            .named_action(
864                "jump",
865                ActionKind::Button,
866                ContextId::GLOBAL,
867                vec![Binding::digital(InputCode::Key(32))],
868            )
869            .unwrap();
870        target.feed(InputCode::Key(32), 1.);
871        target.feed(InputCode::Key(32), 0.);
872        let before = live_state(&target);
873        let error = ConfigError::IncompatibleBinding(ConfigBinding {
874            action_id: look,
875            action_name: Some("look_x".into()),
876            action_kind: ActionKind::Delta,
877            context: inactive,
878            context_name: "inactive".into(),
879            binding_index: 0,
880        });
881        assert_eq!(target.validate_config(&bytes), Err(error.clone()));
882        assert_eq!(target.apply_config_checked(&bytes), Err(error.clone()));
883        assert_eq!(target.apply_config(&bytes), Err(InputError::InvalidBinding));
884        assert_eq!(live_state(&target), before);
885        assert!(error.to_string().contains("look_x"));
886        assert!(error.to_string().contains("inactive"));
887    }
888
889    #[test]
890    fn malformed_previews_and_imports_preserve_pending_input() {
891        let mut target = map();
892        target.feed(InputCode::Key(32), 1.);
893        target.feed_delta(InputCode::MouseDelta(0), 7.);
894        let before = live_state(&target);
895        let bytes = target.encode_config(ControlSettings::default()).unwrap();
896        let mut checksum = bytes.clone();
897        checksum[10] ^= 1;
898        let mut version = bytes.clone();
899        version[4] = 2;
900        resign(&mut version);
901        let mut nonfinite = bytes;
902        nonfinite[8..12].copy_from_slice(&f32::NAN.to_le_bytes());
903        resign(&mut nonfinite);
904        for (bytes, reason) in [
905            (Vec::new(), InputError::InvalidConfig),
906            (checksum, InputError::ConfigChecksum),
907            (version, InputError::ConfigVersion),
908            (nonfinite, InputError::InvalidConfig),
909            (vec![0; MAX_CONFIG_BYTES + 1], InputError::InvalidConfig),
910        ] {
911            assert_eq!(
912                target.validate_config(&bytes),
913                Err(ConfigError::Input(reason))
914            );
915            assert_eq!(
916                target.apply_config_checked(&bytes),
917                Err(ConfigError::Input(reason))
918            );
919            assert_eq!(target.apply_config(&bytes), Err(reason));
920            assert_eq!(live_state(&target), before);
921        }
922        assert!(
923            std::error::Error::source(&ConfigError::Input(InputError::InvalidConfig)).is_some()
924        );
925    }
926
927    #[test]
928    fn checked_import_swaps_sources_and_resets_only_matched_pending_input() {
929        let mut target = map();
930        let jump = target.action_id("jump").unwrap();
931        let look = target.action_id("look_x").unwrap();
932        let fire = target
933            .named_action(
934                "fire",
935                ActionKind::Button,
936                ContextId::GLOBAL,
937                vec![Binding::digital(InputCode::Key(65))],
938            )
939            .unwrap();
940        let retained = target
941            .named_action(
942                "retained",
943                ActionKind::Delta,
944                ContextId::GLOBAL,
945                vec![Binding::digital(InputCode::TouchDelta(1))],
946            )
947            .unwrap();
948        let unnamed = target.action(vec![Binding::digital(InputCode::Key(99))]);
949        target.feed(InputCode::Key(32), 1.);
950        target.feed(InputCode::Key(65), 1.);
951        target.feed(InputCode::Key(99), 1.);
952        target.feed(InputCode::Key(99), 0.);
953        target.feed_delta(InputCode::MouseDelta(0), 4.);
954        target.feed_delta(InputCode::TouchDelta(1), 9.);
955        let retained_state = target.peek(retained);
956        let unnamed_state = target.peek(unnamed);
957
958        // Each replacement conflicts with an old binding, but the complete
959        // proposed swap does not. Registration order differs from the target.
960        let mut source = ActionMap::default();
961        for (name, code) in [("fire", 32), ("jump", 65)] {
962            source
963                .named_action(
964                    name,
965                    ActionKind::Button,
966                    ContextId::GLOBAL,
967                    vec![Binding::digital(InputCode::Key(code))],
968                )
969                .unwrap();
970        }
971        source
972            .named_action(
973                "look_x",
974                ActionKind::Delta,
975                ContextId::GLOBAL,
976                vec![Binding::digital(InputCode::MouseDelta(1))],
977            )
978            .unwrap();
979        let bytes = source.encode_config(ControlSettings::default()).unwrap();
980        let preview = target.validate_config(&bytes).unwrap();
981        assert!(preview.conflicts.is_empty());
982        assert_eq!(
983            target.apply_config_checked(&bytes).unwrap(),
984            preview.applied
985        );
986        assert_eq!(target.peek(jump), Action::default());
987        assert_eq!(target.peek(fire), Action::default());
988        assert_eq!(target.peek(look), Action::default());
989        assert_eq!(target.peek(retained), retained_state);
990        assert_eq!(target.peek(unnamed), unnamed_state);
991        target.feed(InputCode::Key(65), 0.);
992        target.feed(InputCode::Key(65), 1.);
993        assert!(target.consume_tick(jump).pressed);
994        assert!(!target.consume_tick(fire).pressed);
995        target.feed_delta(InputCode::MouseDelta(0), 3.);
996        assert_eq!(target.peek(look), Action::default());
997        target.feed_delta(InputCode::MouseDelta(1), 2.);
998        assert_eq!(target.consume_tick(look).value, 2.);
999    }
1000
1001    #[test]
1002    fn duplicate_sources_include_signed_scales_but_ignore_zero_scales_and_other_devices() {
1003        let mut map = ActionMap::default();
1004        map.action(vec![
1005            Binding::digital(InputCode::Key(1)),
1006            Binding::digital(InputCode::Mouse(1)),
1007            Binding {
1008                code: InputCode::Key(1),
1009                scale: -2.,
1010                deadzone: 0.5,
1011            },
1012            Binding {
1013                code: InputCode::Key(1),
1014                scale: -0.,
1015                deadzone: 0.,
1016            },
1017        ]);
1018        let report = map
1019            .validate_config(&map.encode_config(ControlSettings::default()).unwrap())
1020            .unwrap();
1021        assert_eq!(report.conflicts.len(), 1);
1022        assert_eq!(report.conflicts[0].code, InputCode::Key(1));
1023        assert_eq!(report.conflicts[0].first.action_id, 0);
1024        assert_eq!(report.conflicts[0].second.action_id, 0);
1025        assert_eq!(report.conflicts[0].first.binding_index, 0);
1026        assert_eq!(report.conflicts[0].second.binding_index, 2);
1027        assert_eq!(report.conflicts[0].first.action_name, None);
1028    }
1029
1030    #[test]
1031    fn conflict_cap_distinguishes_exactly_full_and_truncated_reports() {
1032        let mut map = ActionMap::default();
1033        // C(16,2) + C(16,2) + C(6,2) + C(2,2) = 256 pairs.
1034        let mut bindings = Vec::new();
1035        for (code, count) in [(1, 16), (2, 16), (3, 6), (4, 2)] {
1036            bindings.extend(vec![Binding::digital(InputCode::Key(code)); count]);
1037        }
1038        let id = map
1039            .named_action(
1040                "many",
1041                ActionKind::Axis,
1042                ContextId::GLOBAL,
1043                bindings.clone(),
1044            )
1045            .unwrap();
1046        let bytes = map.encode_config(ControlSettings::default()).unwrap();
1047        let full = map.validate_config(&bytes).unwrap();
1048        assert_eq!(full.conflicts.len(), MAX_CONFIG_CONFLICTS);
1049        assert!(!full.conflicts_truncated);
1050        assert_eq!(map.validate_config(&bytes).unwrap(), full);
1051        bindings.push(Binding::digital(InputCode::Key(4)));
1052        map.try_rebind(id, bindings).unwrap();
1053        let bytes = map.encode_config(ControlSettings::default()).unwrap();
1054        let report = map.validate_config(&bytes).unwrap();
1055        assert_eq!(report.conflicts.len(), MAX_CONFIG_CONFLICTS);
1056        assert!(report.conflicts_truncated);
1057        assert_eq!(report.conflicts, full.conflicts);
1058        let before = live_state(&map);
1059        assert_eq!(
1060            map.apply_config_checked(&bytes),
1061            Err(ConfigError::Conflicts(Box::new(report)))
1062        );
1063        assert_eq!(live_state(&map), before);
1064    }
1065    #[test]
1066    fn radial_deadzones_curves_and_nonfinite_sticks_are_bounded() {
1067        let s = ControlSettings {
1068            pad_curve: 2.,
1069            ..Default::default()
1070        };
1071        assert_eq!(s.stick(Vec2::splat(0.1)), Vec2::ZERO);
1072        let d = s.stick(Vec2::ONE);
1073        assert!((d.length() - 1.).abs() < 1e-5);
1074        assert!((d.x - d.y).abs() < 1e-6);
1075        assert!(s.stick(Vec2::X * 0.5).x < 0.5);
1076        assert_eq!(s.stick(Vec2::new(f32::NAN, 0.)), Vec2::ZERO);
1077    }
1078}