1
//! Haptic feedback — the one OUTPUT in the input subsystem.
2
//!
3
//! It does not fit the event model, because nothing is being reported: the app
4
//! is asking the hardware to do something. But it belongs here, because every
5
//! platform exposes it through its input stack and because the thing being
6
//! driven is an input device — a trackpad, a controller, a pen.
7
//!
8
//! # Why the vocabulary is SEMANTIC and not a waveform
9
//!
10
//! Each platform has its own waveform language (Core Haptics patterns, Android
11
//! `VibrationEffect` compositions, `DualSense` trigger profiles) and none of them
12
//! translate. Worse, the same waveform feels different on every actuator: a
13
//! Taptic Engine, an LRA in a phone, and the ERM motors in a gamepad have
14
//! different resonant frequencies and rise times, so a millisecond envelope
15
//! tuned on one is mush on another.
16
//!
17
//! So the vocabulary names the INTENT — "a selection changed", "an action was
18
//! rejected" — and each backend picks the actuator's own best rendering. This
19
//! is what Apple, Google and Microsoft all recommend for their own APIs, and it
20
//! is the only way one call site can be correct on a trackpad, a phone and a
21
//! controller at once.
22
//!
23
//! The set is the union of the platform vocabularies rather than their
24
//! intersection, because the intersection is nearly empty (macOS has THREE
25
//! patterns) and a caller that wants `TextHandleMove` on Android should not be
26
//! denied it because macOS would render it as a generic tap. Anything a
27
//! platform cannot render natively degrades along [`HapticPattern::fallback`]
28
//! until it reaches something the platform does have.
29
//!
30
//! # Platform mapping
31
//!
32
//! | pattern | macOS `NSHapticFeedbackPattern` | Android | iOS `UIFeedbackGenerator` |
33
//! |---|---|---|---|
34
//! | `Selection` | `Alignment` | `CLOCK_TICK` | `UISelectionFeedbackGenerator` |
35
//! | `ImpactLight` | `Alignment` | `PRIMITIVE_LOW_TICK` | `.light` |
36
//! | `ImpactMedium` | `LevelChange` | `PRIMITIVE_TICK` | `.medium` |
37
//! | `ImpactHeavy` | `Generic` | `PRIMITIVE_CLICK` | `.heavy` |
38
//! | `ImpactSoft` | `Alignment` | `PRIMITIVE_LOW_TICK` | `.soft` |
39
//! | `ImpactRigid` | `LevelChange` | `PRIMITIVE_CLICK` | `.rigid` |
40
//! | `Success` | `LevelChange` | `CONFIRM` | `.success` |
41
//! | `Warning` | `Generic` | `EFFECT_DOUBLE_CLICK` | `.warning` |
42
//! | `Error` | `Generic` | `REJECT` | `.error` |
43
//! | `KeyPress` | `Alignment` | `KEYBOARD_PRESS` | — |
44
//! | `KeyRelease` | `Alignment` | `KEYBOARD_RELEASE` | — |
45
//! | `LongPress` | `LevelChange` | `LONG_PRESS` | — |
46
//! | `ContextClick` | `LevelChange` | `CONTEXT_CLICK` | — |
47
//! | `TextHandleMove` | `Alignment` | `TEXT_HANDLE_MOVE` | — |
48
//! | `GestureStart` | `Alignment` | `GESTURE_START` | — |
49
//! | `GestureEnd` | `Alignment` | `GESTURE_END` | — |
50
//! | `Rise` | `Alignment` | `PRIMITIVE_QUICK_RISE` | — |
51
//! | `Fall` | `Alignment` | `PRIMITIVE_QUICK_FALL` | — |
52
//! | `Spin` | `Alignment` | `PRIMITIVE_SPIN` (API 31+) | — |
53
//!
54
//! A dash means the platform has no native equivalent and the backend walks
55
//! [`HapticPattern::fallback`] to reach one it does.
56

            
57
use alloc::vec::Vec;
58

            
59
/// A haptic pattern to play, named by INTENT rather than by waveform.
60
///
61
/// See the module docs for the per-platform mapping and for why this names
62
/// intents instead of envelopes.
63
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
64
#[repr(C)]
65
pub enum HapticPattern {
66
    // --- selection ---------------------------------------------------------
67
    /// A value moved to a new discrete step — a slider hitting a detent, a
68
    /// picker wheel advancing, a segmented control changing. The lightest
69
    /// thing in the vocabulary; safe to fire repeatedly during a drag.
70
    Selection,
71

            
72
    // --- impacts, by weight ------------------------------------------------
73
    /// A small, light collision — a lightweight object landing.
74
    ImpactLight,
75
    /// A moderate collision. The sensible default for "something happened".
76
    ImpactMedium,
77
    /// A large, heavy collision — a heavyweight object landing.
78
    ImpactHeavy,
79
    /// A dull, compliant thud — the impact of something soft. Distinguished
80
    /// from `ImpactLight` by texture, not strength.
81
    ImpactSoft,
82
    /// A crisp, hard tap — the impact of something inflexible. Distinguished
83
    /// from `ImpactHeavy` by texture, not strength.
84
    ImpactRigid,
85

            
86
    // --- notifications -----------------------------------------------------
87
    /// A task completed successfully.
88
    Success,
89
    /// A task completed, but something needs attention.
90
    Warning,
91
    /// A task failed, or an action was rejected — an invalid drop target, a
92
    /// form that will not submit.
93
    Error,
94

            
95
    // --- discrete UI events ------------------------------------------------
96
    /// A key went down on an on-screen keyboard.
97
    KeyPress,
98
    /// A key came up on an on-screen keyboard.
99
    KeyRelease,
100
    /// A long press crossed its threshold and is now committed. Fire this at
101
    /// the MOMENT the threshold is crossed, not when the finger lifts — the
102
    /// whole point is to tell the user they can let go.
103
    LongPress,
104
    /// A secondary/context action was invoked — a right-click, a long-press
105
    /// menu opening.
106
    ContextClick,
107
    /// A text selection handle moved to a new character position.
108
    TextHandleMove,
109

            
110
    // --- gesture boundaries ------------------------------------------------
111
    /// A continuous gesture began and is now tracking.
112
    GestureStart,
113
    /// A continuous gesture ended.
114
    GestureEnd,
115

            
116
    // --- chirps (amplitude/frequency sweeps) -------------------------------
117
    /// A quick upward sweep — something growing, expanding, being picked up.
118
    Rise,
119
    /// A quick downward sweep — something shrinking, collapsing, being
120
    /// dropped.
121
    Fall,
122
    /// A spinning, bidirectional flutter — momentum, a wheel being flicked.
123
    Spin,
124
}
125

            
126
impl HapticPattern {
127
    /// The next-simplest pattern to try when a backend cannot render this one.
128
    ///
129
    /// Backends walk this chain rather than silently dropping the request, so
130
    /// a caller asking for `Spin` on a device whose actuator predates the
131
    /// primitive still feels *something*. Every chain terminates at
132
    /// `Selection`, which every haptic device on every platform can render;
133
    /// `Selection` itself returns `None`, which is the signal to give up.
134
    ///
135
    /// This exists because the degradation is a property of the PATTERN, not
136
    /// of the backend — otherwise all six backends would each invent their own
137
    /// (differing) fallback and the same call would feel unrelated across
138
    /// platforms.
139
    #[must_use]
140
    // The arms are grouped by semantic family, each with the comment explaining
141
    // why that family degrades where it does. Several families legitimately land
142
    // on `Selection`; merging them into one or-pattern would delete the ladder.
143
    #[allow(clippy::match_same_arms)]
144
71
    pub const fn fallback(self) -> Option<Self> {
145
        use HapticPattern::{
146
            ContextClick, Error, Fall, GestureEnd, GestureStart, ImpactHeavy, ImpactLight,
147
            ImpactMedium, ImpactRigid, ImpactSoft, KeyPress, KeyRelease, LongPress, Rise,
148
            Selection, Spin, Success, TextHandleMove, Warning,
149
        };
150
71
        match self {
151
            // The terminus: nothing is simpler than a selection tick.
152
20
            Selection => None,
153

            
154
            // Impacts collapse toward the middle weight, then to a tick.
155
17
            ImpactLight | ImpactSoft => Some(Selection),
156
12
            ImpactMedium => Some(ImpactLight),
157
5
            ImpactHeavy | ImpactRigid => Some(ImpactMedium),
158

            
159
            // Notifications degrade to an impact of matching weight: a
160
            // failure should still feel heavier than a success.
161
1
            Success => Some(ImpactLight),
162
1
            Warning => Some(ImpactMedium),
163
2
            Error => Some(ImpactHeavy),
164

            
165
            // Discrete UI events are all light taps underneath.
166
4
            KeyPress | KeyRelease | TextHandleMove => Some(Selection),
167
2
            LongPress | ContextClick => Some(ImpactMedium),
168

            
169
            // Gesture boundaries are the lightest possible marker.
170
2
            GestureStart | GestureEnd => Some(Selection),
171

            
172
            // Chirps have no simple equivalent; a medium impact at least
173
            // marks the moment.
174
2
            Rise | Fall => Some(ImpactLight),
175
3
            Spin => Some(ImpactMedium),
176
        }
177
71
    }
178

            
179
    /// Walk [`fallback`](Self::fallback) until `supported` accepts a pattern.
180
    ///
181
    /// Backends call this instead of matching on the pattern twice. Returns
182
    /// `None` if nothing in the chain is supported, which means the request
183
    /// should be dropped.
184
    #[must_use]
185
6
    pub fn resolve(self, supported: impl Fn(Self) -> bool) -> Option<Self> {
186
6
        let mut current = Some(self);
187
21
        while let Some(p) = current {
188
20
            if supported(p) {
189
5
                return Some(p);
190
15
            }
191
15
            current = p.fallback();
192
        }
193
1
        None
194
6
    }
195
}
196

            
197
/// Which device should play the pattern.
198
///
199
/// `#[repr(C, u8)]` rather than `#[repr(C)]` because `Gamepad` carries a
200
/// payload: a data-carrying enum needs an explicit discriminant type for its
201
/// layout to be defined across the FFI boundary, and the API's FFI checker
202
/// rejects `repr(C)` on one for exactly that reason.
203
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
204
#[repr(C, u8)]
205
pub enum HapticTarget {
206
    /// Whatever the system considers the default — the trackpad on a laptop,
207
    /// the body of a phone.
208
    System,
209
    /// A specific gamepad, by its `GamepadId`. Rumble rather than a tap: a
210
    /// controller's actuators are motors, so the light patterns become short
211
    /// low-amplitude pulses rather than the crisp taps a trackpad gives.
212
    Gamepad(u32),
213
    /// The pen currently in proximity. Only Apple Pencil Pro and some Surface
214
    /// pens have an actuator; a request to any other pen is silently ignored.
215
    Pen,
216
}
217

            
218
/// A queued haptic request.
219
///
220
/// Queued rather than played synchronously because a callback runs on the
221
/// layout thread, and the platform APIs that drive actuators want to be called
222
/// from the event loop — the same reason clipboard writes and menu opens are
223
/// deferred.
224
#[derive(Debug, Copy, Clone, PartialEq)]
225
#[repr(C)]
226
pub struct HapticRequest {
227
    pub pattern: HapticPattern,
228
    pub target: HapticTarget,
229
    /// Strength scale in `0.0..=1.0`, where `1.0` is the platform's own
230
    /// default strength for the pattern.
231
    ///
232
    /// Portable because three of the four backends take a scale natively:
233
    /// Android's composition primitives take a float scale, iOS's
234
    /// `impactOccurred(intensity:)` takes one, and gamepad rumble IS an
235
    /// amplitude. macOS is the exception — `NSHapticFeedbackPattern` has no
236
    /// strength axis at all, so the value is ignored there rather than
237
    /// emulated, because faking it with repeated taps feels like a stutter.
238
    pub intensity: f32,
239
    /// How long the effect should last, in milliseconds. `0` means "the
240
    /// pattern's own natural duration", which is what every tap-style
241
    /// actuator wants.
242
    ///
243
    /// Only meaningful for continuous actuators — gamepad rumble motors,
244
    /// which run until told to stop. Tap-style actuators ignore it.
245
    pub duration_ms: u32,
246
}
247

            
248
impl HapticRequest {
249
    /// A request at full strength and natural duration — the common case.
250
    #[must_use]
251
84
    pub const fn new(pattern: HapticPattern, target: HapticTarget) -> Self {
252
84
        Self {
253
84
            pattern,
254
84
            target,
255
84
            intensity: 1.0,
256
84
            duration_ms: 0,
257
84
        }
258
84
    }
259

            
260
    /// Clamp the scale into the range every backend assumes.
261
    ///
262
    /// Callers compute intensity from things like drag velocity, so an
263
    /// out-of-range or NaN value is expected rather than exceptional; a NaN
264
    /// reaching Android's `addPrimitive` throws.
265
    #[must_use]
266
11
    pub const fn intensity_clamped(&self) -> f32 {
267
11
        if self.intensity.is_nan() {
268
3
            1.0
269
        } else {
270
8
            self.intensity.clamp(0.0, 1.0)
271
        }
272
11
    }
273

            
274
    /// How long a CONTINUOUS actuator should run, in milliseconds.
275
    ///
276
    /// `duration_ms == 0` means "the pattern's natural duration", which for a
277
    /// tap-style actuator is whatever the platform does and for a MOTOR is not
278
    /// zero: a rumble of zero length is not something a person can feel.
279
    /// 150ms is gilrs's own example figure and about the shortest pulse an ERM
280
    /// motor can spin up and down within.
281
    ///
282
    /// Shared rather than repeated per backend: the gilrs path and the Android
283
    /// per-controller vibrator answer the same question, and two copies of a
284
    /// magic number drift.
285
    #[must_use]
286
2
    pub const fn rumble_duration_ms(&self) -> u32 {
287
2
        rumble_duration_ms(self.duration_ms)
288
2
    }
289

            
290
    /// Which MOTOR this pattern belongs on, not how hard to drive it.
291
    ///
292
    /// A controller has a low-frequency motor that THUDS and a high-frequency
293
    /// one that BUZZES, and the pattern picks between them. Driving both
294
    /// together is a different, muddier sensation rather than a louder one -
295
    /// which is why this is a bool and not a mix.
296
    ///
297
    /// `true` = the strong (low-frequency) motor.
298
    #[must_use]
299
12
    pub const fn wants_strong_motor(&self) -> bool {
300
6
        matches!(
301
12
            self.pattern,
302
            HapticPattern::ImpactHeavy
303
                | HapticPattern::ImpactMedium
304
                | HapticPattern::ImpactRigid
305
                | HapticPattern::Error
306
                | HapticPattern::Warning
307
                | HapticPattern::LongPress
308
        )
309
12
    }
310

            
311
    /// The intensity as an 8-bit amplitude in `1..=255`.
312
    ///
313
    /// Android's `VibrationEffect.createOneShot` takes amplitude in that
314
    /// range, where `0` is not "silent" but INVALID - it throws
315
    /// `IllegalArgumentException`. A caller that wants silence must not play
316
    /// at all, so this floors at 1 and the backend checks for a zero intensity
317
    /// before calling.
318
    #[must_use]
319
7
    pub fn amplitude_u8(&self) -> u8 {
320
7
        let scaled = self.intensity_clamped() * 255.0;
321
        // `as` saturates, and the clamp above already bounds it to [0, 255];
322
        // the floor at 1 is the part that matters.
323
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
324
7
        let byte = scaled as u8;
325
7
        byte.max(1)
326
7
    }
327
}
328

            
329
/// See [`HapticRequest::rumble_duration_ms`].
330
const DEFAULT_RUMBLE_MS: u32 = 150;
331

            
332
/// The free-function form of [`HapticRequest::rumble_duration_ms`], for a
333
/// backend that was handed the duration rather than the whole request.
334
#[must_use]
335
2
pub const fn rumble_duration_ms(duration_ms: u32) -> u32 {
336
2
    if duration_ms == 0 {
337
1
        DEFAULT_RUMBLE_MS
338
    } else {
339
1
        duration_ms
340
    }
341
2
}
342

            
343
/// Collects haptic requests for the platform backend to play.
344
#[derive(Debug, Clone, Default, PartialEq)]
345
pub struct HapticManager {
346
    pending: Vec<HapticRequest>,
347
}
348

            
349
impl HapticManager {
350
    #[must_use]
351
29055
    pub fn new() -> Self {
352
29055
        Self::default()
353
29055
    }
354

            
355
    /// Queue a pattern at full strength.
356
66
    pub fn play(&mut self, pattern: HapticPattern, target: HapticTarget) {
357
66
        self.play_request(HapticRequest::new(pattern, target));
358
66
    }
359

            
360
    /// Queue a fully-specified request.
361
66
    pub fn play_request(&mut self, request: HapticRequest) {
362
        // Coalesced: a callback that fires per-frame during a drag would
363
        // otherwise queue a tick per frame and the device would buzz
364
        // continuously instead of ticking once.
365
66
        if self
366
66
            .pending
367
66
            .last()
368
66
            .is_some_and(|r| r.pattern == request.pattern && r.target == request.target)
369
        {
370
59
            return;
371
7
        }
372
7
        self.pending.push(request);
373
66
    }
374

            
375
    /// Drain the queue — called by the shell each pass.
376
5
    pub fn take_pending(&mut self) -> Vec<HapticRequest> {
377
5
        core::mem::take(&mut self.pending)
378
5
    }
379

            
380
    /// Whether anything is queued, so a backend can skip acquiring a native
381
    /// performer (which on macOS means an Objective-C round trip) when there
382
    /// is nothing to play. Called once per pass on every window.
383
    #[must_use]
384
2
    pub const fn has_pending(&self) -> bool {
385
2
        !self.pending.is_empty()
386
2
    }
387
}
388

            
389
#[cfg(test)]
390
mod tests {
391
    use super::*;
392

            
393
    /// A rumble of zero length is not something a person can feel, so `0`
394
    /// ("natural duration") has to become a real pulse for a MOTOR - unlike a
395
    /// tap actuator, where the platform decides.
396
    #[test]
397
1
    fn a_natural_duration_becomes_a_real_pulse_for_a_motor() {
398
1
        let mut r = HapticRequest::new(HapticPattern::ImpactHeavy, HapticTarget::System);
399
1
        assert_eq!(r.duration_ms, 0, "the constructor still means `natural`");
400
1
        assert_eq!(r.rumble_duration_ms(), 150);
401

            
402
1
        r.duration_ms = 40;
403
1
        assert_eq!(r.rumble_duration_ms(), 40, "an explicit duration wins");
404
1
    }
405

            
406
    /// The split is by PATTERN, not by strength: a heavy impact belongs on the
407
    /// low-frequency motor and a selection tick on the high-frequency one, and
408
    /// swapping them makes every tick feel like a thud.
409
    #[test]
410
1
    fn the_motor_split_follows_the_pattern() {
411
6
        for p in [
412
1
            HapticPattern::ImpactHeavy,
413
1
            HapticPattern::ImpactMedium,
414
1
            HapticPattern::ImpactRigid,
415
1
            HapticPattern::Error,
416
1
            HapticPattern::Warning,
417
1
            HapticPattern::LongPress,
418
        ] {
419
6
            assert!(
420
6
                HapticRequest::new(p, HapticTarget::System).wants_strong_motor(),
421
                "{p:?} must drive the strong motor"
422
            );
423
        }
424
6
        for p in [
425
1
            HapticPattern::Selection,
426
1
            HapticPattern::ImpactLight,
427
1
            HapticPattern::ImpactSoft,
428
1
            HapticPattern::Success,
429
1
            HapticPattern::KeyPress,
430
1
            HapticPattern::TextHandleMove,
431
        ] {
432
6
            assert!(
433
6
                !HapticRequest::new(p, HapticTarget::System).wants_strong_motor(),
434
                "{p:?} must drive the weak motor"
435
            );
436
        }
437
1
    }
438

            
439
    /// Android's `createOneShot` REJECTS amplitude 0 - it is invalid, not
440
    /// silent - so the floor at 1 is what keeps a very small intensity from
441
    /// throwing instead of buzzing faintly.
442
    #[test]
443
1
    fn the_amplitude_never_reaches_the_value_android_rejects() {
444
1
        let mut r = HapticRequest::new(HapticPattern::ImpactHeavy, HapticTarget::System);
445

            
446
1
        r.intensity = 1.0;
447
1
        assert_eq!(r.amplitude_u8(), 255);
448
1
        r.intensity = 0.5;
449
1
        assert_eq!(r.amplitude_u8(), 127);
450

            
451
5
        for tiny in [0.0, 0.0001, -5.0, f32::NAN] {
452
4
            r.intensity = tiny;
453
4
            let a = r.amplitude_u8();
454
4
            assert!(
455
4
                a >= 1,
456
                "intensity {tiny} produced amplitude {a}, which Android rejects"
457
            );
458
        }
459
        // NaN is treated as "full" by `intensity_clamped`, not as zero.
460
1
        r.intensity = f32::NAN;
461
1
        assert_eq!(r.amplitude_u8(), 255);
462
1
    }
463

            
464
    /// Every chain has to TERMINATE, or a backend walking it hangs. A cycle
465
    /// here would be an infinite loop inside the event loop, on the device
466
    /// only, which is the worst possible place to discover it.
467
    #[test]
468
1
    fn every_fallback_chain_terminates_at_selection() {
469
        const ALL: &[HapticPattern] = &[
470
            HapticPattern::Selection,
471
            HapticPattern::ImpactLight,
472
            HapticPattern::ImpactMedium,
473
            HapticPattern::ImpactHeavy,
474
            HapticPattern::ImpactSoft,
475
            HapticPattern::ImpactRigid,
476
            HapticPattern::Success,
477
            HapticPattern::Warning,
478
            HapticPattern::Error,
479
            HapticPattern::KeyPress,
480
            HapticPattern::KeyRelease,
481
            HapticPattern::LongPress,
482
            HapticPattern::ContextClick,
483
            HapticPattern::TextHandleMove,
484
            HapticPattern::GestureStart,
485
            HapticPattern::GestureEnd,
486
            HapticPattern::Rise,
487
            HapticPattern::Fall,
488
            HapticPattern::Spin,
489
        ];
490

            
491
20
        for start in ALL {
492
19
            let mut seen = alloc::vec::Vec::new();
493
19
            let mut current = Some(*start);
494
75
            while let Some(p) = current {
495
56
                assert!(
496
56
                    !seen.contains(&p),
497
                    "fallback chain from {start:?} cycles at {p:?} (seen {seen:?})"
498
                );
499
56
                seen.push(p);
500
56
                assert!(
501
56
                    seen.len() <= ALL.len(),
502
                    "fallback chain from {start:?} is longer than the vocabulary"
503
                );
504
56
                current = p.fallback();
505
            }
506
19
            assert_eq!(
507
19
                seen.last(),
508
                Some(&HapticPattern::Selection),
509
                "chain from {start:?} ended at {:?}, not Selection — a backend that only supports \
510
                 Selection would drop it",
511
                seen.last()
512
            );
513
        }
514
1
    }
515

            
516
    /// The point of the chain: a backend supporting only the one universal
517
    /// pattern still renders every request in the vocabulary.
518
    #[test]
519
1
    fn a_selection_only_backend_resolves_everything() {
520
4
        for p in [
521
1
            HapticPattern::Spin,
522
1
            HapticPattern::Error,
523
1
            HapticPattern::ImpactHeavy,
524
1
            HapticPattern::TextHandleMove,
525
        ] {
526
4
            assert_eq!(
527
15
                p.resolve(|c| c == HapticPattern::Selection),
528
                Some(HapticPattern::Selection),
529
                "{p:?} did not degrade to Selection"
530
            );
531
        }
532
1
    }
533

            
534
    /// A backend that supports the pattern natively must NOT degrade it.
535
    #[test]
536
1
    fn resolve_prefers_the_exact_pattern() {
537
1
        assert_eq!(
538
1
            HapticPattern::Spin.resolve(|_| true),
539
            Some(HapticPattern::Spin)
540
        );
541
1
    }
542

            
543
    /// A backend with no actuator at all gets `None` rather than looping.
544
    #[test]
545
1
    fn resolve_gives_up_when_nothing_is_supported() {
546
1
        assert_eq!(HapticPattern::Spin.resolve(|_| false), None);
547
1
    }
548

            
549
    /// The dedup exists so a per-frame drag callback ticks once, not 60×.
550
    #[test]
551
1
    fn adjacent_identical_requests_coalesce() {
552
1
        let mut m = HapticManager::new();
553
61
        for _ in 0..60 {
554
60
            m.play(HapticPattern::Selection, HapticTarget::System);
555
60
        }
556
1
        assert_eq!(m.take_pending().len(), 1);
557
1
    }
558

            
559
    /// ...but a DIFFERENT pattern in between must survive: coalescing is
560
    /// adjacent-only, not a set.
561
    #[test]
562
1
    fn a_different_pattern_breaks_the_coalescing_run() {
563
1
        let mut m = HapticManager::new();
564
1
        m.play(HapticPattern::Selection, HapticTarget::System);
565
1
        m.play(HapticPattern::Error, HapticTarget::System);
566
1
        m.play(HapticPattern::Selection, HapticTarget::System);
567
1
        assert_eq!(m.take_pending().len(), 3);
568
1
    }
569

            
570
    /// The same pattern on two different devices is two different requests.
571
    #[test]
572
1
    fn the_target_is_part_of_the_coalescing_key() {
573
1
        let mut m = HapticManager::new();
574
1
        m.play(HapticPattern::Selection, HapticTarget::System);
575
1
        m.play(HapticPattern::Selection, HapticTarget::Gamepad(0));
576
1
        assert_eq!(m.take_pending().len(), 2);
577
1
    }
578

            
579
    /// A NaN intensity reaching Android's `addPrimitive` throws, and callers
580
    /// derive intensity from velocities that can divide by zero.
581
    #[test]
582
1
    fn intensity_is_clamped_and_nan_becomes_full_strength() {
583
1
        let mk = |i: f32| HapticRequest {
584
4
            intensity: i,
585
4
            ..HapticRequest::new(HapticPattern::Selection, HapticTarget::System)
586
4
        };
587
1
        assert_eq!(mk(f32::NAN).intensity_clamped(), 1.0);
588
1
        assert_eq!(mk(-3.0).intensity_clamped(), 0.0);
589
1
        assert_eq!(mk(9.0).intensity_clamped(), 1.0);
590
1
        assert_eq!(mk(0.25).intensity_clamped(), 0.25);
591
1
    }
592

            
593
    /// Draining must actually empty the queue, or the coalescing key (the
594
    /// LAST entry) never changes and every later request is swallowed.
595
    #[test]
596
1
    fn take_pending_empties_the_queue() {
597
1
        let mut m = HapticManager::new();
598
1
        m.play(HapticPattern::Error, HapticTarget::System);
599
1
        assert!(m.has_pending());
600
1
        assert_eq!(m.take_pending().len(), 1);
601
1
        assert!(!m.has_pending());
602
1
        assert!(m.take_pending().is_empty());
603
1
    }
604
}