rust_widgets 2.8.2

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! SignaturePad widget — a touch-friendly freehand drawing surface.
//!
//! Captures pen strokes as a list of [`SignatureStroke`]s, each a polyline of
//! [`Point`]s. A stroke is in progress between a press and the matching release,
//! and every move appends a point. Optional smoothing collapses near-duplicate
//! points so a jittery finger produces a clean line rather than a cloud of
//! specks. The pad supports undo, clear, and export to a plain point list.

use crate::compat::Instant;
use crate::core::{Color, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::{GenericSignal, Signal1};
use crate::widget::capability::coercion::{expect_f64, expect_usize};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

/// A single continuous pen stroke, stored as a polyline of points.
#[derive(Debug, Clone, PartialEq)]
pub struct SignatureStroke {
    points: Vec<Point>,
}

impl SignatureStroke {
    /// Creates an empty stroke.
    pub fn new() -> Self {
        Self { points: Vec::new() }
    }

    /// Creates a stroke from a list of points.
    pub fn from_points(points: Vec<Point>) -> Self {
        Self { points }
    }

    /// Appends a point to the stroke.
    pub fn push(&mut self, point: Point) {
        self.points.push(point);
    }

    /// Returns the stroke's points.
    pub fn points(&self) -> &[Point] {
        &self.points
    }

    /// Returns the number of points in the stroke.
    pub fn len(&self) -> usize {
        self.points.len()
    }

    /// Returns true when the stroke has no points.
    pub fn is_empty(&self) -> bool {
        self.points.is_empty()
    }
}

impl Default for SignatureStroke {
    fn default() -> Self {
        Self::new()
    }
}

/// A touch-friendly signature capture surface.
///
/// A drag (press → move → release) records one stroke on top of the previous
/// ones. The last stroke can be undone, or the whole pad cleared. `changed`
/// fires whenever the stroke set changes, and `stroke_count` reflects the
/// current total.
pub struct SignaturePad {
    base: BaseWidget,
    strokes: Vec<SignatureStroke>,
    current: Option<SignatureStroke>,
    stroke_color: Color,
    stroke_width: u32,
    /// Minimum distance, in pixels, a new point must be from the previous one
    /// before it is recorded. Points closer than this are dropped.
    min_point_distance: f32,
    /// Minimum time, in milliseconds, between recorded points.
    ///
    /// # Why distance alone was not enough
    ///
    /// A distance-only filter has no way to tell "the pointer is moving slowly and
    /// has already produced enough points" from "the pointer is moving fast and has
    /// produced too few". Sampling a fast stroke at one point per input event left
    /// every segment long, so a curve drawn quickly came out as a **polygon**: the
    /// pad recorded where the pointer *was*, never where it *went*. Time is the
    /// missing dimension -- a point is now recorded when it is far enough away *or*
    /// when enough time has passed, and a gap wider than this interval is filled by
    /// interpolating along the segment so the curve is smooth at any speed.
    min_point_interval_ms: u64,
    /// When the most recently recorded point was taken, from the OS monotonic clock.
    ///
    /// `None` until a stroke begins. The clock is read *inside* the widget when a
    /// pointer event arrives (see [`Self::extend_stroke`]): the event payloads carry
    /// position, pressure and tilt but no time, and a drawing surface must not
    /// acquire a network dependency for a value the operating system already
    /// provides. A network timestamp answers a different question -- *provenance*,
    /// "when was this signed" -- which is the caller's to attach and must not gate
    /// whether ink can be drawn.
    last_point_at: Option<Instant>,
    /// Emitted with no payload whenever the committed stroke set changes.
    pub changed: GenericSignal,
    /// Emitted with the final stroke when a drag is released and committed.
    pub stroke_completed: Signal1<SignatureStroke>,
}

impl SignaturePad {
    /// Creates an empty signature pad.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::SignaturePad, geometry, "SignaturePad"),
            strokes: Vec::new(),
            current: None,
            stroke_color: Color::rgb(20, 20, 20),
            stroke_width: 2,
            min_point_distance: 1.5,
            min_point_interval_ms: 10,
            last_point_at: None,
            changed: GenericSignal::new(),
            stroke_completed: Signal1::new(),
        }
    }

    /// Returns the committed strokes (excluding any in-progress stroke).
    pub fn strokes(&self) -> &[SignatureStroke] {
        &self.strokes
    }

    /// Returns the total number of committed strokes.
    pub fn stroke_count(&self) -> usize {
        self.strokes.len()
    }

    /// Returns true when the pad has no committed strokes.
    pub fn is_empty(&self) -> bool {
        self.strokes.is_empty()
    }

    /// Removes the most recently committed stroke, returning whether one was
    /// removed. Emits `changed` when a stroke is actually removed.
    pub fn undo(&mut self) -> bool {
        if self.strokes.pop().is_some() {
            self.changed.emit();
            self.base.request_redraw();
            true
        } else {
            false
        }
    }

    /// Removes every committed stroke. Emits `changed`.
    pub fn clear(&mut self) {
        if !self.strokes.is_empty() {
            self.strokes.clear();
            self.current = None;
            // The interval is measured from the last recorded point, so clearing must
            // forget it too -- otherwise the next stroke's first move is compared
            // against a moment that belongs to a stroke no longer on the pad.
            self.last_point_at = None;
            self.changed.emit();
            self.base.request_redraw();
        }
    }

    /// Returns the pen stroke color.
    pub fn stroke_color(&self) -> Color {
        self.stroke_color
    }

    /// Sets the pen stroke color and requests a redraw.
    pub fn set_stroke_color(&mut self, color: Color) {
        self.stroke_color = color;
        self.base.request_redraw();
    }

    /// Returns the pen stroke width in pixels.
    pub fn stroke_width(&self) -> u32 {
        self.stroke_width
    }

    /// Sets the pen stroke width, floored at 1, and requests a redraw.
    pub fn set_stroke_width(&mut self, width: u32) {
        self.stroke_width = width.max(1);
        self.base.request_redraw();
    }

    /// Returns the minimum distance between recorded points, in pixels.
    pub fn min_point_distance(&self) -> f32 {
        self.min_point_distance
    }

    /// Sets the minimum distance between recorded points. Values below 0 collapse
    /// to 0 (every point is recorded).
    pub fn set_min_point_distance(&mut self, distance: f32) {
        self.min_point_distance = distance.max(0.0);
    }

    /// Returns the minimum interval between recorded points, in milliseconds.
    ///
    /// This is the time half of the sampling rule; see
    /// [`Self::set_min_point_interval_ms`] for why distance alone polygonised fast
    /// strokes.
    pub fn min_point_interval_ms(&self) -> u64 {
        self.min_point_interval_ms
    }

    /// Sets the minimum interval between recorded points, in **milliseconds**.
    ///
    /// A point is recorded when it is at least [`Self::min_point_distance`] from the
    /// last one **or** at least this long after it, and a gap wider than this
    /// interval is subdivided by interpolation so a fast stroke stays a curve
    /// rather than becoming a polygon.
    ///
    /// `0` records every input event, which is the pre-existing behaviour of a pad
    /// with no smoothing; there is no upper bound because the interval only ever
    /// makes the pad *sparser*, and a caller asking for a very long one is asking
    /// for a deliberately coarse capture.
    pub fn set_min_point_interval_ms(&mut self, interval_ms: u64) {
        self.min_point_interval_ms = interval_ms;
    }

    /// Exports every committed stroke's points as a flat list, each stroke
    /// followed by a `(-1, -1)` sentinel so the caller can reconstruct stroke
    /// boundaries from a single vector.
    pub fn export_polylines(&self) -> Vec<Point> {
        let mut out = Vec::new();
        for stroke in &self.strokes {
            out.extend_from_slice(stroke.points());
            out.push(Point::new(-1, -1));
        }
        out
    }

    fn in_progress(&self) -> bool {
        self.current.is_some()
    }

    fn begin_stroke(&mut self, point: Point) {
        let mut stroke = SignatureStroke::new();
        stroke.push(point);
        self.current = Some(stroke);
        // The clock starts with the stroke, so the first interval is measured
        // against the press rather than against whenever a pointer last moved.
        self.last_point_at = Some(Instant::now());
    }

    fn extend_stroke(&mut self, point: Point) {
        // The clock is read once, before the borrow of `self.current`, so the event's
        // arrival time is a fact about this call rather than about the point's fate.
        let now = Instant::now();
        let elapsed_ms = self
            .last_point_at
            .map(|last| now.saturating_duration_since(last).as_millis() as u64)
            // A move with no press behind it (a synthetic event, or a stroke removed
            // under the pointer) has no interval to measure; treating it as `0` keeps
            // the point on the distance rule rather than fabricating a timestamp.
            .unwrap_or(0);
        // Read out as values before the mutable borrow of `self.current` below, so the
        // sampling rule and its resolution are snapshots of this call rather than reads
        // through a borrow that outlives them.
        let min_distance = self.min_point_distance;
        let min_interval_ms = self.min_point_interval_ms;

        let Some(current) = self.current.as_mut() else {
            return;
        };
        let Some(last) = current.points().last().copied() else {
            // A stroke always begins with a point, but a caller-built empty `current`
            // must not silently swallow the move.
            current.push(point);
            self.last_point_at = Some(now);
            self.base.request_redraw();
            return;
        };

        let dx = (point.x - last.x) as f32;
        let dy = (point.y - last.y) as f32;
        let distance = (dx * dx + dy * dy).sqrt();
        let far_enough = distance >= min_distance;
        let long_enough = elapsed_ms >= min_interval_ms;
        if !far_enough && !long_enough {
            // Too close *and* too soon: this is the jitter the smoothing exists to
            // drop. The clock is deliberately **not** advanced, so the interval is
            // measured against the last point actually recorded rather than against
            // the last event seen -- otherwise a stream of dropped jitter would keep
            // pushing the next accepted point further away.
            return;
        }

        // A long gap is filled in rather than cut across. This is the half that makes
        // a fast stroke smooth: without it, a pointer that travelled 60 px between
        // two events would deposit two points and the pad would draw one straight
        // edge, which is the polygonisation this control was reported for.
        if distance > min_distance && min_interval_ms > 0 {
            for step in interpolation_steps(last, point, distance, min_distance) {
                current.push(step);
            }
        }
        current.push(point);
        self.last_point_at = Some(now);
        self.base.request_redraw();
    }

    fn end_stroke(&mut self) {
        let Some(stroke) = self.current.take() else {
            return;
        };
        // A single-point stroke still counts: it is a tap, which for a signature
        // pad is a legitimate dot.
        self.strokes.push(stroke.clone());
        self.stroke_completed.emit(stroke);
        self.changed.emit();
        self.base.request_redraw();
    }
}

impl Widget for SignaturePad {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }

    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> crate::core::Size {
        crate::core::Size::new(320, 160)
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `SignaturePad`'s property contract.
impl WidgetProperties for SignaturePad {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "stroke_count" => Ok(CapabilityValue::UInt(self.stroke_count() as u64)),
            "stroke_width" => Ok(CapabilityValue::UInt(self.stroke_width() as u64)),
            "stroke_color" => Ok(CapabilityValue::Color(self.stroke_color())),
            "min_point_distance" => Ok(CapabilityValue::Float(self.min_point_distance() as f64)),
            "min_point_interval_ms" => Ok(CapabilityValue::UInt(self.min_point_interval_ms())),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "stroke_count" => Err(CapabilityAccessError::ReadOnlyProperty),
            "stroke_width" => {
                self.set_stroke_width(expect_usize(value)? as u32);
                Ok(())
            }
            "stroke_color" => match value {
                CapabilityValue::Color(color) => {
                    self.set_stroke_color(color);
                    Ok(())
                }
                _ => Err(CapabilityAccessError::TypeMismatch),
            },
            "min_point_distance" => {
                self.set_min_point_distance(expect_f64(value)? as f32);
                Ok(())
            }
            "min_point_interval_ms" => {
                self.set_min_point_interval_ms(expect_usize(value)? as u64);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of![
            "stroke_count",
            "stroke_width",
            "stroke_color",
            "min_point_distance",
            "min_point_interval_ms",
            BASE_PROPERTY_NAMES
        ]
    }

    fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
        match name {
            "undo" => {
                let _ = self.undo();
                Ok(())
            }
            _ => Err(CapabilityAccessError::UnknownCommand),
        }
    }
}

impl EventHandler for SignaturePad {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
        if !self.base.is_enabled() {
            return;
        }
        let rect = self.geometry();
        match event {
            Event::MousePress { pos, button: 1 } if rect.contains_point(*pos) => {
                self.begin_stroke(*pos);
            }
            #[cfg(feature = "touch")]
            Event::TouchBegin { pos, .. } if rect.contains_point(*pos) => {
                self.begin_stroke(*pos);
            }
            Event::MouseMove { pos } | Event::PointerMove { pos, .. } if self.in_progress() => {
                self.extend_stroke(*pos);
            }
            #[cfg(feature = "touch")]
            Event::TouchMove { pos, .. } if self.in_progress() => {
                self.extend_stroke(*pos);
            }
            Event::MouseRelease { .. } if self.in_progress() => {
                self.end_stroke();
            }
            #[cfg(feature = "touch")]
            Event::TouchEnd { .. } if self.in_progress() => {
                self.end_stroke();
            }
            _ => { /* Other events are not relevant */ }
        }
    }
}

impl Draw for SignaturePad {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();

        // The pad surface, its frame, and the empty-state baseline are chrome, so
        // they resolve explicit style first, then the theme's resolved style for
        // this control, and only then a literal. Without the theme step the pad
        // stayed white in both appearances and a switch changed nothing.
        //
        // `self.stroke_color` is deliberately *not* themed: it is the caller's
        // configured ink, which the `stroke_color` property writes, so the caller's
        // value must win over anything the theme says.
        //
        // `resolved_theme_style` takes and releases the global manager's lock
        // internally, so no guard is held across the draw (the mutex is not
        // re-entrant).
        let style = self.base.style().clone();
        let theme = crate::style::resolved_theme_style("signature_pad");
        // `signature_pad` is absent from `WidgetRole::for_kind_name`'s table, so it classifies
        // as `Surface` and resolves to `theme.colors.background` — the window's own fill. A pad
        // filled with that colour is byte-identical to the frame behind it, which is why
        // `signature_pad.svg` showed only the baseline and the two `rgba(18,18,18)` rectangles
        // were indistinguishable. The fill is therefore derived one step from the window fill
        // for a `Base`/`Input`-style face, so the writing area reads as a well the ink sits in.
        // A colour the caller set explicitly still wins: it is a deliberate choice, not the
        // window fill arriving through the resolver.
        let window_fill = {
            let manager = crate::style::theme_manager();
            manager.current_theme().map(|active| active.colors.background).unwrap_or(Color::WHITE)
        };
        let text_color = style
            .text_color
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or(Color::BLACK);
        let background = match style
            .background_color
            .or_else(|| theme.as_ref().and_then(|t| t.background_color))
        {
            Some(resolved) if resolved != window_fill => resolved,
            _ => window_fill.blend(&text_color, 0.10),
        };
        let border = style
            .border_color
            .or_else(|| theme.as_ref().and_then(|t| t.border_color))
            .filter(|resolved| *resolved != background)
            .unwrap_or_else(|| background.blend(&text_color, 0.35));
        // The hint line is secondary chrome: derived from the resolved colours so it
        // stays visible against either surface.
        let hint = background.blend(&text_color, 0.4);

        context.face(
            rect,
            background,
            self.style().surface.unwrap_or_default(),
            self.style().border_radius.unwrap_or(0),
            Color::BLACK,
        );
        context.draw_rect(rect, border);

        // Draw committed strokes.
        for stroke in &self.strokes {
            draw_stroke(context, stroke, self.stroke_color, self.stroke_width);
        }
        // Draw the in-progress stroke on top.
        if let Some(current) = &self.current {
            draw_stroke(context, current, self.stroke_color, self.stroke_width);
        }

        // Empty-state hint: a baseline that reads like a signature line.
        if self.strokes.is_empty() && self.current.is_none() {
            let mid_y = rect.y + rect.height as i32 / 2;
            let inset = rect.width as i32 / 6;
            context.draw_line_stroke(
                Point::new(rect.x + inset, mid_y),
                Point::new(rect.x + rect.width as i32 - inset, mid_y),
                hint,
                1,
            );
        }
    }
}

/// The intermediate points to lay between `from` and `to` so that no drawn segment is
/// longer than `min_distance`.
///
/// The count is `ceil(distance / min_distance) - 1`, which spaces the inserted points at
/// the same resolution the pad accepts directly: a slow stroke and a fast one therefore
/// produce strokes of the **same** geometric fidelity, which is the property the old
/// distance-only rule could not express. When `min_distance` is `0` there is no resolution
/// to honour and nothing is inserted.
///
/// # Why a free function
///
/// It is called from the one place that appends to a stroke, and it reads nothing from the
/// widget: taking the threshold as a parameter is what lets the caller hold a mutable
/// borrow of the stroke while the count is computed, and it makes the spacing rule testable
/// without constructing a pad.
fn interpolation_steps(from: Point, to: Point, distance: f32, min_distance: f32) -> Vec<Point> {
    if min_distance <= 0.0 || !distance.is_finite() || !min_distance.is_finite() {
        return Vec::new();
    }
    let steps = (distance / min_distance).ceil() as usize;
    if steps <= 1 {
        return Vec::new();
    }
    let mut out = Vec::with_capacity(steps - 1);
    for i in 1..steps {
        let t = i as f32 / steps as f32;
        out.push(Point::new(
            from.x + ((to.x - from.x) as f32 * t).round() as i32,
            from.y + ((to.y - from.y) as f32 * t).round() as i32,
        ));
    }
    out
}

/// Draws a single stroke as a connected polyline.
fn draw_stroke(context: &mut RenderContext, stroke: &SignatureStroke, color: Color, width: u32) {
    let points = stroke.points();
    match points.len() {
        0 => {}
        1 => {
            // A single point renders as a dot.
            context.draw_line_stroke_aa(points[0], points[0], color, width.max(2));
        }
        _ => {
            for pair in points.windows(2) {
                context.draw_line_stroke_aa(pair[0], pair[1], color, width);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    };

    fn pad() -> SignaturePad {
        SignaturePad::new(Rect::new(0, 0, 320, 160))
    }

    #[test]
    fn new_pad_is_empty() {
        let p = pad();
        assert!(p.is_empty());
        assert_eq!(p.stroke_count(), 0);
        assert!(p.strokes().is_empty());
    }

    #[test]
    fn a_press_move_release_records_one_stroke() {
        let mut p = pad();
        p.handle_event(&Event::mouse_press(10, 20, 1));
        p.handle_event(&Event::mouse_move(30, 40));
        p.handle_event(&Event::mouse_move(60, 50));
        p.handle_event(&Event::mouse_release(60, 50, 1));

        assert_eq!(p.stroke_count(), 1);
        assert!(!p.is_empty());
        // The **ends** are asserted rather than the length: the moves above are 20 and ~30 px
        // apart, so they are now filled in by interpolation and the count is a function of the
        // distance threshold, not of how many events arrived. What must not change is that the
        // stroke begins at the press and ends at the release.
        let stroke = &p.strokes()[0];
        assert_eq!(stroke.points()[0], Point::new(10, 20));
        assert_eq!(stroke.points().last().copied(), Some(Point::new(60, 50)));
        assert!(stroke.len() >= 3, "the real points survive interpolation");
    }

    #[test]
    fn smoothing_drops_near_duplicate_points() {
        let mut p = pad();
        p.handle_event(&Event::mouse_press(10, 20, 1));
        // Two near-identical points: both within the 1.5px threshold of the
        // previous point, so neither is recorded.
        p.handle_event(&Event::mouse_move(10, 20));
        p.handle_event(&Event::mouse_move(10, 21));
        p.handle_event(&Event::mouse_release(10, 21, 1));

        let stroke = &p.strokes()[0];
        // Only the starting press survived; the near-duplicate moves were dropped.
        assert_eq!(stroke.len(), 1);
        assert_eq!(stroke.points()[0], Point::new(10, 20));
    }

    /// `interpolation_steps` spaces inserted points at the pad's own resolution.
    ///
    /// The count is asserted exactly, because the *rule* is the point: `ceil(d / min) - 1`
    /// inserted points is what makes a fast stroke and a slow one land at the same fidelity.
    #[test]
    fn interpolation_spaces_points_at_the_pads_own_resolution() {
        // 10 px at a 1.5 px threshold: `ceil(10 / 1.5) = 7` steps, so 6 inserted points, the
        // first at `t = 1/7` (x = 1.43 -> 1) and the last at `t = 6/7` (x = 8.57 -> 9).
        let steps = interpolation_steps(Point::new(0, 0), Point::new(10, 0), 10.0, 1.5);
        assert_eq!(steps.len(), 6);
        assert_eq!(steps[0], Point::new(1, 0));
        assert_eq!(steps[5], Point::new(9, 0));

        // A hop shorter than the threshold has no interior to fill.
        assert!(interpolation_steps(Point::new(0, 0), Point::new(1, 0), 1.0, 1.5).is_empty());

        // A zero threshold means "no resolution to honour", not "divide by zero".
        assert!(interpolation_steps(Point::new(0, 0), Point::new(100, 0), 100.0, 0.0).is_empty());
    }

    /// The interval rule accepts a point that has not moved, once enough time has passed.
    ///
    /// This is the half the old distance-only rule could not express, and the reason a
    /// **stationary** pen still produces a record of how long it rested there.
    #[test]
    fn a_stationary_point_is_recorded_once_the_interval_passes() {
        let mut p = pad();
        // Nothing moves, so the default 10 ms interval is what admits the second point. The
        // test sleeps rather than scaling time, because the clock is the OS's and the point of
        // the rule is that it reads that clock.
        p.handle_event(&Event::mouse_press(10, 20, 1));
        std::thread::sleep(std::time::Duration::from_millis(25));
        p.handle_event(&Event::mouse_move(10, 20));

        let current_points = p.current.as_ref().expect("a stroke is in progress").len();
        assert_eq!(
            current_points, 2,
            "a point held in place past the interval must be recorded, so a pause is visible \
             in the stroke rather than being silently swallowed"
        );
    }

    /// The interval rule can be switched off, restoring the pre-existing distance-only
    /// behaviour, and setting it is reflected by the capability contract.
    #[test]
    fn the_interval_is_configurable_and_reported() {
        let mut p = pad();
        assert_eq!(p.min_point_interval_ms(), 10, "the shipped default");
        p.set_min_point_interval_ms(0);
        assert_eq!(p.min_point_interval_ms(), 0);
        assert_eq!(p.get("min_point_interval_ms").expect("readable"), CapabilityValue::UInt(0));
        p.set("min_point_interval_ms", CapabilityValue::UInt(40)).expect("writable");
        assert_eq!(p.min_point_interval_ms(), 40);
    }

    #[test]
    fn undo_and_clear_work() {
        let mut p = pad();
        p.handle_event(&Event::mouse_press(10, 20, 1));
        p.handle_event(&Event::mouse_release(10, 20, 1));
        assert_eq!(p.stroke_count(), 1);

        assert!(p.undo());
        assert_eq!(p.stroke_count(), 0);
        assert!(!p.undo()); // nothing left to undo

        p.handle_event(&Event::mouse_press(10, 20, 1));
        p.handle_event(&Event::mouse_release(10, 20, 1));
        assert_eq!(p.stroke_count(), 1);
        p.clear();
        assert!(p.is_empty());
    }

    #[test]
    fn changed_and_stroke_completed_signals_fire() {
        let mut p = pad();
        let changed = Arc::new(AtomicUsize::new(0));
        let c = changed.clone();
        p.changed.connect(move || {
            c.fetch_add(1, Ordering::SeqCst);
        });

        let completed = Arc::new(AtomicUsize::new(0));
        let cc = completed.clone();
        p.stroke_completed.connect(move |_| {
            cc.fetch_add(1, Ordering::SeqCst);
        });

        p.handle_event(&Event::mouse_press(10, 20, 1));
        p.handle_event(&Event::mouse_release(10, 20, 1));
        assert_eq!(changed.load(Ordering::SeqCst), 1);
        assert_eq!(completed.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn export_polylines_emits_sentinels() {
        let mut p = pad();
        p.handle_event(&Event::mouse_press(10, 20, 1));
        p.handle_event(&Event::mouse_move(30, 40));
        p.handle_event(&Event::mouse_release(30, 40, 1));
        p.handle_event(&Event::mouse_press(50, 60, 1));
        p.handle_event(&Event::mouse_release(50, 60, 1));

        let flat = p.export_polylines();
        // The structure is what this test is about: two strokes, each terminated by a sentinel.
        // The stroke lengths are a function of the distance threshold now that moves are
        // interpolated, so they are read back rather than hardcoded.
        let first = p.strokes()[0].len();
        let second = p.strokes()[1].len();
        assert_eq!(flat.len(), first + 1 + second + 1);
        assert_eq!(flat[first], Point::new(-1, -1));
        assert_eq!(flat[first + 1 + second], Point::new(-1, -1));
    }

    #[test]
    #[cfg(feature = "touch")]
    fn touch_events_record_strokes_too() {
        let mut p = pad();
        p.handle_event(&crate::event::Event::touch_begin(5, 5, 1));
        p.handle_event(&crate::event::Event::touch_move(40, 40, 1));
        p.handle_event(&crate::event::Event::touch_end(40, 40, 1));
        assert_eq!(p.stroke_count(), 1);
    }

    #[test]
    fn stroke_width_is_floored_at_one() {
        let mut p = pad();
        p.set_stroke_width(0);
        assert_eq!(p.stroke_width(), 1);
    }

    #[test]
    fn disabled_pad_ignores_input() {
        let mut p = pad();
        p.set_enabled(false);
        p.handle_event(&Event::mouse_press(10, 20, 1));
        p.handle_event(&Event::mouse_release(10, 20, 1));
        assert!(p.is_empty());
    }
}