rust_widgets 2.9.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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! CupertinoSegmentedControl — iOS-style segmented control.
//!
//! A pill-shaped container with horizontally arranged segments. The selected
//! segment has a sliding highlight. Clicking a segment selects it and emits
//! a `value_changed` signal with the segment index.

use crate::compat::Cow;
use crate::core::{Color, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::style::{MotionSlot, PropertyDriver};
use crate::widget::capability::coercion::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::metrics::{dimensions, role_font, ControlMetrics};
use crate::widget::text_utils::elide_to_width;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

/// A segment's content: a caption and an optional icon name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CupertinoSegment {
    /// The caption shown in the segment.
    pub label: String,
    /// An optional icon name, resolved as a bundled glyph when one matches.
    pub icon: Option<String>,
    /// Whether the segment can be selected; a disabled segment paints in disabled ink and
    /// ignores taps.
    pub enabled: bool,
}

impl CupertinoSegment {
    /// A segment with a caption and no icon.
    pub fn new(label: impl Into<String>) -> Self {
        Self { label: label.into(), icon: None, enabled: true }
    }

    /// The same segment with an icon name attached.
    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
        self.icon = Some(icon.into());
        self
    }

    /// The same segment, disabled.
    pub fn disabled(mut self) -> Self {
        self.enabled = false;
        self
    }
}

/// How the selected segment is painted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SegmentTint {
    /// A white thumb on the grey track, which is the iOS 13+ appearance and the default.
    #[default]
    WhiteThumb,
    /// The theme's accent colour, which is the older Material-flavoured appearance.
    Accent,
}

/// iOS-style segmented control.
///
/// Displays a pill-shaped container with horizontally arranged text segments.
/// The selected segment is highlighted with a sliding white indicator.
/// Emits `value_changed` when the user clicks a segment.
pub struct CupertinoSegmentedControl {
    base: BaseWidget,
    segments: Vec<String>,
    selected_index: usize,
    /// How far the highlight has travelled, `0.0` just after leaving its segment and `1.0` arrived.
    ///
    /// # Why the doc and the code disagreed for a while
    ///
    /// The module doc has always said "a **sliding** highlight", and the draw path computed the
    /// indicator's x straight from `selected_index` — so the promise was in the prose and the
    /// teleport was in the pixels. The indicator now interpolates between the segment it left and
    /// the one it is heading for, which is what the doc claimed all along.
    ///
    /// A 0..=1 fraction rather than a pixel offset, because a `PropertyDriver` interpolates a
    /// progress (it clamps its target to that range), and because a fraction survives a relayout
    /// that moves every segment.
    slide: PropertyDriver,
    /// The segment the current slide started from, so `slide`'s fraction has a left endpoint.
    slide_from: usize,
    /// Per-segment icon names, parallel to `segments`.
    segment_icons: Vec<Option<String>>,
    /// Per-segment enabled flags, parallel to `segments`.
    segment_enabled: Vec<bool>,
    /// How the selected segment is painted.
    tint: SegmentTint,
    /// Emitted when the selected segment changes with the new index.
    pub value_changed: Signal1<usize>,
}

impl CupertinoSegmentedControl {
    /// Creates a new CupertinoSegmentedControl with the given geometry.
    pub fn new(geometry: Rect) -> Self {
        let base = BaseWidget::new(
            WidgetKind::CupertinoSegmentedControl,
            geometry,
            "CupertinoSegmentedControl",
        );
        Self {
            base,
            segments: Vec::new(),
            selected_index: 0,
            // At rest on segment 0: `slide == 1.0` means "arrived", not "just left".
            slide: PropertyDriver::at(1.0, MotionSlot::Normal),
            slide_from: 0,
            segment_icons: Vec::new(),
            segment_enabled: Vec::new(),
            tint: SegmentTint::WhiteThumb,
            value_changed: Signal1::new(),
        }
    }

    /// Sets the segment labels, replacing all existing segments.
    /// Resets selection to 0 if the new list is non-empty.
    pub fn set_segments(&mut self, segments: Vec<String>) {
        self.segment_icons.clear();
        self.segment_icons.resize(segments.len(), None);
        self.segment_enabled.clear();
        self.segment_enabled.resize(segments.len(), true);
        self.segments = segments;
        if self.selected_index >= self.segments.len().max(1) {
            self.selected_index = if self.segments.is_empty() {
                0
            } else {
                self.selected_index.min(self.segments.len() - 1)
            };
        }
        // A rebuilt segment set is a reset, not a selection change: the highlight starts on the
        // segment it is on rather than animating out of the old set.
        self.slide_from = self.selected_index;
        self.slide.jump_to(1.0);
        self.base.request_redraw();
    }

    /// Replaces the segments with caption + optional icon items.
    pub fn set_segment_items(&mut self, segments: Vec<CupertinoSegment>) {
        self.segments = segments.iter().map(|segment| segment.label.clone()).collect();
        self.segment_icons = segments.iter().map(|segment| segment.icon.clone()).collect();
        self.segment_enabled = segments.iter().map(|segment| segment.enabled).collect();
        if self.selected_index >= self.segments.len().max(1) {
            self.selected_index = if self.segments.is_empty() {
                0
            } else {
                self.selected_index.min(self.segments.len() - 1)
            };
        }
        self.slide_from = self.selected_index;
        self.slide.jump_to(1.0);
        self.base.request_redraw();
    }

    /// Returns the icon name of segment `index`.
    pub fn segment_icon(&self, index: usize) -> Option<&str> {
        self.segment_icons.get(index).and_then(|icon| icon.as_deref())
    }

    /// Whether segment `index` can be selected; an out-of-range index is treated as disabled.
    pub fn is_segment_enabled(&self, index: usize) -> bool {
        self.segment_enabled.get(index).copied().unwrap_or(false)
    }

    /// Enables or disables one segment, returning whether the index exists.
    pub fn set_segment_enabled(&mut self, index: usize, enabled: bool) -> bool {
        let Some(slot) = self.segment_enabled.get_mut(index) else {
            return false;
        };
        if *slot == enabled {
            return true;
        }
        *slot = enabled;
        self.base.request_redraw();
        true
    }

    /// Returns how the selected segment is painted.
    pub fn tint(&self) -> SegmentTint {
        self.tint
    }

    /// Sets how the selected segment is painted.
    pub fn set_tint(&mut self, tint: SegmentTint) {
        if self.tint == tint {
            return;
        }
        self.tint = tint;
        self.base.request_redraw();
    }

    /// Returns a reference to the segment labels.
    pub fn segments(&self) -> &[String] {
        &self.segments
    }

    /// Sets the selected segment index. Clamped to valid range.
    pub fn set_selected_index(&mut self, index: usize) {
        if self.segments.is_empty() {
            self.selected_index = 0;
            return;
        }
        let clamped = index.min(self.segments.len() - 1);
        if clamped != self.selected_index {
            // Re-aim from the highlight's **fractional** position, not from a rounded segment: a tap
            // that lands while the pill is still travelling must resume from where it is, or the
            // highlight visibly jumps backwards first.
            let position = self.indicator_position();
            self.slide_from = position.floor().max(0.0) as usize;
            let from = self.slide_from as f32;
            let to = clamped as f32;
            let fraction = if (to - from).abs() < f32::EPSILON {
                1.0
            } else {
                ((position - from) / (to - from)).clamp(0.0, 1.0)
            };
            self.selected_index = clamped;
            self.slide.jump_to(fraction);
            self.slide.set_target(1.0);
            self.value_changed.emit(clamped);
            self.base.request_redraw();
        }
    }

    /// Returns the currently selected index.
    pub fn selected_index(&self) -> Option<usize> {
        if self.segments.is_empty() {
            None
        } else {
            Some(self.selected_index.min(self.segments.len() - 1))
        }
    }

    /// The segment index the highlight is currently drawn at, as a **fractional** value.
    ///
    /// Strictly between two whole indices while the highlight is travelling, which is exactly what
    /// "the indicator slid rather than jumped" means; an animation test samples it per frame.
    pub fn indicator_position(&self) -> f32 {
        let from = self.slide_from as f32;
        let to = self.selected_index as f32;
        from + (to - from) * self.slide.value()
    }

    /// Advances the highlight's slide by `delta_ms`; `true` while it is still moving.
    pub fn tick(&mut self, delta_ms: u32) -> bool {
        self.slide.tick(delta_ms)
    }

    /// Whether the highlight is between two segments -- answers only, never advances.
    pub fn is_animating(&self) -> bool {
        self.slide.is_moving()
    }

    /// Returns the number of segments.
    pub fn segment_count(&self) -> usize {
        self.segments.len()
    }

    /// The track the control actually paints: full width,
    /// `dimensions::SEGMENTED_CONTROL_HEIGHT` tall, centred in the rectangle it was given.
    ///
    /// # Why the track is not the rectangle
    ///
    /// A segmented control's chrome is one row of segments. Taking `rect.height` made a
    /// 240x120 census cell a **240x120 stadium**, and it disagreed with the 32 px `size_hint`
    /// the control reports. The band is the single derivation the paint and the hit test share.
    fn track_band(&self) -> Rect {
        ControlMetrics::full_width_band(self.geometry(), dimensions::SEGMENTED_CONTROL_HEIGHT)
    }
}

impl Widget for CupertinoSegmentedControl {
    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) -> Size {
        crate::core::Size::new(
            crate::widget::metrics::dimensions::CUPERTINO_SEGMENTED_DEFAULT_WIDTH,
            crate::widget::metrics::dimensions::SEGMENTED_CONTROL_HEIGHT,
        )
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::CupertinoSegmentedControl
    }

    // The highlight slide is the control's own animation; the trait spelling is what the frame bus
    // reaches through `&mut dyn Widget`, which is the only way the slide actually happens.
    fn tick(&mut self, delta_ms: u32) -> bool {
        CupertinoSegmentedControl::tick(self, delta_ms)
    }

    fn is_animating(&self) -> bool {
        CupertinoSegmentedControl::is_animating(self)
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
    /// Resolves a published event name to the control's own signal.
    ///
    /// # Why this is explicit
    ///
    /// `connect_event` validates a name against the capability table and registers a hub slot; only
    /// `event_signal_dyn` joins that name to the signal the control actually **emits**. Without an
    /// arm a published name is valid and inert, which is the silent failure
    /// `tools/check_event_signal_dyn.sh` exists to make impossible: the arm set is compared against
    /// the capability's published names, so the two cannot drift.
    fn event_signal_dyn(&self, name: &str) -> Option<crate::signal::EventSignalRef> {
        use crate::signal::EventSignalRef;
        match name {
            "value_changed" => {
                Some(EventSignalRef::mapped("value_changed", &self.value_changed, |v| {
                    CapabilityValue::UInt(*v as u64)
                }))
            }
            _ => None,
        }
    }
}

/// `CupertinoSegmentedControl`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_input.in.rs` / `access_write_input.in.rs` dispatch, so callers see
/// the same coercions and the same errors as before. `selected_index` reads the
/// control's real selection; `segment_count` is derived from the segment list and
/// has no setter, so writes are refused with
/// [`CapabilityAccessError::ReadOnlyProperty`].
impl WidgetProperties for CupertinoSegmentedControl {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "selected_index" => {
                Ok(CapabilityValue::UInt(self.selected_index().unwrap_or(0) as u64))
            }
            "segment_count" => Ok(CapabilityValue::UInt(self.segment_count() as u64)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "selected_index" => {
                self.set_selected_index(expect_usize(value)?);
                Ok(())
            }
            // Derived from the segment list, which owns it.
            "segment_count" => Err(CapabilityAccessError::ReadOnlyProperty),
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["selected_index", "segment_count", BASE_PROPERTY_NAMES]
    }
}

impl Draw for CupertinoSegmentedControl {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();
        if rect.width == 0 || rect.height == 0 {
            return;
        }

        let seg_count = self.segments.len();
        // ── The track actually painted ──
        //
        // `rect` is the area the control was *given*; the control's own chrome is one row of
        // segments, `dimensions::SEGMENTED_CONTROL_HEIGHT` tall and centred. Painting the
        // track across the whole rectangle made a 240x120 census cell a bare 240x120 stadium
        // with no segment division in it — the defect this replaces — and it disagreed with the
        // 32 px size the control reports. A control with no segments still paints its track,
        // which is what keeps a freshly constructed control visible; that track is now the
        // fixed-height pill rather than the whole canvas.
        let track_rect = self.track_band();
        let seg_w = if seg_count == 0 {
            track_rect.width as i32
        } else {
            track_rect.width as i32 / seg_count as i32
        };
        let corner_radius = track_rect.height / 2;

        // Chrome colours resolve explicit style first, then the theme's resolved style for
        // this control, and only then fall back to a literal. Every colour below used to be
        // a literal, so a light/dark switch left the pill, its indicator and its labels
        // unchanged — the rendering census reported the control as theme-blind.
        //
        // The theme read is a separate manager lock, taken and released inside
        // `resolved_theme_style`, so it is not held across the draw — the global manager's
        // mutex is not re-entrant.
        let style = self.base.style();
        let theme = crate::style::resolved_theme_style_shared("cupertino_segmented_control");
        // Read as its own lock acquisition and copied out as values, so the guard is dropped
        // before anything else touches the theme. The control is not in the role table, so it
        // classifies as `Surface` and its resolved background is the window fill itself; the
        // track below therefore derives its own distinct surface rather than painting the
        // window's. The selected segment is the control's value indicator, so its sliding
        // highlight reads the theme's primary.
        let (window_fill, foreground, primary) = {
            let manager = crate::style::theme_manager();
            match manager.current_theme() {
                Some(active) => {
                    (active.colors.background, active.colors.foreground, active.colors.primary)
                }
                None => (Color::rgb(240, 240, 240), Color::BLACK, Color::rgb(0, 122, 255)),
            }
        };

        let ink = style
            .text_color
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or(foreground);
        // The track: one step from the window fill toward the text colour, so the pill is a
        // distinct element on a light theme and on a dark one. The filter is on the
        // **resolved** value, not only on the theme's: the active theme is applied to every
        // control before it is drawn, so `style.background_color` already holds `Surface`'s
        // window fill and letting it through unfiltered is exactly the invisible-pill defect
        // this guards against. A caller's own colour still wins.
        let track_from_theme = window_fill.blend(&ink, 0.08);
        let track_surface = match style.background_color {
            Some(resolved) if resolved != window_fill => resolved,
            _ => track_from_theme,
        };
        // The slider's knob makes the same distinction between the track it sits on and the
        // page behind it: raised by default, recessed while disabled.
        let track_color = if self.base.is_enabled() {
            track_surface
        } else {
            track_surface.blend(&window_fill, 0.50)
        };
        context.fill_rounded_rect(track_rect, corner_radius, track_color);

        if seg_count == 0 {
            return;
        }

        // ── Sliding highlight for the selected segment ──
        // The accent marks the selection and is contrast-checked against the track so the
        // selected label stays legible on either appearance. A caller's explicit text colour
        // still wins.
        let selected_bg = match self.tint {
            SegmentTint::WhiteThumb => Color::WHITE,
            SegmentTint::Accent => primary.contrast_color().blend(&primary, 0.30),
        };
        let highlight_color = match self.tint {
            SegmentTint::WhiteThumb => selected_bg,
            SegmentTint::Accent => style.text_color.unwrap_or(selected_bg),
        };
        let indicator_color = if self.base.is_enabled() {
            highlight_color
        } else {
            highlight_color.blend(&track_color, 0.50)
        };
        // The highlight interpolates between the segment it left and the one it is heading for, so
        // the movement itself carries the information that the value changed. Derived through the
        // one accessor the animation test also samples, so the two cannot disagree.
        let position = self.indicator_position();
        let sel_x = track_rect.x + (position * seg_w as f32) as i32;
        let sel_rect = Rect::new(
            sel_x + 2,
            track_rect.y + 2,
            seg_w.saturating_sub(4) as u32,
            track_rect.height.saturating_sub(4),
        );
        context.fill_rounded_rect(sel_rect, corner_radius, indicator_color);

        // ── Segment labels ──
        // The label face is the **effective font** at its role size (D09-STYLE-01).
        let font = role_font(style, 13.0);
        // The unselected label is de-emphasised from the control's own ink rather than being
        // a fixed grey that a dark theme would render illegible.
        let unselected = ink.blend(&track_color, 0.45);
        for (i, seg) in self.segments.iter().enumerate() {
            let seg_x = track_rect.x + (i as i32) * seg_w;
            // The label must contrast with what it is painted on — the selected thumb for the
            // selected segment, the track for the rest — so the two are chosen against their
            // own backdrop instead of both assuming a light one.
            let color = if !self.base.is_enabled() || !self.is_segment_enabled(i) {
                self.base.disabled_ink_on(unselected, track_color)
            } else if i == self.selected_index {
                indicator_color.contrast_color()
            } else {
                unselected
            };
            // A segment may carry an icon, drawn in the leading half of its own box and
            // resolved through the same named-icon path every other control uses.
            let mut text_origin = seg_x;
            let mut text_width = seg_w;
            if let Some(icon) = self.segment_icons.get(i).and_then(|icon| icon.as_deref()) {
                let side = 14.min(track_rect.height.saturating_sub(8)).max(1);
                let icon_rect = Rect::new(
                    seg_x + 4,
                    track_rect.y + (track_rect.height as i32 - side as i32) / 2,
                    side,
                    side,
                );
                if crate::widget::draw_icon_named(context, icon_rect, color, icon) {
                    text_origin += side as i32 + 4;
                    text_width = text_width.saturating_sub((side + 8) as i32);
                }
            }
            // A label wider than its segment is elided rather than painted over its
            // neighbours. The shared primitive owns the budget and is measured with the
            // renderer's own callback, so the fitting decision and the painted advance come
            // from one metric; a label that fits is borrowed and keeps its old origin, which
            // the fitted draw's own inset would have shifted.
            let label = fitted_segment_label(seg, text_width, &mut |text: &str| {
                crate::widget::base_widgets::measure_cache::measure_text(context, text, &font).width
            });
            let metrics =
                crate::widget::base_widgets::measure_cache::measure_text(context, &label, &font);
            let text_x = text_origin + (text_width - metrics.width as i32) / 2;
            // Centre the label in its segment. The origin is the glyph box's top edge, so the
            // offset is half the *line box*; the old ascent/descent pair began the glyph box
            // half a line below the segment's middle.
            let text_y = track_rect.y + (track_rect.height as i32 - metrics.height as i32) / 2;
            context.draw_text(
                Point::new(text_x, text_y),
                &label,
                &font,
                color,
                HorizontalAlignment::Left,
            );
        }
    }
}

/// Elides `label` to the label band of a segment `segment_width` wide.
///
/// The band is the segment inset two points at each end, the same reservation the paint
/// path used to compute inline. `measure` is the renderer's advance measurement, so the
/// budget is the width the paint path will actually produce; a label that fits is returned
/// borrowed.
fn fitted_segment_label<'a>(
    label: &'a str,
    segment_width: i32,
    measure: &mut dyn FnMut(&str) -> u32,
) -> Cow<'a, str> {
    let budget = (segment_width - 4).max(0) as u32;
    elide_to_width(label, budget, measure)
}

impl EventHandler for CupertinoSegmentedControl {
    fn handle_event(&mut self, event: &Event) {
        match event {
            Event::MouseRelease { pos, button } => {
                // A disabled control must not change its selection. Without this the
                // `set_enabled(false)` API had no effect on this widget at all: the
                // click was still accepted and `value_changed` still fired.
                if !self.base.is_enabled() {
                    self.base.handle_event(event);
                    return;
                }
                if *button != 1 || self.segments.is_empty() {
                    return;
                }

                // The click is resolved against the same band the segments are painted in, so a
                // tap above or below the bar hits nothing rather than selecting a segment whose
                // ink is not there.
                let track_rect = self.track_band();
                let seg_w = track_rect.width as i32 / self.segments.len() as i32;
                if seg_w <= 0 {
                    return;
                }
                let rel_x = pos.x - track_rect.x;

                if rel_x < 0 || rel_x >= track_rect.width as i32 {
                    return;
                }
                if pos.y < track_rect.y || pos.y >= track_rect.y + track_rect.height as i32 {
                    return;
                }

                let index = (rel_x / seg_w) as usize;
                if index < self.segments.len()
                    && index != self.selected_index
                    && self.is_segment_enabled(index)
                {
                    // The click goes through the same setter the property path uses, so the
                    // highlight slides instead of jumping (MW-18).
                    self.set_selected_index(index);
                }
            }
            _ => {
                self.base.handle_event(event);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::widget::svg::render_to_svg;
    use std::sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    };

    #[test]
    fn cupertino_segmented_control_creation() {
        let sc = CupertinoSegmentedControl::new(Rect::new(0, 0, 300, 32));
        assert_eq!(sc.kind(), WidgetKind::CupertinoSegmentedControl);
        assert_eq!(sc.segment_count(), 0);
        assert_eq!(sc.selected_index().unwrap_or(0), 0);
    }

    #[test]
    fn cupertino_segmented_control_set_segments() {
        let mut sc = CupertinoSegmentedControl::new(Rect::new(0, 0, 300, 32));
        sc.set_segments(vec!["One".to_string(), "Two".to_string(), "Three".to_string()]);
        assert_eq!(sc.segment_count(), 3);
        assert_eq!(sc.selected_index().unwrap_or(0), 0);
    }

    #[test]
    fn cupertino_segmented_control_selection() {
        let mut sc = CupertinoSegmentedControl::new(Rect::new(0, 0, 300, 32));
        sc.set_segments(vec!["A".to_string(), "B".to_string(), "C".to_string()]);
        sc.set_selected_index(1);
        assert_eq!(sc.selected_index().unwrap_or(0), 1);

        // Clamp to max
        sc.set_selected_index(10);
        assert_eq!(sc.selected_index().unwrap_or(0), 2);
    }

    #[test]
    fn cupertino_segmented_control_value_changed_signal() {
        let mut sc = CupertinoSegmentedControl::new(Rect::new(0, 0, 300, 32));
        sc.set_segments(vec!["X".to_string(), "Y".to_string(), "Z".to_string()]);

        let fired = Arc::new(AtomicBool::new(false));
        let last_index = Arc::new(std::sync::Mutex::new(0usize));
        let f = fired.clone();
        let li = last_index.clone();
        sc.value_changed.connect(move |idx| {
            f.store(true, Ordering::SeqCst);
            *li.lock().unwrap() = *idx;
        });

        // Click on segment 1 (x ~100-199)
        // seg_w = 300/3 = 100, segment 1 is at x 100-199
        sc.handle_event(&Event::MouseRelease { pos: Point::new(150, 16), button: 1 });
        assert!(fired.load(Ordering::SeqCst));
        assert_eq!(*last_index.lock().unwrap(), 1);
    }

    #[test]
    fn cupertino_segmented_control_click_same_segment_no_emit() {
        let mut sc = CupertinoSegmentedControl::new(Rect::new(0, 0, 300, 32));
        sc.set_segments(vec!["A".to_string(), "B".to_string()]);

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        sc.value_changed.connect(move |_: std::sync::Arc<usize>| {
            f.store(true, Ordering::SeqCst);
        });

        // Click on segment 0 (which is already selected)
        sc.handle_event(&Event::MouseRelease { pos: Point::new(50, 16), button: 1 });
        assert!(!fired.load(Ordering::SeqCst));
    }

    #[test]
    fn cupertino_segmented_control_svg_output() {
        let mut sc = CupertinoSegmentedControl::new(Rect::new(0, 0, 300, 32));
        sc.set_segments(vec!["Day".to_string(), "Week".to_string(), "Month".to_string()]);
        let svg = render_to_svg(&mut sc);
        assert!(svg.starts_with("<svg"));
    }

    /// A disabled segmented control must ignore taps.
    ///
    /// `handle_event` previously went straight to the hit test, so `set_enabled(false)`
    /// had no effect on this widget: a tap still moved the selection and still emitted
    /// `value_changed`. The neighbouring `LineEdit`/`Slider` gate on
    /// `is_enabled()` first, so this was an inconsistency rather than a deliberate
    /// policy.
    #[test]
    fn cupertino_segmented_control_disabled_ignores_taps() {
        let mut sc = CupertinoSegmentedControl::new(Rect::new(0, 0, 300, 32));
        sc.set_segments(vec!["A".to_string(), "B".to_string()]);
        sc.set_enabled(false);

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        sc.value_changed.connect(move |_: std::sync::Arc<usize>| {
            f.store(true, Ordering::SeqCst);
        });

        // Segment 1 (x 150-299) is not the selected one, so an enabled control would
        // have changed selection here.
        sc.handle_event(&Event::MouseRelease { pos: Point::new(200, 16), button: 1 });

        assert!(!fired.load(Ordering::SeqCst), "a disabled control must not emit");
        assert_eq!(
            sc.selected_index().unwrap_or(0),
            0,
            "a disabled control must not change selection"
        );
    }

    /// A disabled control must paint differently from an enabled one.
    ///
    /// The paint path ignored `enabled` entirely, so a control that refused taps
    /// still looked fully interactive — the user taps and nothing happens.
    #[test]
    fn cupertino_segmented_control_disabled_renders_differently() {
        // Holds the crate-wide theme guard: this test renders, and a concurrent
        // test that switches the appearance would otherwise change a later frame.
        let _theme_guard = crate::style::theme_test_guard();
        let mut sc = CupertinoSegmentedControl::new(Rect::new(0, 0, 300, 32));
        sc.set_segments(vec!["A".to_string(), "B".to_string()]);
        let enabled_svg = render_to_svg(&mut sc);

        sc.set_enabled(false);
        let disabled_svg = render_to_svg(&mut sc);

        assert_ne!(
            enabled_svg, disabled_svg,
            "the disabled state must be visible; otherwise the control lies about \
             accepting input"
        );
    }

    /// The track is one 32 px pill whatever rectangle the control was given.
    ///
    /// The defect this pins: the track was `fill_rounded_rect(rect, rect.height / 2, ..)`,
    /// so a 240x120 census cell drew a bare 240x120 stadium with no segment division in it —
    /// the segments inherited the same height, leaving nothing to divide.
    #[test]
    fn the_track_keeps_its_own_height_in_any_rectangle() {
        for height in [32u32, 60, 120, 300] {
            let sc = CupertinoSegmentedControl::new(Rect::new(0, 0, 240, height));
            assert_eq!(
                sc.track_band().height,
                crate::widget::metrics::dimensions::SEGMENTED_CONTROL_HEIGHT,
                "at control height {height}"
            );
        }
    }

    /// The highlight slides between segments rather than teleporting.
    ///
    /// # The defect this pins
    ///
    /// The module doc has always said "a **sliding** white indicator" while the draw path
    /// computed the highlight's x straight from `selected_index` — the promise was in the prose and
    /// the teleport was in the pixels. The three-frame shape (§0.3) is the assertion: the middle
    /// sample must be strictly between the two ends, which a teleporting highlight cannot produce.
    #[test]
    fn the_highlight_slides_rather_than_teleporting() {
        let mut sc = CupertinoSegmentedControl::new(Rect::new(0, 0, 240, 32));
        sc.set_segments(vec!["One".to_string(), "Two".to_string(), "Three".to_string()]);
        assert_eq!(sc.indicator_position(), 0.0, "a fresh control rests on the first segment");
        assert!(!sc.is_animating(), "and owes no frames");

        sc.set_selected_index(2);
        assert!(sc.is_animating(), "changing the selection owes frames");
        assert_eq!(sc.indicator_position(), 0.0, "the slide starts where the highlight was");

        assert!(sc.tick(60), "still moving after one step");
        let mid = sc.indicator_position();
        assert!(mid > 0.0 && mid < 2.0, "the highlight must take an interior position (got {mid})");
        while sc.tick(60) {}
        assert_eq!(sc.indicator_position(), 2.0, "and settle on the selected segment");
        assert!(!sc.is_animating(), "a settled control owes no more frames");
    }

    /// The slide reaches the **pixels**, not only the model.
    ///
    /// # Why the position assertion above is not enough
    ///
    /// A first version of this test asserted only on `indicator_position()` and passed even with the
    /// draw path reverted to `selected_index * seg_w` — a stored value that no paint site reads is
    /// the defect this crate has hit repeatedly (`audio_visualizer`, `data_grid`, the bezier
    /// handles). This one renders the *same* control at three points of the slide and requires the
    /// frames to differ, so a draw path that ignores the slide fails whatever the model says.
    #[test]
    fn the_slide_reaches_the_painted_highlight() {
        use crate::widget::svg::render_to_svg;

        let mut sc = CupertinoSegmentedControl::new(Rect::new(0, 0, 240, 32));
        sc.set_segments(vec!["One".to_string(), "Two".to_string(), "Three".to_string()]);
        sc.set_selected_index(2);

        let at_start = render_to_svg(&mut sc);
        assert!(sc.tick(60), "the highlight is travelling");
        let midway = render_to_svg(&mut sc);
        assert_ne!(
            at_start, midway,
            "a highlight that is mid-slide must not paint like one still at the start"
        );

        while sc.tick(60) {}
        let arrived = render_to_svg(&mut sc);
        assert_ne!(midway, arrived, "nor must the arrival paint like the midpoint");
    }

    /// A multi-byte segment label is elided on character boundaries, never inside a glyph.
    ///
    /// The budget is the segment less its two-point inset, measured by the renderer; the
    /// shared primitive keeps only whole characters and marks the cut with `…`.
    #[test]
    fn a_wide_segment_label_is_elided_on_character_boundaries() {
        let mut measure = |text: &str| text.chars().count() as u32 * 14;
        // A 64 px segment leaves a 60 px band: three glyphs plus the ellipsis.
        assert_eq!(
            fitted_segment_label(
                "\u{4e16}\u{754c}\u{4f60}\u{597d}\u{4e16}\u{754c}",
                64,
                &mut measure
            ),
            "\u{4e16}\u{754c}\u{4f60}\u{2026}"
        );
        assert_eq!(
            fitted_segment_label("\u{1f389}\u{1f389}\u{1f389}\u{1f389}\u{1f389}", 64, &mut measure),
            "\u{1f389}\u{1f389}\u{1f389}\u{2026}",
            "an emoji is a single character to the budget, not four bytes"
        );
    }

    /// A label that fits its segment is borrowed, so the paint path allocates nothing for it.
    #[test]
    fn a_fitting_segment_label_is_borrowed() {
        let mut measure = |text: &str| text.chars().count() as u32 * 14;
        assert!(matches!(
            fitted_segment_label("Day", 64, &mut measure),
            crate::compat::Cow::Borrowed("Day")
        ));
    }

    #[test]
    fn the_selected_thumb_is_white_by_default_and_accent_on_request() {
        let mut control = CupertinoSegmentedControl::new(Rect::new(0, 0, 300, 32));
        control.set_segments(vec!["One".to_string(), "Two".to_string()]);
        assert_eq!(control.tint(), SegmentTint::WhiteThumb);
        control.set_tint(SegmentTint::Accent);
        assert_eq!(control.tint(), SegmentTint::Accent);
    }

    #[test]
    fn a_segment_can_carry_an_icon() {
        let mut control = CupertinoSegmentedControl::new(Rect::new(0, 0, 300, 32));
        control.set_segment_items(vec![
            CupertinoSegment::new("Grid").with_icon("grid"),
            CupertinoSegment::new("List"),
        ]);
        assert_eq!(control.segment_icon(0), Some("grid"));
        assert_eq!(control.segment_icon(1), None);
        assert_eq!(control.segments(), ["Grid".to_string(), "List".to_string()]);
    }
}