use std::collections::{HashMap, VecDeque};
use std::error::Error;
use std::fmt;
use std::num::NonZeroU64;
use std::time::Duration;
use super::types::{
ButtonEvent, ButtonEventKind, ButtonPhase, ControlId, EventBatch, GestureKind, Timestamp,
};
pub trait EventMapper {
type Output;
type Error;
fn map_event(
&mut self,
event: &ButtonEvent,
output: &mut Vec<Self::Output>,
) -> Result<(), Self::Error>;
fn map_batch(
&mut self,
events: &[ButtonEvent],
output: &mut Vec<Self::Output>,
) -> Result<(), Self::Error> {
for event in events {
self.map_event(event, output)?;
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct QueuedInputSource<M>
where
M: EventMapper,
{
mapper: M,
pending: VecDeque<M::Output>,
}
impl<M> QueuedInputSource<M>
where
M: EventMapper,
{
pub fn new(mapper: M) -> Self {
Self {
mapper,
pending: VecDeque::new(),
}
}
pub fn mapper(&self) -> &M {
&self.mapper
}
pub fn mapper_mut(&mut self) -> &mut M {
&mut self.mapper
}
pub fn enqueue_batch(&mut self, batch: &EventBatch) -> Result<usize, M::Error> {
self.enqueue_events(&batch.events)
}
pub fn enqueue_events(&mut self, events: &[ButtonEvent]) -> Result<usize, M::Error> {
let mut mapped = Vec::new();
self.mapper.map_batch(events, &mut mapped)?;
let appended = mapped.len();
self.pending.extend(mapped);
Ok(appended)
}
pub fn next_event(&mut self) -> Option<M::Output> {
self.pending.pop_front()
}
pub fn pending_len(&self) -> usize {
self.pending.len()
}
pub fn is_empty(&self) -> bool {
self.pending.is_empty()
}
pub fn drain(&mut self) -> Vec<M::Output> {
self.pending.drain(..).collect()
}
pub fn flush_to<S>(&mut self, sink: &mut S) -> Result<usize, FlushError<S::Error>>
where
S: TryEventSink<M::Output>,
{
let mut sent = 0;
while let Some(event) = self.pending.pop_front() {
match sink.try_send(event) {
Ok(()) => sent += 1,
Err(Rejected { event, error }) => {
self.pending.push_front(event);
return Err(FlushError { sent, error });
}
}
}
Ok(sent)
}
pub fn into_parts(self) -> (M, VecDeque<M::Output>) {
(self.mapper, self.pending)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rejected<E, Err> {
pub event: E,
pub error: Err,
}
impl<E, Err> Rejected<E, Err> {
pub const fn new(event: E, error: Err) -> Self {
Self { event, error }
}
pub fn into_parts(self) -> (E, Err) {
(self.event, self.error)
}
}
pub trait TryEventSink<E> {
type Error;
fn try_send(&mut self, event: E) -> Result<(), Rejected<E, Self::Error>>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlushError<Err> {
pub sent: usize,
pub error: Err,
}
impl<Err> fmt::Display for FlushError<Err>
where
Err: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"input sink rejected an event after accepting {}: {}",
self.sent, self.error
)
}
}
impl<Err> Error for FlushError<Err>
where
Err: Error + 'static,
{
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&self.error)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SourceId(pub u32);
impl SourceId {
pub const fn new(value: u32) -> Self {
Self(value)
}
pub const fn get(self) -> u32 {
self.0
}
}
impl fmt::Display for SourceId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "source:{}", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct InputTiming {
pub occurred_at: Timestamp,
pub recognized_at: Timestamp,
}
impl From<&ButtonEvent> for InputTiming {
fn from(event: &ButtonEvent) -> Self {
Self {
occurred_at: event.occurred_at,
recognized_at: event.recognized_at,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InputValue {
Released,
Pressed,
Repeat(NonZeroU64),
Trigger,
Count(NonZeroU64),
Duration(Duration),
Scalar(i64),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct InputEvent<Code> {
pub source: SourceId,
pub sequence: u64,
pub timing: InputTiming,
pub code: Code,
pub value: InputValue,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EventSelector {
State(ButtonPhase),
Tap { count: u8 },
HoldStart { threshold: Duration },
HoldMilestone { threshold: Duration },
Repeat,
HoldEnd,
}
impl EventSelector {
pub fn classify(event: &ButtonEvent) -> (ControlId, Self) {
match &event.kind {
ButtonEventKind::State { control, phase } => (*control, Self::State(*phase)),
ButtonEventKind::Gesture { control, kind } => {
let selector = match kind {
GestureKind::Tap { count } => Self::Tap { count: *count },
GestureKind::HoldStart { threshold } => Self::HoldStart {
threshold: *threshold,
},
GestureKind::HoldMilestone { threshold } => Self::HoldMilestone {
threshold: *threshold,
},
GestureKind::Repeat { .. } => Self::Repeat,
GestureKind::HoldEnd { .. } => Self::HoldEnd,
};
(*control, selector)
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binding<Code> {
pub code: Code,
pub value: BindingValue,
}
impl<Code> Binding<Code> {
pub const fn new(code: Code, value: InputValue) -> Self {
Self {
code,
value: BindingValue::Fixed(value),
}
}
pub const fn auto(code: Code) -> Self {
Self {
code,
value: BindingValue::Auto,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BindingValue {
Fixed(InputValue),
Auto,
}
#[derive(Debug, Clone)]
pub struct BindingMapper<Code> {
source: SourceId,
next_sequence: Option<u64>,
bindings: HashMap<(ControlId, EventSelector), Vec<Binding<Code>>>,
}
impl<Code> BindingMapper<Code> {
pub fn new(source: SourceId) -> Self {
Self::with_initial_sequence(source, 0)
}
pub fn with_initial_sequence(source: SourceId, next_sequence: u64) -> Self {
Self {
source,
next_sequence: Some(next_sequence),
bindings: HashMap::new(),
}
}
pub const fn source(&self) -> SourceId {
self.source
}
pub const fn next_sequence(&self) -> Option<u64> {
self.next_sequence
}
pub fn bind(
&mut self,
control: ControlId,
selector: EventSelector,
code: Code,
value: InputValue,
) -> &mut Self {
self.bindings
.entry((control, selector))
.or_default()
.push(Binding::new(code, value));
self
}
pub fn with_binding(
mut self,
control: ControlId,
selector: EventSelector,
code: Code,
value: InputValue,
) -> Self {
self.bind(control, selector, code, value);
self
}
pub fn bind_auto(
&mut self,
control: ControlId,
selector: EventSelector,
code: Code,
) -> &mut Self {
self.bindings
.entry((control, selector))
.or_default()
.push(Binding::auto(code));
self
}
pub fn binding_count(&self) -> usize {
self.bindings.values().map(Vec::len).sum()
}
fn mapped_output_count(&self, events: &[ButtonEvent]) -> Result<usize, BindingError> {
events.iter().try_fold(0usize, |total, event| {
let key = EventSelector::classify(event);
let additional = self.bindings.get(&key).map_or(0, Vec::len);
total
.checked_add(additional)
.ok_or(BindingError::SequenceOverflow {
next_sequence: self.next_sequence,
required: usize::MAX,
})
})
}
fn sequence_after(&self, required: usize) -> Result<Option<u64>, BindingError> {
if required == 0 {
return Ok(self.next_sequence);
}
let start = self.next_sequence.ok_or(BindingError::SequenceOverflow {
next_sequence: None,
required,
})?;
let additional =
u64::try_from(required - 1).map_err(|_| BindingError::SequenceOverflow {
next_sequence: Some(start),
required,
})?;
let last = start
.checked_add(additional)
.ok_or(BindingError::SequenceOverflow {
next_sequence: Some(start),
required,
})?;
Ok(last.checked_add(1))
}
fn map_events_checked(
&mut self,
events: &[ButtonEvent],
output: &mut Vec<InputEvent<Code>>,
) -> Result<(), BindingError>
where
Code: Clone,
{
let required = self.mapped_output_count(events)?;
let sequence_after = self.sequence_after(required)?;
for event in events {
let key = EventSelector::classify(event);
if self.bindings.get(&key).is_some_and(|bindings| {
bindings
.iter()
.any(|binding| binding.value == BindingValue::Auto)
}) {
automatic_value(event)?;
}
}
let mut sequence = self.next_sequence;
for event in events {
let key = EventSelector::classify(event);
let Some(bindings) = self.bindings.get(&key) else {
continue;
};
for binding in bindings {
let current = sequence.expect("sequence capacity was preflighted");
output.push(InputEvent {
source: self.source,
sequence: current,
timing: InputTiming::from(event),
code: binding.code.clone(),
value: match binding.value {
BindingValue::Fixed(value) => value,
BindingValue::Auto => {
automatic_value(event).expect("automatic payloads were preflighted")
}
},
});
sequence = current.checked_add(1);
}
}
debug_assert_eq!(sequence, sequence_after);
self.next_sequence = sequence_after;
Ok(())
}
}
impl<Code> EventMapper for BindingMapper<Code>
where
Code: Clone,
{
type Output = InputEvent<Code>;
type Error = BindingError;
fn map_event(
&mut self,
event: &ButtonEvent,
output: &mut Vec<Self::Output>,
) -> Result<(), Self::Error> {
self.map_events_checked(std::slice::from_ref(event), output)
}
fn map_batch(
&mut self,
events: &[ButtonEvent],
output: &mut Vec<Self::Output>,
) -> Result<(), Self::Error> {
self.map_events_checked(events, output)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BindingError {
SequenceOverflow {
next_sequence: Option<u64>,
required: usize,
},
InvalidTapCount,
}
impl fmt::Display for BindingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SequenceOverflow {
next_sequence,
required,
} => write!(
f,
"cannot allocate {required} input sequence numbers starting at {next_sequence:?}"
),
Self::InvalidTapCount => write!(f, "a tap event contains count=0"),
}
}
}
impl Error for BindingError {}
fn automatic_value(event: &ButtonEvent) -> Result<InputValue, BindingError> {
match &event.kind {
ButtonEventKind::State { phase, .. } => Ok(match phase {
ButtonPhase::Down => InputValue::Pressed,
ButtonPhase::Up => InputValue::Released,
}),
ButtonEventKind::Gesture { kind, .. } => match kind {
GestureKind::Tap { count } => NonZeroU64::new(u64::from(*count))
.map(InputValue::Count)
.ok_or(BindingError::InvalidTapCount),
GestureKind::HoldStart { threshold } | GestureKind::HoldMilestone { threshold } => {
Ok(InputValue::Duration(*threshold))
}
GestureKind::Repeat { count } => Ok(InputValue::Repeat(*count)),
GestureKind::HoldEnd { held_for } => Ok(InputValue::Duration(*held_for)),
},
}
}
#[cfg(test)]
mod tests {
use super::super::types::{ChordId, KeyId};
use super::*;
const KEY_A: ControlId = ControlId::Key(KeyId(1));
const KEY_B: ControlId = ControlId::Key(KeyId(2));
fn state(control: ControlId, phase: ButtonPhase, at: u64) -> ButtonEvent {
ButtonEvent {
occurred_at: Timestamp::from_millis(at),
recognized_at: Timestamp::from_millis(at + 1),
kind: ButtonEventKind::State { control, phase },
}
}
fn tap(control: ControlId, count: u8, at: u64) -> ButtonEvent {
ButtonEvent::gesture(
control,
GestureKind::Tap { count },
Timestamp::from_millis(at),
Timestamp::from_millis(at + 2),
)
}
fn batch(events: Vec<ButtonEvent>) -> EventBatch {
let mut batch = EventBatch::new(Timestamp::from_millis(100));
batch.events = events;
batch
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct FanOutMapper;
impl EventMapper for FanOutMapper {
type Output = String;
type Error = &'static str;
fn map_event(
&mut self,
event: &ButtonEvent,
output: &mut Vec<Self::Output>,
) -> Result<(), Self::Error> {
let (control, selector) = EventSelector::classify(event);
if control == KEY_B {
return Err("unmappable B");
}
if matches!(selector, EventSelector::State(ButtonPhase::Down)) {
output.push("first".to_owned());
output.push("second".to_owned());
}
Ok(())
}
}
#[test]
fn generic_mapper_can_append_zero_or_many_outputs() {
let mut source = QueuedInputSource::new(FanOutMapper);
let added = source
.enqueue_batch(&batch(vec![
state(KEY_A, ButtonPhase::Up, 0),
state(KEY_A, ButtonPhase::Down, 2),
]))
.unwrap();
assert_eq!(added, 2);
assert_eq!(source.pending_len(), 2);
assert_eq!(source.next_event().as_deref(), Some("first"));
assert_eq!(source.next_event().as_deref(), Some("second"));
assert!(source.is_empty());
}
#[test]
fn mapping_error_never_commits_a_partial_domain_batch() {
let mut source = QueuedInputSource::new(FanOutMapper);
source
.enqueue_events(&[state(KEY_A, ButtonPhase::Down, 0)])
.unwrap();
let error = source
.enqueue_events(&[
state(KEY_A, ButtonPhase::Down, 1),
state(KEY_B, ButtonPhase::Down, 2),
])
.unwrap_err();
assert_eq!(error, "unmappable B");
assert_eq!(source.drain(), vec!["first", "second"]);
}
#[derive(Debug)]
struct ScriptedSink<E> {
outcomes: VecDeque<Result<(), &'static str>>,
accepted: Vec<E>,
calls: usize,
}
impl<E> ScriptedSink<E> {
fn new(outcomes: impl IntoIterator<Item = Result<(), &'static str>>) -> Self {
Self {
outcomes: outcomes.into_iter().collect(),
accepted: Vec::new(),
calls: 0,
}
}
}
impl<E> TryEventSink<E> for ScriptedSink<E> {
type Error = &'static str;
fn try_send(&mut self, event: E) -> Result<(), Rejected<E, Self::Error>> {
self.calls += 1;
match self.outcomes.pop_front().unwrap_or(Ok(())) {
Ok(()) => {
self.accepted.push(event);
Ok(())
}
Err(error) => Err(Rejected::new(event, error)),
}
}
}
#[test]
fn rejected_returns_ownership_without_clone() {
let mut sink = ScriptedSink::new([Err("full")]);
let event = Box::new(String::from("owned"));
let rejected = sink.try_send(event).unwrap_err();
assert_eq!(*rejected.event, "owned");
assert_eq!(rejected.error, "full");
}
#[test]
fn fifo_flush_sends_every_event_once() {
let mut source = QueuedInputSource::new(FanOutMapper);
source
.enqueue_events(&[
state(KEY_A, ButtonPhase::Down, 0),
state(KEY_A, ButtonPhase::Down, 1),
])
.unwrap();
let mut sink = ScriptedSink::new([]);
assert_eq!(source.flush_to(&mut sink), Ok(4));
assert_eq!(sink.accepted, ["first", "second", "first", "second"]);
assert!(source.is_empty());
}
#[test]
fn failed_flush_retains_rejected_event_and_tail() {
let mut source = QueuedInputSource::new(FanOutMapper);
source
.enqueue_events(&[
state(KEY_A, ButtonPhase::Down, 0),
state(KEY_A, ButtonPhase::Down, 1),
])
.unwrap();
let mut sink = ScriptedSink::new([Ok(()), Err("full")]);
let error = source.flush_to(&mut sink).unwrap_err();
assert_eq!(
error,
FlushError {
sent: 1,
error: "full"
}
);
assert_eq!(sink.accepted, ["first"]);
assert_eq!(source.drain(), ["second", "first", "second"]);
}
#[test]
fn repeated_failure_and_retry_are_exactly_once() {
let mut source = QueuedInputSource::new(FanOutMapper);
source
.enqueue_events(&[state(KEY_A, ButtonPhase::Down, 0)])
.unwrap();
for expected_error in ["full-1", "full-2"] {
let mut sink = ScriptedSink::new([Err(expected_error)]);
assert_eq!(
source.flush_to(&mut sink),
Err(FlushError {
sent: 0,
error: expected_error,
})
);
assert!(sink.accepted.is_empty());
assert_eq!(source.pending_len(), 2);
}
let mut recovered = ScriptedSink::new([]);
assert_eq!(source.flush_to(&mut recovered), Ok(2));
assert_eq!(recovered.accepted, ["first", "second"]);
assert!(source.is_empty());
}
#[test]
fn empty_flush_never_calls_sink() {
let mut source = QueuedInputSource::new(FanOutMapper);
let mut sink = ScriptedSink::<String>::new([Err("must not be used")]);
assert_eq!(source.flush_to(&mut sink), Ok(0));
assert_eq!(sink.calls, 0);
}
#[test]
fn old_pending_events_precede_new_batches() {
let mut source = QueuedInputSource::new(FanOutMapper);
source
.enqueue_events(&[state(KEY_A, ButtonPhase::Down, 0)])
.unwrap();
let mut blocked = ScriptedSink::new([Ok(()), Err("full")]);
source.flush_to(&mut blocked).unwrap_err();
source
.enqueue_events(&[state(KEY_A, ButtonPhase::Down, 1)])
.unwrap();
assert_eq!(source.drain(), ["second", "first", "second"]);
}
#[test]
fn binding_mapper_adds_runtime_context_and_preserves_binding_order() {
let mut mapper = BindingMapper::with_initial_sequence(SourceId(7), 41);
mapper
.bind(
KEY_A,
EventSelector::State(ButtonPhase::Down),
"KEY_A",
InputValue::Pressed,
)
.bind(
KEY_A,
EventSelector::State(ButtonPhase::Down),
"WAKE",
InputValue::Trigger,
);
let mut source = QueuedInputSource::new(mapper);
let domain = state(KEY_A, ButtonPhase::Down, 10);
assert_eq!(source.enqueue_events(std::slice::from_ref(&domain)), Ok(2));
assert_eq!(
source.drain(),
vec![
InputEvent {
source: SourceId(7),
sequence: 41,
timing: InputTiming::from(&domain),
code: "KEY_A",
value: InputValue::Pressed,
},
InputEvent {
source: SourceId(7),
sequence: 42,
timing: InputTiming::from(&domain),
code: "WAKE",
value: InputValue::Trigger,
},
]
);
assert_eq!(source.mapper().next_sequence(), Some(43));
}
#[test]
fn unmapped_events_are_explicitly_ignored_without_consuming_sequence() {
let mapper = BindingMapper::<u16>::new(SourceId(3));
let mut source = QueuedInputSource::new(mapper);
assert_eq!(source.enqueue_events(&[tap(KEY_A, 1, 10)]), Ok(0));
assert!(source.is_empty());
assert_eq!(source.mapper().next_sequence(), Some(0));
}
#[test]
fn selectors_distinguish_control_gesture_and_threshold() {
let chord = ControlId::Chord(ChordId(9));
let hold = ButtonEvent::gesture(
chord,
GestureKind::HoldStart {
threshold: Duration::from_secs(1),
},
Timestamp::from_millis(1_000),
Timestamp::from_millis(1_005),
);
assert_eq!(
EventSelector::classify(&hold),
(
chord,
EventSelector::HoldStart {
threshold: Duration::from_secs(1),
}
)
);
}
#[test]
fn binding_sequence_preflight_is_transactional_for_the_whole_batch() {
let mapper = BindingMapper::with_initial_sequence(SourceId(1), u64::MAX).with_binding(
KEY_A,
EventSelector::State(ButtonPhase::Down),
10u16,
InputValue::Pressed,
);
let mut source = QueuedInputSource::new(mapper);
let error = source
.enqueue_events(&[
state(KEY_A, ButtonPhase::Down, 0),
state(KEY_A, ButtonPhase::Down, 1),
])
.unwrap_err();
assert_eq!(
error,
BindingError::SequenceOverflow {
next_sequence: Some(u64::MAX),
required: 2,
}
);
assert!(source.is_empty());
assert_eq!(source.mapper().next_sequence(), Some(u64::MAX));
assert_eq!(
source.enqueue_events(&[state(KEY_A, ButtonPhase::Down, 2)]),
Ok(1)
);
let last = source.next_event().unwrap();
assert_eq!(last.sequence, u64::MAX);
assert_eq!(source.mapper().next_sequence(), None);
let exhausted = source
.enqueue_events(&[state(KEY_A, ButtonPhase::Down, 3)])
.unwrap_err();
assert_eq!(
exhausted,
BindingError::SequenceOverflow {
next_sequence: None,
required: 1,
}
);
assert!(source.is_empty());
}
#[test]
fn retry_delivers_the_same_numbered_event() {
let mapper = BindingMapper::new(SourceId(1)).with_binding(
KEY_A,
EventSelector::Tap { count: 1 },
99u16,
InputValue::Trigger,
);
let mut source = QueuedInputSource::new(mapper);
let domain = tap(KEY_A, 1, 20);
source
.enqueue_events(std::slice::from_ref(&domain))
.unwrap();
let mut blocked = ScriptedSink::new([Err("full")]);
source.flush_to(&mut blocked).unwrap_err();
assert_eq!(source.mapper().next_sequence(), Some(1));
let mut recovered = ScriptedSink::new([]);
assert_eq!(source.flush_to(&mut recovered), Ok(1));
assert_eq!(recovered.accepted[0].sequence, 0);
assert_eq!(recovered.accepted[0].timing, InputTiming::from(&domain));
assert_eq!(source.mapper().next_sequence(), Some(1));
}
#[test]
fn automatic_binding_preserves_dynamic_gesture_payload() {
let mapper = BindingMapper::new(SourceId(1));
let mut source = QueuedInputSource::new(mapper);
source
.mapper_mut()
.bind_auto(KEY_A, EventSelector::Tap { count: 2 }, "DOUBLE_TAP");
let event = tap(KEY_A, 2, 20);
source.enqueue_events(&[event]).unwrap();
assert_eq!(
source.next_event().unwrap().value,
InputValue::Count(NonZeroU64::new(2).unwrap())
);
}
}