cranpose-services 0.1.85

Multiplatform system services for Cranpose (HTTP, URI, and OS integrations)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Haptic feedback — the framework analogue of Jetpack's `LocalHapticFeedback`.
//!
//! The compiled-in default is a no-op; platform backends install a real
//! implementation through [`set_platform_haptics`] (iOS `UIFeedbackGenerator`,
//! Android `Vibrator`). Desktop and the web have no haptics and drop it.
//!
//! Two layers sit on one trait. [`HapticFeedback`] names the seven semantic
//! events every platform can express, and is what UI code should use.
//! [`HapticPattern`], [`Haptics::vibrate`] and [`Haptics::perform_effect`]
//! address the vibrator directly, which is what an app that designs its own
//! set of distinct "feels" needs; every one of them carries a defaulted body
//! that degrades to the closest [`HapticFeedback`] constant, so a backend that
//! implements only [`Haptics::perform`] still answers the whole trait.

use cranpose_core::compositionLocalOfWithPolicy;
use cranpose_core::CompositionLocal;
use cranpose_core::CompositionLocalProvider;
use cranpose_macros::composable;
use std::cell::RefCell;
use std::rc::Rc;

/// A haptic feedback event.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum HapticFeedback {
    /// A light physical impact (e.g. a small control toggling).
    ImpactLight,
    /// A medium physical impact (e.g. a button press).
    ImpactMedium,
    /// A heavy physical impact (e.g. a large snap).
    ImpactHeavy,
    /// A selection change (e.g. scrubbing through a picker).
    Selection,
    /// A task completed successfully.
    Success,
    /// A warning.
    Warning,
    /// An error / rejected action.
    Error,
}

/// A system-defined vibration primitive.
///
/// These map to Android's `VibrationEffect.EFFECT_*` constants, which are tuned
/// per device by the manufacturer and therefore feel more native than a
/// hand-timed one-shot of the same length.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum HapticEffect {
    /// `VibrationEffect.EFFECT_CLICK`.
    Click,
    /// `VibrationEffect.EFFECT_TICK` — the lightest primitive.
    Tick,
    /// `VibrationEffect.EFFECT_DOUBLE_CLICK`.
    DoubleClick,
    /// `VibrationEffect.EFFECT_HEAVY_CLICK`.
    HeavyClick,
}

impl HapticEffect {
    /// The closest [`HapticFeedback`] constant, used by the trait's defaulted
    /// bodies and by backends without predefined effects.
    pub fn closest_feedback(self) -> HapticFeedback {
        match self {
            HapticEffect::Tick => HapticFeedback::Selection,
            HapticEffect::Click => HapticFeedback::ImpactLight,
            HapticEffect::DoubleClick => HapticFeedback::ImpactMedium,
            HapticEffect::HeavyClick => HapticFeedback::ImpactHeavy,
        }
    }
}

/// Why a haptic pattern could not be built.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum HapticError {
    /// Timings and amplitudes must describe the same number of steps.
    #[error("waveform has {timings} timings and {amplitudes} amplitudes; they must match")]
    LengthMismatch {
        /// How many timings were supplied.
        timings: usize,
        /// How many amplitudes were supplied.
        amplitudes: usize,
    },
    /// A waveform needs at least one step.
    #[error("waveform has no steps")]
    Empty,
    /// A waveform whose timings are all zero would never play.
    #[error("waveform has a total duration of zero")]
    ZeroDuration,
    /// The repeat index must point at a step of the waveform.
    #[error("repeat index {index} is out of range for a {len}-step waveform")]
    RepeatOutOfRange {
        /// The requested repeat index.
        index: usize,
        /// How many steps the waveform has.
        len: usize,
    },
    /// The waveform is longer than the platform vibrator accepts.
    #[error("waveform has {len} steps, more than the maximum of {max}")]
    TooManySteps {
        /// How many steps were supplied.
        len: usize,
        /// The maximum step count.
        max: usize,
    },
}

/// A vibration waveform: alternating durations with a target amplitude each.
///
/// This is Android's `VibrationEffect.createWaveform(long[], int[], int)` in
/// framework terms. Index 0 is an off period by convention (its amplitude is
/// usually 0), then on, then off — but nothing enforces that, so an app is
/// free to shape a ramp out of consecutive non-zero amplitudes.
///
/// Amplitudes run 0 (off) to 255 (the device's strongest). Devices without
/// amplitude control treat any non-zero amplitude as full strength; check
/// [`Haptics::has_amplitude_control`] before designing around subtle levels.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HapticPattern {
    timings_ms: Vec<u32>,
    amplitudes: Vec<u8>,
    repeat: Option<usize>,
}

impl HapticPattern {
    /// The longest waveform the framework passes to a platform vibrator.
    /// Android's own limit is device-defined and far lower in practice; this
    /// bound keeps a malformed pattern from reaching JNI at all.
    pub const MAX_STEPS: usize = 512;

    /// Builds a one-shot waveform.
    ///
    /// Fails when the two slices differ in length, when there are no steps, or
    /// when every timing is zero.
    pub fn new(timings_ms: &[u32], amplitudes: &[u8]) -> Result<HapticPattern, HapticError> {
        Self::build(timings_ms, amplitudes, None)
    }

    /// Builds a waveform that loops back to `repeat_index` until
    /// [`Haptics::cancel`] stops it.
    pub fn repeating(
        timings_ms: &[u32],
        amplitudes: &[u8],
        repeat_index: usize,
    ) -> Result<HapticPattern, HapticError> {
        Self::build(timings_ms, amplitudes, Some(repeat_index))
    }

    fn build(
        timings_ms: &[u32],
        amplitudes: &[u8],
        repeat: Option<usize>,
    ) -> Result<HapticPattern, HapticError> {
        if timings_ms.len() != amplitudes.len() {
            return Err(HapticError::LengthMismatch {
                timings: timings_ms.len(),
                amplitudes: amplitudes.len(),
            });
        }
        if timings_ms.is_empty() {
            return Err(HapticError::Empty);
        }
        if timings_ms.len() > HapticPattern::MAX_STEPS {
            return Err(HapticError::TooManySteps {
                len: timings_ms.len(),
                max: HapticPattern::MAX_STEPS,
            });
        }
        if timings_ms.iter().all(|step| *step == 0) {
            return Err(HapticError::ZeroDuration);
        }
        if let Some(index) = repeat {
            if index >= timings_ms.len() {
                return Err(HapticError::RepeatOutOfRange {
                    index,
                    len: timings_ms.len(),
                });
            }
        }
        Ok(HapticPattern {
            timings_ms: timings_ms.to_vec(),
            amplitudes: amplitudes.to_vec(),
            repeat,
        })
    }

    /// The per-step durations in milliseconds.
    pub fn timings_ms(&self) -> &[u32] {
        &self.timings_ms
    }

    /// The per-step amplitudes, 0 to 255.
    pub fn amplitudes(&self) -> &[u8] {
        &self.amplitudes
    }

    /// The index the waveform loops back to, if it repeats.
    pub fn repeat(&self) -> Option<usize> {
        self.repeat
    }

    /// How many steps the waveform has.
    pub fn len(&self) -> usize {
        self.timings_ms.len()
    }

    /// Always `false`: a pattern cannot be built with no steps.
    pub fn is_empty(&self) -> bool {
        false
    }

    /// One pass through the waveform, in milliseconds.
    pub fn total_duration_ms(&self) -> u32 {
        self.timings_ms
            .iter()
            .fold(0u32, |sum, step| sum.saturating_add(*step))
    }

    /// The strongest amplitude in the waveform, which is what a backend
    /// without waveform support falls back on.
    pub fn peak_amplitude(&self) -> u8 {
        self.amplitudes.iter().copied().max().unwrap_or(0)
    }

    /// The closest [`HapticFeedback`] constant for this pattern, derived from
    /// its strength and length. Backends without waveform support use it.
    pub fn closest_feedback(&self) -> HapticFeedback {
        let peak = u32::from(self.peak_amplitude());
        let duration = self.total_duration_ms();
        if peak >= 200 || duration >= 120 {
            HapticFeedback::ImpactHeavy
        } else if peak >= 110 || duration >= 40 {
            HapticFeedback::ImpactMedium
        } else {
            HapticFeedback::ImpactLight
        }
    }
}

/// Performs haptic feedback. Installed by the platform backend; the default is
/// a no-op.
///
/// Only [`perform`](Haptics::perform) has to be implemented. Every other method
/// falls back to it, so extending this trait cannot break an existing backend.
pub trait Haptics {
    /// Plays a semantic feedback event.
    fn perform(&self, feedback: HapticFeedback);

    /// Vibrates once for `duration_ms` at `amplitude` (1 to 255; 0 means the
    /// device default strength).
    ///
    /// Maps to `VibrationEffect.createOneShot(long, int)` on Android. The
    /// defaulted body picks the closest [`HapticFeedback`] constant.
    fn vibrate(&self, duration_ms: u32, amplitude: u8) {
        let feedback = if amplitude >= 200 || duration_ms >= 120 {
            HapticFeedback::ImpactHeavy
        } else if amplitude >= 110 || duration_ms >= 40 {
            HapticFeedback::ImpactMedium
        } else {
            HapticFeedback::ImpactLight
        };
        self.perform(feedback);
    }

    /// Plays a waveform pattern.
    ///
    /// Maps to `VibrationEffect.createWaveform(long[], int[], int)` on Android.
    /// The defaulted body plays [`HapticPattern::closest_feedback`] once.
    fn play_pattern(&self, pattern: &HapticPattern) {
        self.perform(pattern.closest_feedback());
    }

    /// Plays a system-defined primitive.
    ///
    /// Maps to `VibrationEffect.createPredefined(int)` on Android. The
    /// defaulted body plays [`HapticEffect::closest_feedback`].
    fn perform_effect(&self, effect: HapticEffect) {
        self.perform(effect.closest_feedback());
    }

    /// Stops any vibration in progress, including a repeating waveform.
    /// Backends with no way to cancel leave this as a no-op.
    fn cancel(&self) {}

    /// Whether the device reproduces amplitudes rather than treating every
    /// non-zero level as full strength.
    fn has_amplitude_control(&self) -> bool {
        false
    }
}

pub type HapticsRef = Rc<dyn Haptics>;

struct NoopHaptics;

impl Haptics for NoopHaptics {
    fn perform(&self, _feedback: HapticFeedback) {}
}

thread_local! {
    static PLATFORM_HAPTICS: RefCell<Option<HapticsRef>> = const { RefCell::new(None) };
}

/// Installs a platform haptics implementation, replacing any previous one.
pub fn set_platform_haptics(haptics: HapticsRef) {
    PLATFORM_HAPTICS.with(|cell| *cell.borrow_mut() = Some(haptics));
}

/// Removes any registered platform haptics (tests and teardown).
pub fn clear_platform_haptics() {
    PLATFORM_HAPTICS.with(|cell| *cell.borrow_mut() = None);
}

pub fn default_haptics() -> HapticsRef {
    PLATFORM_HAPTICS
        .with(|cell| cell.borrow().clone())
        .unwrap_or_else(|| Rc::new(NoopHaptics))
}

pub fn local_haptics() -> CompositionLocal<HapticsRef> {
    thread_local! {
        static LOCAL_HAPTICS: RefCell<Option<CompositionLocal<HapticsRef>>> = const { RefCell::new(None) };
    }

    LOCAL_HAPTICS.with(|cell| {
        let mut local = cell.borrow_mut();
        local
            .get_or_insert_with(|| compositionLocalOfWithPolicy(default_haptics, Rc::ptr_eq))
            .clone()
    })
}

#[allow(non_snake_case)]
#[composable]
pub fn ProvideHaptics(content: impl FnOnce()) {
    let haptics = cranpose_core::remember(default_haptics).with(|state| state.clone());
    let local = local_haptics();
    CompositionLocalProvider(vec![local.provides(haptics)], move || {
        content();
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::run_test_composition;
    use std::cell::Cell;

    /// A backend that implements only `perform`, exactly as one written before
    /// the waveform methods existed would.
    #[derive(Default)]
    struct Rec {
        events: RefCell<Vec<HapticFeedback>>,
    }

    impl Haptics for Rec {
        fn perform(&self, feedback: HapticFeedback) {
            self.events.borrow_mut().push(feedback);
        }
    }

    #[test]
    fn registered_haptics_receives_events() {
        clear_platform_haptics();
        default_haptics().perform(HapticFeedback::Selection); // no-op, no panic

        struct Counter(Rc<Cell<u32>>);
        impl Haptics for Counter {
            fn perform(&self, _f: HapticFeedback) {
                self.0.set(self.0.get() + 1);
            }
        }
        let count = Rc::new(Cell::new(0));
        set_platform_haptics(Rc::new(Counter(count.clone())));
        default_haptics().perform(HapticFeedback::ImpactMedium);
        assert_eq!(count.get(), 1);
        clear_platform_haptics();
    }

    #[test]
    fn noop_backend_answers_every_method_without_panicking() {
        clear_platform_haptics();
        let haptics = default_haptics();
        haptics.perform(HapticFeedback::Error);
        haptics.vibrate(30, 128);
        haptics.perform_effect(HapticEffect::DoubleClick);
        haptics.play_pattern(&HapticPattern::new(&[0, 20, 10, 20], &[0, 255, 0, 120]).unwrap());
        haptics.cancel();
        assert!(!haptics.has_amplitude_control());
    }

    #[test]
    fn waveform_rejects_length_mismatch_instead_of_panicking() {
        assert_eq!(
            HapticPattern::new(&[0, 20, 10], &[0, 255]),
            Err(HapticError::LengthMismatch {
                timings: 3,
                amplitudes: 2
            })
        );
        assert_eq!(
            HapticPattern::repeating(&[0, 20], &[0, 255, 128], 0),
            Err(HapticError::LengthMismatch {
                timings: 2,
                amplitudes: 3
            })
        );
    }

    #[test]
    fn waveform_rejects_empty_zero_and_out_of_range_repeat() {
        assert_eq!(HapticPattern::new(&[], &[]), Err(HapticError::Empty));
        assert_eq!(
            HapticPattern::new(&[0, 0, 0], &[0, 255, 0]),
            Err(HapticError::ZeroDuration)
        );
        assert_eq!(
            HapticPattern::repeating(&[0, 20], &[0, 255], 2),
            Err(HapticError::RepeatOutOfRange { index: 2, len: 2 })
        );
        let long = vec![1u32; HapticPattern::MAX_STEPS + 1];
        let amps = vec![1u8; HapticPattern::MAX_STEPS + 1];
        assert_eq!(
            HapticPattern::new(&long, &amps),
            Err(HapticError::TooManySteps {
                len: HapticPattern::MAX_STEPS + 1,
                max: HapticPattern::MAX_STEPS
            })
        );
    }

    #[test]
    fn waveform_exposes_its_shape() {
        let pattern = HapticPattern::repeating(&[0, 40, 30, 40], &[0, 200, 0, 90], 1)
            .expect("valid waveform");
        assert_eq!(pattern.timings_ms(), &[0, 40, 30, 40]);
        assert_eq!(pattern.amplitudes(), &[0, 200, 0, 90]);
        assert_eq!(pattern.repeat(), Some(1));
        assert_eq!(pattern.len(), 4);
        assert!(!pattern.is_empty());
        assert_eq!(pattern.total_duration_ms(), 110);
        assert_eq!(pattern.peak_amplitude(), 200);
        assert_eq!(pattern.closest_feedback(), HapticFeedback::ImpactHeavy);

        let light = HapticPattern::new(&[0, 8], &[0, 40]).expect("valid waveform");
        assert_eq!(light.closest_feedback(), HapticFeedback::ImpactLight);
        let medium = HapticPattern::new(&[0, 50], &[0, 120]).expect("valid waveform");
        assert_eq!(medium.closest_feedback(), HapticFeedback::ImpactMedium);
        assert_eq!(light.repeat(), None);
    }

    #[test]
    fn total_duration_saturates_instead_of_overflowing() {
        let pattern = HapticPattern::new(&[u32::MAX, u32::MAX], &[255, 255]).expect("valid");
        assert_eq!(pattern.total_duration_ms(), u32::MAX);
    }

    #[test]
    fn defaulted_methods_fall_back_to_perform() {
        let backend = Rc::new(Rec::default());
        let haptics: HapticsRef = backend.clone();

        haptics.vibrate(10, 20);
        haptics.vibrate(60, 20);
        haptics.vibrate(10, 220);
        haptics.perform_effect(HapticEffect::Tick);
        haptics.perform_effect(HapticEffect::Click);
        haptics.perform_effect(HapticEffect::DoubleClick);
        haptics.perform_effect(HapticEffect::HeavyClick);
        haptics.play_pattern(&HapticPattern::new(&[0, 200], &[0, 255]).unwrap());
        haptics.cancel();

        assert_eq!(
            *backend.events.borrow(),
            vec![
                HapticFeedback::ImpactLight,
                HapticFeedback::ImpactMedium,
                HapticFeedback::ImpactHeavy,
                HapticFeedback::Selection,
                HapticFeedback::ImpactLight,
                HapticFeedback::ImpactMedium,
                HapticFeedback::ImpactHeavy,
                HapticFeedback::ImpactHeavy,
            ]
        );
    }

    #[test]
    fn provide_haptics_publishes_the_platform_backend() {
        clear_platform_haptics();
        let backend = Rc::new(Rec::default());
        let haptics: HapticsRef = backend.clone();
        set_platform_haptics(haptics);

        run_test_composition(move || {
            ProvideHaptics(|| {
                local_haptics().current().perform(HapticFeedback::Success);
            });
        });

        assert_eq!(*backend.events.borrow(), vec![HapticFeedback::Success]);
        clear_platform_haptics();
    }
}