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
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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Tooltip widget — a popup label that appears on hover for context info.
//!
//! The Tooltip widget displays a short text label near a target widget when the
//! pointer hovers over it. It supports configurable show/hide delays, custom colors,
//! padding, and maximum width. Tooltips are rendered as rounded rectangles with
//! semi-transparent dark backgrounds and white text.

use crate::core::HorizontalAlignment;
use crate::core::ObjectId;
use crate::core::{Color, Font, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::style::animation::{MotionSlot, PropertyDriver};
use crate::widget::capability::coercion::{expect_bool, expect_string};
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, ControlMetrics};
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

/// Default delay (ms) before the tooltip appears after mouse enters the target.
const DEFAULT_SHOW_DELAY_MS: u64 = 500;
/// Default delay (ms) before the tooltip hides after mouse leaves the target.
const DEFAULT_HIDE_DELAY_MS: u64 = 200;
/// Default padding inside the tooltip (pixels).
const DEFAULT_PADDING: i32 = 6;
/// Default font size for tooltip text.
const DEFAULT_FONT_SIZE: f32 = 12.0;
/// Default maximum width of the tooltip before text wraps.
const DEFAULT_MAX_WIDTH: u32 = 300;
/// Default background colour, used as the last resort behind [`Tooltip`]'s own
/// `background_color` field when neither an explicit style nor the theme resolves one.
const DEFAULT_BG_COLOR: Color = Color::rgba(40, 40, 40, 220);
/// Default text colour, the counterpart of [`DEFAULT_BG_COLOR`].
const DEFAULT_TEXT_COLOR: Color = Color::WHITE;
/// Timer id used for show-delay scheduling.
const TIMER_SHOW_ID: u32 = 1;
/// Timer id used for hide-delay scheduling.
const TIMER_HIDE_ID: u32 = 2;

/// Tooltip widget — a popup label attached to a target widget.
///
/// The tooltip appears when the pointer hovers over the target widget and
/// disappears after the pointer leaves. Both delays are configurable.
pub struct Tooltip {
    base: BaseWidget,
    text: String,
    target_widget: Option<ObjectId>,
    show_delay: u64,
    hide_delay: u64,
    visible: bool,
    background_color: Color,
    text_color: Color,
    padding: i32,
    font_size: f32,
    max_width: u32,
    /// Tracks whether the pointer is currently hovering over the target area.
    hovering: bool,
    /// What the bubble is fading towards: `1.0` shown, `0.0` hidden.
    ///
    /// # Why the fade is a field and not a fourth boolean
    ///
    /// A tooltip is the canonical *delayed* control: it waits out the show delay, appears,
    /// and — the part a reader actually notices — lingers after the pointer leaves so it can
    /// be read. It used to switch on and off across two `Event::Timer` ids, which made both
    /// the fade and the two delays a function of how often the host sent those events
    /// instead of a function of time. `fade` is driven by [`Tooltip::tick`] from `delta_ms`,
    /// and the delays are elapsed-time counters on the same clock — so the 450 ms a tooltip
    /// stays readable is 450 ms on every host, and `tick` is what the frame bus owns.
    fade: PropertyDriver,
    /// Milliseconds the pointer has rested on the target while a show is pending.
    show_elapsed_ms: u64,
    /// Milliseconds the pointer has been away while a hide is pending.
    hide_elapsed_ms: u64,
    /// Tracks whether a show delay is counting down.
    show_pending: bool,
    /// Tracks whether a hide delay is counting down.
    hide_pending: bool,
}

impl Tooltip {
    /// Creates a new Tooltip widget with the given text and geometry.
    ///
    /// The tooltip starts hidden with default show/hide delays, default
    /// semi-transparent dark background, white text, 6px padding, 12px font
    /// size, and 300px max width. No target widget is set initially.
    pub fn new(text: &str, geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::Tooltip, geometry, "Tooltip"),
            text: text.to_string(),
            target_widget: None,
            show_delay: DEFAULT_SHOW_DELAY_MS,
            hide_delay: DEFAULT_HIDE_DELAY_MS,
            visible: false,
            background_color: DEFAULT_BG_COLOR,
            text_color: DEFAULT_TEXT_COLOR,
            padding: DEFAULT_PADDING,
            font_size: DEFAULT_FONT_SIZE,
            max_width: DEFAULT_MAX_WIDTH,
            hovering: false,
            fade: PropertyDriver::at(0.0, MotionSlot::Fast),
            show_elapsed_ms: 0,
            hide_elapsed_ms: 0,
            show_pending: false,
            hide_pending: false,
        }
    }

    /// Sets the tooltip text content.
    pub fn set_text(&mut self, text: &str) {
        self.text = text.to_string();
        self.base.request_redraw();
    }

    /// Returns the tooltip text content.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Immediately shows the tooltip, jumping the fade to its shown end.
    ///
    /// "Immediately" is the contract: a caller that calls `show` wants the bubble now, not a
    /// fade toward it, so the transition is snapped rather than retargeted.
    pub fn show(&mut self) {
        self.show_pending = false;
        self.hide_pending = false;
        self.show_elapsed_ms = 0;
        self.hide_elapsed_ms = 0;
        self.visible = true;
        self.fade.jump_to(1.0);
        self.base.request_redraw();
    }

    /// Immediately hides the tooltip, jumping the fade to its hidden end.
    pub fn hide(&mut self) {
        self.hide_pending = false;
        self.show_pending = false;
        self.show_elapsed_ms = 0;
        self.hide_elapsed_ms = 0;
        self.visible = false;
        self.fade.jump_to(0.0);
        self.base.request_redraw();
    }

    /// How opaque the bubble currently is, in `0.0..=1.0`.
    ///
    /// Exposed so the fade can be asserted without depending on a rendered pixel — the
    /// tooltip's whole timing contract is this one number moving on `tick`.
    pub fn fade_progress(&self) -> f32 {
        self.fade.value()
    }

    /// Advances the tooltip's delays and fade by `delta_ms`.
    ///
    /// # What this single entry point replaces
    ///
    /// Two `Event::Timer` ids used to do this work: one fired the pending show, one the
    /// pending hide, and neither carried a duration — so the elapsed time was whatever the
    /// host's timer interval happened to be, and the fade had no intermediate states at all.
    /// Here the show/hide delays are elapsed counters and the fade is a `PropertyDriver`, both
    /// stepped from the same `delta_ms` the frame bus hands every animation in the crate.
    pub fn tick(&mut self, delta_ms: u32) -> bool {
        let mut owes_frame = false;
        if self.show_pending {
            self.show_elapsed_ms = self.show_elapsed_ms.saturating_add(u64::from(delta_ms));
            if self.show_elapsed_ms >= self.show_delay {
                // A delayed show is a *fade in*, not a snap: `visible` flips so the bubble is
                // on the painted path, and the transition carries it up from transparent.
                self.show_pending = false;
                self.visible = true;
            }
            // The countdown itself wants frames even before the bubble is visible, or the
            // delay would only elapse while something else happened to repaint.
            owes_frame = true;
        }
        if self.hide_pending {
            self.hide_elapsed_ms = self.hide_elapsed_ms.saturating_add(u64::from(delta_ms));
            if self.hide_elapsed_ms >= self.hide_delay {
                self.hide_pending = false;
                self.visible = false;
            }
            owes_frame = true;
        }
        // The target is the shown state while visible, the hidden state otherwise; a `show`
        // that has not yet elapsed leaves `visible` false, so the bubble stays faded out
        // until the delay is up — which is what makes the delay *and* the fade one mechanism.
        let target = if self.visible { 1.0 } else { 0.0 };
        self.fade.set_target(target);
        if self.fade.tick(delta_ms) {
            owes_frame = true;
        }
        if owes_frame {
            self.base.request_redraw();
        }
        owes_frame
    }

    /// Returns whether the tooltip is currently visible.
    pub fn is_visible(&self) -> bool {
        self.visible
    }

    /// Reports the tooltip's own shown-state.
    ///
    /// Deliberately distinct from [`Widget::is_visible`], which this widget
    /// overrides to hide `BaseWidget::visible`. The property contract publishes
    /// the inherited `visible` for the control, so the popup state is published
    /// under the `shown` name instead; without this separation the base property
    /// would be unreachable.
    pub fn is_shown(&self) -> bool {
        self.visible
    }

    /// Sets the tooltip's own shown-state, scheduling nothing.
    ///
    /// The counterpart to [`is_shown`](Self::is_shown); it routes through the
    /// existing `show` / `hide` accessors so the pending-timer bookkeeping stays
    /// consistent.
    pub fn set_shown(&mut self, shown: bool) {
        if shown {
            self.show();
        } else {
            self.hide();
        }
    }

    /// Returns the bubble's fill colour.
    ///
    /// The last step of `draw`'s resolution order — explicit style, then the theme, then
    /// this field — so a caller can override the bubble without restyling the whole control.
    pub fn background_color(&self) -> Color {
        self.background_color
    }

    /// Sets the bubble's fill colour and requests a redraw.
    ///
    /// Written straight onto the widget rather than onto its style so it survives the
    /// theme's own application, which would otherwise replace the widget's style record.
    pub fn set_background_color(&mut self, color: Color) {
        self.background_color = color;
        self.base.request_redraw();
    }

    /// Returns the colour the bubble's text is drawn in.
    ///
    /// Read only when the bubble is opaque enough for the default contrast colour to be
    /// unreadable; `draw` otherwise uses the bubble's own contrast colour.
    pub fn text_color(&self) -> Color {
        self.text_color
    }

    /// Sets the colour the bubble's text is drawn in and requests a redraw.
    pub fn set_text_color(&mut self, color: Color) {
        self.text_color = color;
        self.base.request_redraw();
    }

    /// Sets the target widget id that this tooltip is attached to.
    /// The tooltip responds to mouse enter/leave events associated with
    /// this target by scheduling show/hide.
    pub fn set_target(&mut self, target: ObjectId) {
        self.target_widget = Some(target);
    }

    /// Returns the target widget id, if any.
    pub fn target(&self) -> Option<ObjectId> {
        self.target_widget
    }

    /// Sets the show delay in milliseconds.
    /// This is the time the pointer must hover before the tooltip appears.
    pub fn set_show_delay(&mut self, ms: u64) {
        self.show_delay = ms;
    }

    /// Sets the hide delay in milliseconds.
    /// This is the time after the pointer leaves before the tooltip disappears.
    pub fn set_hide_delay(&mut self, ms: u64) {
        self.hide_delay = ms;
    }

    /// Calculates the preferred size of the tooltip based on the text content
    /// and the configured padding.
    ///
    /// Uses a simple estimation: measures the text at the configured font size
    /// and adds padding on all sides. If the text is empty, returns a default
    /// minimum size.
    pub fn preferred_size(&self) -> Size {
        if self.text.is_empty() {
            return Size::new((self.padding as u32) * 2, (self.padding as u32) * 2 + 16);
        }
        // Estimate: approximate text measurement using character count
        let char_width = self.font_size * 0.6;
        let estimated_width = (self.text.len() as f32 * char_width).ceil() as u32;
        let line_height = (self.font_size * 1.4).ceil() as u32;

        let width = (estimated_width + (self.padding as u32) * 2).min(self.max_width);
        let height = line_height + (self.padding as u32) * 2;
        Size::new(width, height)
    }
}

impl Widget for Tooltip {
    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::TOOLTIP_DEFAULT_WIDTH,
            crate::widget::metrics::dimensions::TOOLTIP_HEIGHT,
        )
    }

    /// One frame of the delays and the fade. The frame bus calls this; nothing else does.
    fn tick(&mut self, delta_ms: u32) -> bool {
        Tooltip::tick(self, delta_ms)
    }

    /// A pending delay or a mid-fade bubble owes frames; one fully shown or hidden does not.
    fn is_animating(&self) -> bool {
        if self.show_pending || self.hide_pending {
            return true;
        }
        // The driver holds the target, so the comparison that used to re-derive it from
        // `visible` here is the driver's own `is_moving` -- one statement of the fact, and the
        // tick path aims at the same one.
        self.fade.is_moving()
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `Tooltip`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_dialog.in.rs` / `access_write_dialog.in.rs` dispatch, so callers see
/// the same coercions and the same errors as before.
///
/// The legacy table served a `visible` arm for this kind, but there is a name
/// collision to resolve: this widget overrides [`Widget::is_visible`] to return its
/// *popup* state, so a `visible` arm here would shadow the shared `visible` that
/// [`base_property_get`] serves — the two would be indistinguishable and the base
/// one unreachable. The popup state is therefore published as `shown`, and bare
/// `visible` keeps meaning what it means for every other control.
impl WidgetProperties for Tooltip {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "text" => Ok(CapabilityValue::String(self.text().to_string())),
            "shown" => Ok(CapabilityValue::Bool(self.is_shown())),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "text" => {
                self.set_text(&expect_string(value)?);
                Ok(())
            }
            "shown" => {
                self.set_shown(expect_bool(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

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

    /// Runs one of the commands `tooltip` publishes.
    ///
    /// `show` and `hide` map onto the widget's real methods and take no payload
    /// (each also cancels any pending timer). `set_text` carries the text the
    /// caller wants shown, so a bare invocation is reported as needing one
    /// rather than being called unknown.
    fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
        match name {
            "show" => {
                self.show();
                Ok(())
            }
            "hide" => {
                self.hide();
                Ok(())
            }
            "set_text" => Err(CapabilityAccessError::OutOfRange),
            _ => Err(CapabilityAccessError::UnknownCommand),
        }
    }
}

impl EventHandler for Tooltip {
    fn handle_event(&mut self, event: &Event) {
        match event {
            Event::MouseEnter { pos: _ } => {
                if !self.hovering {
                    self.hovering = true;
                    // Cancel any pending hide and restart the show countdown from zero, so the
                    // delay is measured from *this* entry and not from an earlier one.
                    self.hide_pending = false;
                    self.hide_elapsed_ms = 0;
                    // A zero delay shows at once, which is the same path `tick` would take on
                    // its first frame — stated here so `show_delay == 0` needs no frame to fire.
                    if self.show_delay == 0 {
                        self.show();
                    } else {
                        self.show_elapsed_ms = 0;
                        self.show_pending = true;
                        self.base.request_redraw();
                    }
                }
            }
            Event::MouseLeave { pos: _ } => {
                if self.hovering {
                    self.hovering = false;
                    // Cancel any pending show and restart the hide countdown.
                    self.show_pending = false;
                    self.show_elapsed_ms = 0;
                    if self.hide_delay == 0 {
                        self.hide();
                    } else {
                        self.hide_elapsed_ms = 0;
                        self.hide_pending = true;
                        self.base.request_redraw();
                    }
                }
            }
            // The legacy timer path drives the same `tick` the frame bus does, at a nominal
            // frame's worth of time, so a host that has not moved to the bus sees the tooltip
            // it always did. It is a fallback, not the clock: the delays are measured in
            // milliseconds, not in how often this event arrives.
            Event::Timer { id } => {
                if *id == TIMER_SHOW_ID || *id == TIMER_HIDE_ID {
                    self.tick(16);
                }
            }
            _ => {
                self.base.handle_event(event);
            }
        }
    }
}

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

        // Chrome colours resolve explicit style first, then the theme's resolved style for
        // this control, and only then a literal. Every colour below used to be a literal —
        // and the whole body used to be skipped unless the tooltip was already showing — so
        // the census reported `ink = 0` *and* no response to a light/dark switch.
        //
        // The theme reads take and release 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("tooltip");
        // `tooltip` 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
        // bubble painted in that colour would be byte-identical to the frame behind it, so a
        // resolved surface equal to the window fill is re-derived a visible step away from
        // it, the same distinction `Colors::input_background` draws for a field.
        let window_fill = {
            let manager = crate::style::theme_manager();
            manager.current_theme().map(|active| active.colors.background).unwrap_or(Color::WHITE)
        };
        let ink = style
            .text_color
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or(self.text_color);
        // # Why the inverse surface leads
        //
        // A tooltip is the canonical *inverted* bubble: in a light appearance it is dark, in a
        // dark one it is light. The `Surface` role resolves to `surface_container`, which is
        // one step off the page — close enough in the light preset that a bubble painted in it
        // is hard to tell from the frame behind it (BLUE21 AR3's finding). `inverse_surface`
        // states the relationship directly: it is *deliberately* the far end of the axis, and
        // it is the token a theme author tunes.
        //
        // # The defect this replaces (measured, not inferred)
        //
        // The branch that read `inverse_surface` was guarded by `own != window_fill`, where `own`
        // is `self.background_color` — whose **default is `DEFAULT_BG_COLOR`, not the window
        // fill** (`rgba(40,40,40,220)`). The guard was therefore taken on every default-constructed
        // tooltip and the role below it was unreachable: the bubble painted the same
        // `rgba(40,40,40,0.86)` in the dark appearance *and* the light one, and the light bubble
        // sat on a `rgba(240,240,240)` window at 1.72:1 from it. Measured with
        // `tests/tooltip_paint_probe.rs`, which shows the tooltip and settles the fade:
        //
        //     appearance=Dark   bubble fill=rgba(40,40,40,0.86)
        //     appearance=Light  bubble fill=rgba(40,40,40,0.86)   <- the appearance is ignored
        //
        // That is BLUE21 AR3 exactly, and the fix is the same shape `snackbar` already uses: the
        // role pair leads, the caller's own colour wins over it, and the old arithmetic survives
        // only as the fallback for a theme that predates the roles.
        //
        // # Why the pair, and not just the surface
        //
        // `inverse_surface` names a surface whose ink is `on_inverse_surface`. Reading only the
        // surface and then deriving the ink with `contrast_color()` throws away the second half
        // of what the theme said: a theme that pairs a low-contrast surface with a deliberate
        // ink would be overridden by the derivation, and `contrast_color()` picks black or white
        // — neither of which is a colour a theme author chose.
        let caller_color = style.background_color.filter(|_| !style.theme_derived);
        // The surface and its ink are decided **together**, before the fade: the ink belongs to
        // the colour the theme stated, and the fade is a compositing step applied to the surface
        // afterwards. Deriving the ink from the faded fill would make the label change colour as
        // the bubble fades in, which is not what a fade is.
        let inverse_surface = crate::style::layer_color(crate::style::LayerColor::InverseSurface);
        let (bubble_fill, text_color) = match caller_color {
            // A caller's own colour wins outright. Its ink is derived, because the caller chose
            // only a surface and gave us no ink to honour.
            Some(explicit) => (explicit, explicit.contrast_color()),
            None => match inverse_surface {
                // The theme states the pair, so both halves are honoured as stated.
                Some(surface) => {
                    let ink = crate::style::layer_color(crate::style::LayerColor::OnInverseSurface)
                        .unwrap_or_else(|| surface.contrast_color());
                    (surface, ink)
                }
                // A theme that predates the roles: the old derivation, kept so the control still
                // has an answer. `theme_derived` backgrounds are ignored because the resolved
                // `Surface` role is the too-close-to-the-page value this control must not adopt;
                // `own` is only `DEFAULT_BG_COLOR` here, which is why the guard below reads the
                // **caller's** colour rather than the field.
                None => {
                    let own = self.background_color;
                    let surface =
                        if own != window_fill { own } else { window_fill.blend(&ink, 0.85) };
                    (surface, surface.contrast_color())
                }
            },
        };
        let _ = theme;
        // The bubble is blended toward the window by however far the fade has run, so the
        // control still has a rendered body in every state instead of vanishing at rest — and a
        // mid-fade bubble is genuinely between the two, which is what a fade *means*. The old
        // form was a two-state dim (shown or 45% toward the window) with nothing in between;
        // the fade now comes from `tick`, so it moves over time rather than snapping.
        let bubble_color = window_fill.blend(&bubble_fill, self.fade.value());

        let font = Font::simple("sans-serif", self.font_size);

        // Measure text for layout. The empty case measures the placeholder so a hidden
        // tooltip still has a body to paint at the census geometry.
        let label = if self.text.is_empty() { "Tooltip" } else { self.text.as_str() };
        let metrics = context.measure_text(label, &font);
        let text_width = metrics.width;

        // ── The bubble actually painted ──
        //
        // A tooltip is a **single-line bubble of its own height**, centred in the area it was
        // given, not a panel shaped like its container. `total_width = ..max(rect.width)` and
        // `total_height = ..max(rect.height)` did the opposite: the bubble was *at least* the
        // control's size, so the 240x120 census cell drew a full-canvas 240x120 rounded
        // rectangle (`tooltip.svg` carried `<rect x="0" y="0" width="240" height="120"
        // rx="4"/>`) with its label stranded at y = 6 — a poorly filled panel rather than a
        // tooltip. The height is now [`dimensions::TOOLTIP_HEIGHT`] and the width is the
        // label's own advance plus [`dimensions::TOOLTIP_PADDING_H`], so a longer string makes
        // a wider bubble and nothing about the caller's rectangle can stretch it.
        let content_width = text_width.min(self.max_width);
        let total_width = (content_width + dimensions::TOOLTIP_PADDING_H * 2).min(rect.width);
        let bubble = ControlMetrics::center_in(
            rect,
            Size::new(total_width.max(1), dimensions::TOOLTIP_HEIGHT),
        );
        // The corner is the vertical padding, so the radius scales with the bubble's own
        // edging rather than being a fourth literal for a 24 px box.
        let corner_radius = dimensions::TOOLTIP_PADDING_V;

        // Draw rounded rectangle background
        context.fill_rounded_rect(bubble, corner_radius, bubble_color);

        // Draw the label **vertically centred** in the bubble, horizontally at the bubble's
        // own padding.
        //
        // The origin is the glyph box's top-left, so a top-aligned label sat at
        // `bubble.y + padding`; more importantly the old code positioned it from the *control's*
        // rectangle while the bubble was centred, so once the bubble stopped filling its
        // rectangle the two would have been placed from different boxes. `text_line` derives the
        // line box from the bubble itself, which is the same box the fill just painted.
        let line = context.text_line(bubble, &font);
        let text_x = bubble.x + dimensions::TOOLTIP_PADDING_H as i32;

        context.draw_text(
            Point::new(text_x, line.y),
            label,
            &font,
            text_color,
            HorizontalAlignment::Left,
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::widget::svg::render_to_svg;

    #[test]
    fn tooltip_default_creation() {
        let tooltip = Tooltip::new("Hello", Rect::new(0, 0, 100, 40));
        assert_eq!(tooltip.kind(), WidgetKind::Tooltip);
        assert_eq!(tooltip.text(), "Hello");
        assert!(!tooltip.is_visible());
        assert!(tooltip.target().is_none());
        assert_eq!(tooltip.geometry(), Rect::new(0, 0, 100, 40));
    }

    #[test]
    fn tooltip_show_hide() {
        let mut tooltip = Tooltip::new("Test", Rect::new(0, 0, 100, 40));
        assert!(!tooltip.is_visible());

        tooltip.show();
        assert!(tooltip.is_visible());

        tooltip.hide();
        assert!(!tooltip.is_visible());
    }

    #[test]
    fn tooltip_text_accessor() {
        let mut tooltip = Tooltip::new("Initial", Rect::new(0, 0, 100, 40));
        assert_eq!(tooltip.text(), "Initial");

        tooltip.set_text("Updated");
        assert_eq!(tooltip.text(), "Updated");

        tooltip.set_text("");
        assert_eq!(tooltip.text(), "");
    }

    #[test]
    fn tooltip_preferred_size_empty_text() {
        let tooltip = Tooltip::new("", Rect::new(0, 0, 100, 40));
        let size = tooltip.preferred_size();
        assert!(size.width >= 12);
        assert!(size.height >= 28);
    }

    #[test]
    fn tooltip_preferred_size_with_text() {
        let tooltip = Tooltip::new("Hello World", Rect::new(0, 0, 100, 40));
        let size = tooltip.preferred_size();
        // Should be larger than empty padding alone
        assert!(size.width >= 12);
        assert!(size.height >= 28);
    }

    #[test]
    fn tooltip_target_widget() {
        let mut tooltip = Tooltip::new("Info", Rect::new(0, 0, 100, 40));
        assert!(tooltip.target().is_none());

        tooltip.set_target(42);
        assert_eq!(tooltip.target(), Some(42));
    }

    #[test]
    fn tooltip_delays() {
        let mut tooltip = Tooltip::new("Delayed", Rect::new(0, 0, 100, 40));
        // Default delays
        assert_eq!(tooltip.show_delay, 500);
        assert_eq!(tooltip.hide_delay, 200);

        tooltip.set_show_delay(1000);
        assert_eq!(tooltip.show_delay, 1000);

        tooltip.set_hide_delay(300);
        assert_eq!(tooltip.hide_delay, 300);
    }

    /// The show delay is measured in milliseconds, and nothing before it elapses shows the bubble.
    ///
    /// This replaces an assertion that a *single* timer event fired the pending show. That test
    /// encoded the defect: the delay was however long the host took to send the timer, so it was
    /// 500 ms on one host and 32 ms on another. The delay is now a duration on `tick`'s clock,
    /// which is what this asserts — including the part the old test could not state at all, that
    /// the bubble stays hidden *until* the delay is up.
    #[test]
    fn the_show_delay_is_measured_in_milliseconds() {
        let mut tooltip = Tooltip::new("Tooltip", Rect::new(0, 0, 100, 40));
        assert!(!tooltip.is_visible());
        assert!(!tooltip.show_pending);
        assert!(!tooltip.hovering);

        tooltip.handle_event(&Event::MouseEnter { pos: Point::new(10, 10) });
        assert!(tooltip.hovering, "the pointer is on the target");
        assert!(tooltip.show_pending, "and the delay is counting down");
        assert!(!tooltip.is_visible(), "but the bubble is not up yet");

        // Just short of the delay: still hidden. This is the assertion the old form could not
        // make, because it had no notion of *how long* had passed.
        assert!(tooltip.tick(DEFAULT_SHOW_DELAY_MS as u32 - 1), "the countdown owes frames");
        assert!(!tooltip.is_visible(), "the delay must not be short-circuited");

        // The final millisecond completes it.
        tooltip.tick(1);
        assert!(tooltip.is_visible());
        assert!(!tooltip.show_pending);
    }

    /// The full lifecycle, with both delays measured in milliseconds and a fade through it.
    #[test]
    fn tooltip_event_mouse_leave_hides_after_its_own_delay() {
        let mut tooltip = Tooltip::new("Tooltip", Rect::new(0, 0, 100, 40));
        tooltip.handle_event(&Event::MouseEnter { pos: Point::new(10, 10) });
        tooltip.tick(DEFAULT_SHOW_DELAY_MS as u32);
        assert!(tooltip.is_visible(), "the show delay has elapsed");

        // The pointer leaves: still visible, because the hide delay is what keeps a tooltip
        // readable after the pointer has moved on — the whole reason it exists.
        tooltip.handle_event(&Event::MouseLeave { pos: Point::new(0, 0) });
        assert!(!tooltip.hovering);
        assert!(tooltip.hide_pending, "the hide delay is counting down");
        assert!(tooltip.is_visible(), "still readable until the delay elapses");

        tooltip.tick(DEFAULT_HIDE_DELAY_MS as u32 - 1);
        assert!(tooltip.is_visible(), "one millisecond short is still shown");

        tooltip.tick(1);
        assert!(!tooltip.is_visible());
        assert!(!tooltip.hide_pending);
    }

    /// The bubble fades in and out rather than snapping, and settles at both ends.
    ///
    /// A fade is what the show/hide delays are *for*: the delay waits, then the bubble arrives
    /// gradually. The old form had no intermediate state — the bubble was either drawn or blended
    /// 45% toward the window in one step.
    #[test]
    fn the_bubble_fades_rather_than_snapping() {
        let mut tooltip = Tooltip::new("Tooltip", Rect::new(0, 0, 100, 40));
        assert_eq!(tooltip.fade_progress(), 0.0, "a fresh tooltip starts hidden");

        tooltip.show();
        assert_eq!(tooltip.fade_progress(), 1.0, "`show` is immediate, so the fade is snapped");

        // A zero hide delay hides at once, and "at once" includes the fade — a caller that
        // asked for no delay asked for the bubble to be gone, not to fade over the next frames.
        tooltip.handle_event(&Event::MouseEnter { pos: Point::new(10, 10) });
        tooltip.set_hide_delay(0);
        tooltip.handle_event(&Event::MouseLeave { pos: Point::new(0, 0) });
        assert!(!tooltip.is_visible(), "a zero hide delay hides at once");
        assert_eq!(tooltip.fade_progress(), 0.0, "and snaps the fade with it");

        // A *delayed* hide is the one that walks the fade: the bubble stays visible through the
        // delay, then fades out over the frames that follow it.
        tooltip.set_hide_delay(50);
        tooltip.show();
        tooltip.handle_event(&Event::MouseEnter { pos: Point::new(10, 10) });
        tooltip.handle_event(&Event::MouseLeave { pos: Point::new(0, 0) });
        assert!(tooltip.is_visible(), "still readable through the delay");
        assert_eq!(tooltip.fade_progress(), 1.0, "and fully faded in while it waits");
        // Walk the delay out; the bubble then goes invisible while the fade is still full.
        for _ in 0..4 {
            tooltip.tick(16);
        }
        assert!(!tooltip.is_visible(), "the delay has elapsed");
        let after_delay = tooltip.fade_progress();
        assert!(after_delay < 1.0, "the fade starts once the delay expires: {after_delay}");
        assert!(after_delay > 0.0, "and has only just started: {after_delay}");

        // A single frame moves it part of the way, and further frames settle it at zero.
        assert!(tooltip.tick(16), "a mid-fade bubble owes frames");
        let partway = tooltip.fade_progress();
        assert!(partway < 1.0, "the fade must have started: {partway}");
        assert!(partway > 0.0, "and not jumped to the end: {partway}");

        for _ in 0..40 {
            tooltip.tick(16);
        }
        assert_eq!(tooltip.fade_progress(), 0.0, "the fade settles fully hidden");
        assert!(!tooltip.tick(16), "and then owes no more frames");
    }

    #[test]
    fn tooltip_immediate_show_with_zero_delay() {
        let mut tooltip = Tooltip::new("Fast", Rect::new(0, 0, 100, 40));
        tooltip.set_show_delay(0);
        assert!(!tooltip.is_visible());
        assert!(!tooltip.hovering);

        tooltip.handle_event(&Event::MouseEnter { pos: Point::new(5, 5) });
        assert!(tooltip.hovering);
        assert!(tooltip.is_visible()); // shown immediately because delay is 0
    }

    #[test]
    fn tooltip_svg_output_visible() {
        let mut tooltip = Tooltip::new("SVG Tooltip", Rect::new(0, 0, 140, 30));
        tooltip.show();

        let svg = render_to_svg(&mut tooltip);
        assert!(svg.starts_with("<svg"), "SVG should start with <svg, got: {svg:.60}");
        assert!(svg.ends_with("</svg>"), "SVG should end with </svg>");
    }

    #[test]
    fn tooltip_svg_output_hidden() {
        // 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 tooltip = Tooltip::new("Hidden", Rect::new(0, 0, 100, 30));
        // A tooltip that is not showing is dimmed, not omitted: `draw` used to `return`
        // early here, so a tooltip that had been created but not hovered painted nothing at
        // all — the defect the rendering census reported as `ink = 0`.
        let svg = render_to_svg(&mut tooltip);
        assert!(svg.starts_with("<svg"));
        assert!(svg.ends_with("</svg>"));
        let fill_count = svg.matches("fill=").count();
        assert!(
            fill_count > 1,
            "a hidden tooltip must still paint its bubble, got only the background fill: {svg}"
        );

        // Shown and hidden must still be distinguishable, so the fix did not simply paint
        // the same frame in both states.
        let mut open = Tooltip::new("Hidden", Rect::new(0, 0, 100, 30));
        open.show();
        let shown = render_to_svg(&mut open);
        assert_ne!(svg, shown, "showing the tooltip must change what is painted");
    }

    /// A shown tooltip inverts: its bubble is at the *far* end of the theme's axis from the
    /// window it sits on, so it is legible in either appearance.
    ///
    /// # The defect this pins
    /// The bubble colour came from `self.background_color` whenever that differed from the
    /// window fill — and it **always** did, because the field defaults to `DEFAULT_BG_COLOR`
    /// (`rgba(40,40,40,220)`) rather than to the window. The branch that read the theme's
    /// `inverse_surface` was therefore unreachable, and the bubble painted the same colour in
    /// both appearances. Measured from the rendered SVG:
    ///
    /// ```text
    /// appearance=Dark   bubble fill=rgba(40,40,40,0.86)   vs window rgba(18,18,18)  ->  1.27:1
    /// appearance=Light  bubble fill=rgba(40,40,40,0.86)   -> the appearance was ignored
    /// ```
    ///
    /// 1.27:1 is not a tooltip, it is a smudge — and in the light appearance the bubble was
    /// dark while the theme's own stated `inverse_surface` was light, so the control was
    /// contradicting the theme rather than merely ignoring it.
    ///
    /// # Why the assertion is a *relation* and not a colour
    ///
    /// Asserting `rgba(228,225,229)` would pin the preset, and the whole point of the fix is
    /// that the value is the theme's to choose. What must hold for any theme is the
    /// relationship the role states: the bubble is darker than its window in a light
    /// appearance and lighter than it in a dark one, and its ink is legible on it.
    #[test]
    fn a_shown_bubble_inverts_against_its_window() {
        use crate::style::AppearanceMode;
        use crate::widget::svg::render_widget_to_svg_on;

        // The luminance of the bubble: the one chrome `<rect>` that is inset from the frame.
        // Identified by geometry rather than by colour, because the whole point is that the
        // colour is what is under test — matching on "not the backdrop colour" silently picked
        // the backdrop itself whenever the backdrop differed from the string passed in.
        fn bubble_luminance(svg: &str, frame_width: i32, frame_height: i32) -> f64 {
            luminance_of_inset_rect(svg, frame_width, frame_height)
        }

        let _guard = crate::style::theme_test_guard();
        for (appearance, window_is_dark) in
            [(AppearanceMode::Dark, true), (AppearanceMode::Light, false)]
        {
            crate::style::theme_manager().set_appearance(appearance);
            // The window the bubble sits on is the active theme's own background — NOT the
            // hard-coded white `render_to_svg` composites over.
            //
            // # The defect an earlier revision of this test had
            //
            // It rendered with `render_to_svg`, whose backdrop is a constant `Color::WHITE` (see
            // that function's docs). So in the *dark* appearance the "window" this test compared
            // against was white, the bubble was a light grey, and the two were **not** inverses —
            // yet the assertion passed, because it only checked the bubble's absolute luminance
            // and never once looked at the window. A test named `inverts_against_its_window` that
            // does not read the window proves nothing about the inversion it claims to guard.
            let window = crate::style::theme_manager()
                .current_theme()
                .map(|theme| theme.colors.background)
                .unwrap_or(crate::core::Color::WHITE);
            assert_eq!(
                is_dark(window),
                window_is_dark,
                "the {appearance:?} appearance must have a {} window for this test to mean \
                 anything; got {window:?}",
                if window_is_dark { "dark" } else { "light" }
            );

            let bounds = Rect::new(0, 0, 140, 30);
            let mut tooltip = Tooltip::new("hint", bounds);
            tooltip.show();
            let svg = render_widget_to_svg_on(&mut tooltip, bounds, window);

            let bubble = bubble_luminance(&svg, 140, 30);
            // The window is the endpoint of the axis, so "inverted" is simply "on the other side
            // of the midpoint from the window".
            if window_is_dark {
                assert!(
                    bubble > 0.5,
                    "in the dark appearance the bubble must be LIGHT (inverse of the window), \
                     got luminance {bubble:.3}:\n{svg}"
                );
            } else {
                assert!(
                    bubble < 0.5,
                    "in the light appearance the bubble must be DARK (inverse of the window), \
                     got luminance {bubble:.3}:\n{svg}"
                );
            }
            // The relation, stated directly: the bubble and its window are on opposite sides of
            // the midpoint. This is the assertion the test's name promises, and the one that
            // fails if the bubble ever stops inverting (e.g. it is painted in the window's own
            // colour).
            let window_lum = luminance(window);
            assert!(
                (bubble > 0.5) != (window_lum > 0.5),
                "the bubble (luminance {bubble:.3}) and its {appearance:?} window
                 (luminance {window_lum:.3}) must be on opposite sides of the midpoint"
            );
        }
    }

    /// `true` when a colour reads as dark (its relative luminance is at or below the midpoint).
    fn is_dark(color: crate::core::Color) -> bool {
        luminance(color) <= 0.5
    }

    /// The WCAG relative luminance of a colour, on the same scale the assertions use.
    fn luminance(color: crate::core::Color) -> f64 {
        fn linear(channel: u8) -> f64 {
            let c = f64::from(channel) / 255.0;
            if c <= 0.03928 {
                c / 12.92
            } else {
                ((c + 0.055) / 1.055).powf(2.4)
            }
        }
        0.2126 * linear(color.r) + 0.7152 * linear(color.g) + 0.0722 * linear(color.b)
    }

    /// The luminance of the one chrome `<rect>` inset from the frame — the bubble.
    ///
    /// Found by geometry (`x y width height`: the backdrop spans the whole frame, the bubble does
    /// not) rather than by colour, because the colour is what is under test.
    fn luminance_of_inset_rect(svg: &str, frame_width: i32, frame_height: i32) -> f64 {
        let fill = svg
            .lines()
            .filter(|line| line.contains("<rect") && line.contains("fill="))
            .find(|line| {
                let numbers: Vec<i32> =
                    line.split('"').filter_map(|part| part.parse::<i32>().ok()).collect();
                numbers.len() >= 4 && (numbers[2] < frame_width || numbers[3] < frame_height)
            })
            .unwrap_or_else(|| panic!("no inset bubble rect in:\n{svg}"));
        let rgb =
            fill.split("rgba(").nth(1).and_then(|rest| rest.split(')').next()).expect("a fill");
        let channels: Vec<f64> = rgb
            .split(',')
            .take(3)
            .map(|c| c.trim().parse::<f64>().expect("a channel") / 255.0)
            .collect();
        let linear = |c: f64| {
            if c <= 0.03928 {
                c / 12.92
            } else {
                ((c + 0.055) / 1.055).powf(2.4)
            }
        };
        0.2126 * linear(channels[0]) + 0.7152 * linear(channels[1]) + 0.0722 * linear(channels[2])
    }
}