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
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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
// 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, 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};
use std::cell::RefCell;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::rc::Rc;

/// 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;

/// One run of rich text inside a tooltip bubble.
///
/// A plain tooltip has one run — the whole label in one colour. A caller that wants a
/// highlighted fragment (a shortcut, a warning, a unit) installs several runs through
/// [`Tooltip::set_spans`], each with its own colour and weight. The runs are laid out on one
/// line in order, so the bubble is still a tooltip rather than a paragraph.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TooltipSpan {
    /// The text this run contributes.
    pub text: String,
    /// The colour overrides the bubble's resolved ink when set.
    pub color: Option<Color>,
    /// Whether the run is painted in the bubble font's bold face.
    pub bold: bool,
}

impl TooltipSpan {
    /// Creates a plain run in the bubble's own ink and weight.
    pub fn new(text: impl Into<String>) -> Self {
        Self { text: text.into(), color: None, bold: false }
    }

    /// Sets the run's colour.
    pub fn with_color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// Sets the run's weight.
    pub fn with_bold(mut self, bold: bool) -> Self {
        self.bold = bold;
        self
    }
}

/// The inputs that decide how a tooltip label wraps.
#[derive(PartialEq, Eq)]
struct TooltipWrapKey {
    text_hash: u64,
    family_hash: u64,
    size_bits: u32,
    weight: u16,
    bold: bool,
    italic: bool,
    available: u32,
}

/// The last wrap result, so a still frame does no measuring or allocation.
struct TooltipWrapCache {
    key: TooltipWrapKey,
    lines: Rc<Vec<String>>,
    width: u32,
}

/// Cached advances of the rich-text runs.
///
/// A rich tooltip measured every span twice per frame — once for the bubble width and once
/// while painting — and repeated both on every frame that changed no text. The advances are a
/// function of the runs and the resolved font, so they are derived once per revision (G-P10).
struct TooltipSpanCache {
    key: u64,
    widths: Rc<Vec<u32>>,
}

/// 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,
    /// Rich-text runs painted instead of the single `text` label when non-empty.
    spans: Vec<TooltipSpan>,
    /// Whether the label wraps at the bubble's maximum width instead of eliding.
    wrap: bool,
    /// The rectangle the bubble is positioned against, when one was supplied.
    anchor: Option<Rect>,
    /// 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,
    /// Wrapped label cache keyed by text, font identity and available width (M-11).
    wrap_cache: RefCell<Option<TooltipWrapCache>>,
    /// Rich-run advance cache keyed by the runs and the resolved font (G-P10).
    span_cache: RefCell<Option<TooltipSpanCache>>,
}

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,
            spans: Vec::new(),
            wrap: false,
            anchor: None,
            hovering: false,
            fade: PropertyDriver::at(0.0, MotionSlot::Fast),
            show_elapsed_ms: 0,
            hide_elapsed_ms: 0,
            show_pending: false,
            hide_pending: false,
            wrap_cache: RefCell::new(None),
            span_cache: RefCell::new(None),
        }
    }

    /// Sets the tooltip text content.
    ///
    /// A same-value write is a no-op: the string is the tooltip's whole payload (WDGT-12).
    pub fn set_text(&mut self, text: impl Into<String>) {
        let text = text.into();
        if self.text == text {
            return;
        }
        self.text = text;
        self.base.request_redraw();
    }

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

    /// Returns the rich-text runs, empty when the tooltip paints its plain label.
    pub fn spans(&self) -> &[TooltipSpan] {
        &self.spans
    }

    /// Installs rich-text runs, replacing the plain label while they are present.
    ///
    /// An empty vector restores the plain label. The runs are painted on one line in
    /// order; a run whose `color` is unset uses the bubble's resolved ink, and a bold run
    /// uses the bubble font's bold face.
    pub fn set_spans(&mut self, spans: Vec<TooltipSpan>) {
        if self.spans == spans {
            return;
        }
        self.spans = spans;
        self.base.request_redraw();
    }

    /// Removes the rich-text runs, restoring the plain label.
    pub fn clear_spans(&mut self) {
        if self.spans.is_empty() {
            return;
        }
        self.spans.clear();
        self.base.request_redraw();
    }

    /// Returns whether the label wraps at the bubble's maximum width.
    pub fn wrap(&self) -> bool {
        self.wrap
    }

    /// Enables or disables word wrapping.
    ///
    /// Off by default, which is the single-line elided bubble the control has always
    /// painted. On, the label breaks at spaces (and at explicit newlines) and the bubble
    /// grows a line at a time, up to the caller's `max_width`.
    pub fn set_wrap(&mut self, wrap: bool) {
        if self.wrap == wrap {
            return;
        }
        self.wrap = wrap;
        self.base.request_redraw();
    }

    /// Returns the rectangle the bubble is positioned against, if any.
    pub fn anchor_rect(&self) -> Option<Rect> {
        self.anchor
    }

    /// Positions the bubble against `anchor` instead of centring it in the control.
    ///
    /// The bubble is placed below the anchor, flipped above when there is no room, and
    /// clamped inside the control's own rectangle. This is the "follow the thing the
    /// tooltip describes" placement; without an anchor the bubble stays centred, which is
    /// what keeps the default frame unchanged.
    pub fn set_anchor_rect(&mut self, anchor: Rect) {
        if self.anchor == Some(anchor) {
            return;
        }
        self.anchor = Some(anchor);
        self.base.request_redraw();
    }

    /// Removes the anchor, returning the bubble to its centred placement.
    pub fn clear_anchor(&mut self) {
        if self.anchor.take().is_some() {
            self.base.request_redraw();
        }
    }

    /// 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) {
        if self.background_color == color {
            return;
        }
        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) {
        if self.text_color == color {
            return;
        }
        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.
    ///
    /// # What this estimates, and why it changed
    ///
    /// The width is an estimate from the **character** count, not the byte count. The old
    /// body used `self.text.len()`, which is UTF-8 **bytes**: for ASCII the two happen to
    /// agree, but for a CJK label three characters reported roughly three times their real
    /// width, so a Chinese tooltip reserved far more room than its own `draw` used. The live
    /// long-text path already measures through `context.measure_text`; this stays a cheap
    /// estimate because [`Widget::size_hint`] has no render context, and it is documented as
    /// such rather than presented as a measurement.
    ///
    /// Zero-width characters are ignored by the count where the platform agrees with
    /// `char::is_control`; a control character occupies no ink in any font this crate ships.
    pub fn preferred_size(&self) -> Size {
        if self.text.is_empty() && self.spans.is_empty() {
            return Size::new((self.padding as u32) * 2, (self.padding as u32) * 2 + 16);
        }
        // The hint measures with the **same font the bubble draws with** (D09-STYLE-02): a themed
        // body font, or the caller's own `font_size` when the style names none.
        let font = self.bubble_font();
        // Rich runs are measured as the sum of their glyph counts; the hint has no render
        // context, so this is the same estimate as the plain path, applied per run.
        let glyphs: f32 = if self.spans.is_empty() {
            self.text.chars().filter(|c| !c.is_control()).count() as f32
        } else {
            self.spans
                .iter()
                .map(|span| span.text.chars().filter(|c| !c.is_control()).count() as f32)
                .sum()
        };
        // A proportional face averages a little over half an em; this is the same constant
        // the old estimate used and is the honest resolution of a hint without a context.
        let char_width = font.size() * 0.6;
        let estimated_width = (glyphs * char_width).ceil() as u32;
        let line_height = (font.size() * 1.4).ceil() as u32;

        let width = (estimated_width + (self.padding as u32) * 2).min(self.max_width);
        // Wrapping is the one mode the hint can state honestly as a count: the label breaks
        // at the width cap, so the height is that many lines. Without wrapping the label is
        // one line and elides, which is what the old fixed height described.
        let height = if self.wrap {
            let line_width = width.saturating_sub((self.padding as u32) * 2).max(1);
            let lines = estimated_width.saturating_add(line_width - 1) / line_width;
            line_height.saturating_mul(lines.max(1)).saturating_add((self.padding as u32) * 2)
        } else {
            line_height + (self.padding as u32) * 2
        };
        Size::new(width, height)
    }

    /// The lines the plain label is painted on.
    ///
    /// Without wrapping this is the label itself, unchanged. With wrapping the text breaks
    /// at spaces and at explicit newlines, measured against the bubble's content width.
    /// A word longer than the cap is kept whole on its own line and elided by the fitted
    /// draw, rather than being split mid-word.
    fn wrapped_lines(&self, context: &RenderContext, text: &str, font: &Font) -> Rc<Vec<String>> {
        let control_width = self.geometry().width.saturating_sub(dimensions::TOOLTIP_PADDING_H * 2);
        let available =
            if self.wrap { self.max_width.min(control_width).max(1) } else { control_width.max(1) };
        let mut hasher = DefaultHasher::new();
        text.hash(&mut hasher);
        let text_hash = hasher.finish();
        let mut family = DefaultHasher::new();
        font.family().hash(&mut family);
        let key = TooltipWrapKey {
            text_hash,
            family_hash: family.finish(),
            size_bits: font.size().to_bits(),
            weight: font.weight(),
            bold: font.is_bold(),
            italic: font.is_italic(),
            available,
        };
        if let Some(cache) = self.wrap_cache.borrow().as_ref() {
            if cache.key == key {
                return Rc::clone(&cache.lines);
            }
        }
        let lines = if !self.wrap {
            vec![text.to_string()]
        } else {
            let mut lines: Vec<String> = Vec::new();
            for paragraph in text.split('\n') {
                let mut current = String::new();
                for word in paragraph.split(' ') {
                    let candidate = if current.is_empty() {
                        word.to_string()
                    } else {
                        let mut candidate = current.clone();
                        candidate.push(' ');
                        candidate.push_str(word);
                        candidate
                    };
                    if current.is_empty()
                        || context.measure_text(&candidate, font).width <= available
                    {
                        current = candidate;
                    } else {
                        lines.push(core::mem::take(&mut current));
                        current = word.to_string();
                    }
                }
                lines.push(current);
            }
            if lines.is_empty() {
                lines.push(String::new());
            }
            lines
        };
        let width =
            lines.iter().map(|line| context.measure_text(line, font).width).max().unwrap_or(0);
        let lines = Rc::new(lines);
        *self.wrap_cache.borrow_mut() =
            Some(TooltipWrapCache { key, lines: Rc::clone(&lines), width });
        lines
    }

    /// The advance of every rich run, served from a keyed cache.
    ///
    /// The width of one run is a function of its text, its bold flag and the resolved font, so
    /// the vector is rebuilt only when one of those facts changes (G-P10).
    fn span_widths(&self, context: &RenderContext, font: &Font) -> Rc<Vec<u32>> {
        let mut hasher = DefaultHasher::new();
        font.family().hash(&mut hasher);
        font.size().to_bits().hash(&mut hasher);
        font.weight().hash(&mut hasher);
        font.is_bold().hash(&mut hasher);
        font.is_italic().hash(&mut hasher);
        for span in &self.spans {
            span.text.hash(&mut hasher);
            span.bold.hash(&mut hasher);
        }
        let key = hasher.finish();
        if let Some(cache) = self.span_cache.borrow().as_ref() {
            if cache.key == key {
                return Rc::clone(&cache.widths);
            }
        }
        let widths: Vec<u32> = self
            .spans
            .iter()
            .map(|span| {
                let span_font = font.with_bold(span.bold);
                context.measure_text(&span.text, &span_font).width
            })
            .collect();
        let widths = Rc::new(widths);
        *self.span_cache.borrow_mut() = Some(TooltipSpanCache { key, widths: Rc::clone(&widths) });
        widths
    }

    /// The bubble rectangle for a bubble of `size`.
    ///
    /// Centred in the control unless an anchor was supplied, in which case it sits below
    /// the anchor, flips above when that would leave the control, and is clamped inside it.
    fn bubble_rect(&self, rect: Rect, size: Size) -> Rect {
        let Some(anchor) = self.anchor else {
            return ControlMetrics::center_in(rect, size);
        };
        const GAP: i32 = 6;
        let max_x = (rect.x + rect.width as i32 - size.width as i32).max(rect.x);
        let max_y = (rect.y + rect.height as i32 - size.height as i32).max(rect.y);
        let x = (anchor.x + anchor.width as i32 / 2 - size.width as i32 / 2).clamp(rect.x, max_x);
        let below = anchor.y + anchor.height as i32 + GAP;
        let above = anchor.y - size.height as i32 - GAP;
        let y = if below + size.height as i32 <= rect.y + rect.height as i32 || above < rect.y {
            below
        } else {
            above
        }
        .clamp(rect.y, max_y);
        Rect::new(x, y, size.width, size.height)
    }

    /// The font the bubble draws its label with: the resolved `style.font` when set, otherwise the
    /// caller-configured `font_size` in the crate's default sans-serif face.
    ///
    /// Named once so `preferred_size` (the hint) and `draw` cannot measure with different fonts
    /// (D09-STYLE-02). The theme body font reaches a tooltip through `style.font`, so a text-scale
    /// preference now enlarges the bubble as well as its ink.
    fn bubble_font(&self) -> Font {
        self.style().font.clone().unwrap_or_else(|| Font::simple("sans-serif", self.font_size))
    }
}

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())),
            "wrap" => Ok(CapabilityValue::Bool(self.wrap())),
            _ => 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(())
            }
            "wrap" => {
                self.set_wrap(expect_bool(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["text", "shown", "wrap", 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();
        // One theme-manager read supplies both the window fill and the fallback ink; the
        // previous path resolved a separate widget style and then took the manager lock again
        // for the same frame (G-P13).
        let (window_fill, theme_ink) = {
            let manager = crate::style::theme_manager();
            match manager.current_theme() {
                Some(active) => (active.colors.background, Some(active.colors.foreground)),
                None => (Color::WHITE, None),
            }
        };
        let ink = style.text_color.or(theme_ink).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())
                }
            },
        };
        // 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 = self.bubble_font();

        // ── What is painted ──
        //
        // The plain label is wrapped into lines only when the caller enabled wrapping;
        // without it the vector holds exactly the one label the control has always drawn, so
        // the single-line path below is byte-identical to the pre-wrap one. A rich-text run
        // set is painted on one line in order and ignores wrapping.
        let label = if self.text.is_empty() { "Tooltip" } else { self.text.as_str() };
        let lines = if self.spans.is_empty() {
            self.wrapped_lines(context, label, &font)
        } else {
            Rc::new(Vec::new())
        };

        // Measured content width: the widest wrapped line, or every rich run's advance in a
        // row. Either way the bubble is capped by `max_width` and by the control itself.
        let text_width = if self.spans.is_empty() {
            // The wrap cache measured every line when it built them; a still frame reads the
            // widest one instead of measuring the whole label again (M-11).
            self.wrap_cache.borrow().as_ref().map(|cache| cache.width).unwrap_or(0)
        } else {
            let widths = self.span_widths(context, &font);
            widths.iter().fold(0u32, |total, width| total.saturating_add(*width))
        };

        // ── The bubble actually painted ──
        //
        // A tooltip is a **bubble of its own height**, centred in the area it was given (or
        // placed against its anchor), 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
        // [`dimensions::TOOLTIP_HEIGHT`] for a single line and the measured line count plus
        // padding once wrapping is on, and the width is the label's own advance plus
        // [`dimensions::TOOLTIP_PADDING_H`].
        let content_width = text_width.min(self.max_width);
        let total_width = (content_width + dimensions::TOOLTIP_PADDING_H * 2).min(rect.width);
        let single_line = self.spans.is_empty() && !self.wrap;
        let measured_line_height = context.measure_text("M", &font).height.max(1);
        let bubble_height = if single_line || !self.spans.is_empty() {
            dimensions::TOOLTIP_HEIGHT
        } else {
            measured_line_height
                .saturating_mul(lines.len().max(1) as u32)
                .saturating_add(dimensions::TOOLTIP_PADDING_V * 2)
        };
        let bubble = self.bubble_rect(rect, Size::new(total_width.max(1), bubble_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.
        //
        // The band is widened by the fitted draw's own inset so a label that fits is neither
        // shifted nor elided by those 3 px. This was the single-line body, and the plain
        // unwrapped case still takes exactly this path once, so its frame is unchanged.
        let fit_inset = crate::render::TEXT_FIT_MARGIN as i32;
        if !self.spans.is_empty() {
            // Rich runs, left to right on the bubble's one line. Each run is fitted to what
            // is left of the bubble, so a long run elides rather than painting outside it.
            let mut x = bubble.x + dimensions::TOOLTIP_PADDING_H as i32;
            let right = bubble.x + bubble.width as i32 - dimensions::TOOLTIP_PADDING_H as i32;
            let widths = self.span_widths(context, &font);
            for (index, span) in self.spans.iter().enumerate() {
                if x >= right {
                    break;
                }
                let span_font = font.with_bold(span.bold);
                let advance = widths.get(index).copied().unwrap_or(0) as i32;
                let remaining = (right - x).max(1) as u32;
                let band = Rect::new(
                    x - fit_inset,
                    context.text_line(bubble, &span_font).y,
                    remaining.saturating_add((2 * fit_inset) as u32),
                    measured_line_height,
                );
                context.draw_text_fitted_cow(
                    band,
                    &span.text,
                    &span_font,
                    span.color.unwrap_or(text_color),
                    HorizontalAlignment::Left,
                );
                x += advance;
            }
        } else {
            let text_x = bubble.x + dimensions::TOOLTIP_PADDING_H as i32;
            let band_width = (bubble.width.saturating_sub(dimensions::TOOLTIP_PADDING_H * 2) as i32
                + 2 * fit_inset)
                .max(1) as u32;
            let line = context.text_line(bubble, &font);
            // The single-line band is the line box `text_line` derived, so the unwrapped
            // frame stays byte-identical; a wrapped bubble uses the measured line advance
            // so its rows cannot overlap.
            let band_height = if single_line { line.height.max(1) } else { measured_line_height };
            for (index, text) in lines.iter().enumerate() {
                let line_y = if single_line {
                    line.y
                } else {
                    bubble.y
                        + dimensions::TOOLTIP_PADDING_V as i32
                        + index as i32 * measured_line_height as i32
                };
                context.draw_text_fitted_cow(
                    Rect::new(text_x - fit_inset, line_y, band_width, band_height),
                    text,
                    &font,
                    text_color,
                    HorizontalAlignment::Left,
                );
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::Point;
    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);
    }

    /// The width estimate counts **characters**, not UTF-8 bytes: the old body used
    /// `text.len()`, so a CJK tooltip reserved roughly three times the room its own draw
    /// needed. `"你好世界"` is four characters (12 bytes) and must be no wider than four
    /// ASCII characters at the same font size.
    #[test]
    fn tooltip_preferred_size_counts_characters_not_bytes() {
        let ascii = Tooltip::new("abcd", Rect::new(0, 0, 600, 40));
        let cjk = Tooltip::new("你好世界", Rect::new(0, 0, 600, 40));
        assert_eq!(
            cjk.preferred_size().width,
            ascii.preferred_size().width,
            "four characters must measure the same whatever their byte length"
        );
        assert_eq!("你好世界".len(), 12, "12 bytes, so the byte-based estimate was 3x too wide");
    }

    #[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])
    }

    /// The `(y, height)` of the bubble's rounded rectangle in the document.
    fn bubble_box(svg: &str) -> (i32, i32) {
        let chunk = svg
            .split("<rect ")
            .find(|chunk| chunk.contains("rx=\""))
            .unwrap_or_else(|| panic!("the tooltip paints no rounded bubble:\n{svg}"));
        let y = chunk
            .split("y=\"")
            .nth(1)
            .and_then(|rest| rest.split('"').next())
            .and_then(|value| value.parse::<i32>().ok())
            .expect("a bubble y");
        let height = chunk
            .split("height=\"")
            .nth(1)
            .and_then(|rest| rest.split('"').next())
            .and_then(|value| value.parse::<i32>().ok())
            .expect("a bubble height");
        (y, height)
    }

    /// Rich-text runs are painted in their own colours and weights.
    #[test]
    fn rich_text_spans_paint_their_own_runs() {
        let _guard = crate::style::theme_test_guard();
        let mut plain = Tooltip::new("Ctrl+S to save", Rect::new(0, 0, 200, 40));
        plain.show();
        let plain_svg = render_to_svg(&mut plain);
        assert!(!plain_svg.contains("rgba(255,0,0"));

        let mut rich = Tooltip::new("Ctrl+S to save", Rect::new(0, 0, 200, 40));
        rich.set_spans(vec![
            TooltipSpan::new("Ctrl+S").with_color(Color::rgb(255, 0, 0)).with_bold(true),
            TooltipSpan::new(" to save"),
        ]);
        rich.show();
        let rich_svg = render_to_svg(&mut rich);

        assert_eq!(rich.spans().len(), 2);
        assert!(
            rich_svg.contains("rgba(255,0,0,1.00)"),
            "the first run must paint in its own colour: {rich_svg}"
        );
        assert_ne!(plain_svg, rich_svg);

        rich.clear_spans();
        assert!(rich.spans().is_empty());
        assert_eq!(plain_svg, render_to_svg(&mut rich), "clearing restores the plain label");
    }

    /// An anchor places the bubble next to the thing it describes.
    #[test]
    fn an_anchor_places_the_bubble_next_to_it() {
        let mut free = Tooltip::new("hint", Rect::new(0, 0, 300, 300));
        free.show();
        let (free_y, _) = bubble_box(&render_to_svg(&mut free));

        let anchor = Rect::new(100, 100, 40, 20);
        let mut anchored = Tooltip::new("hint", Rect::new(0, 0, 300, 300));
        anchored.set_anchor_rect(anchor);
        anchored.show();
        let (anchored_y, _) = bubble_box(&render_to_svg(&mut anchored));

        assert_eq!(anchored.anchor_rect(), Some(anchor));
        assert!(
            anchored_y >= anchor.y + anchor.height as i32,
            "an anchored bubble sits below its anchor: bubble y={anchored_y}, anchor bottom={}",
            anchor.y + anchor.height as i32
        );
        assert_ne!(free_y, anchored_y, "the anchor must move the bubble");

        anchored.clear_anchor();
        assert_eq!(anchored.anchor_rect(), None);
        assert_eq!(free_y, bubble_box(&render_to_svg(&mut anchored)).0);
    }

    /// Wrapping breaks the label at spaces and grows the bubble a line at a time.
    #[test]
    fn wrapping_grows_the_bubble() {
        let long = "Tooltip words that must wrap onto more lines than one";
        let mut single = Tooltip::new(long, Rect::new(0, 0, 200, 80));
        single.show();
        let (_, single_height) = bubble_box(&render_to_svg(&mut single));

        let mut wrapped = Tooltip::new(long, Rect::new(0, 0, 200, 80));
        wrapped.set_wrap(true);
        wrapped.show();
        let (_, wrapped_height) = bubble_box(&render_to_svg(&mut wrapped));

        assert!(wrapped.wrap());
        assert_eq!(single_height, dimensions::TOOLTIP_HEIGHT as i32);
        assert!(
            wrapped_height > single_height,
            "a wrapped bubble needs more lines: single={single_height}, wrapped={wrapped_height}"
        );
        assert!(wrapped.preferred_size().height > single.preferred_size().height);
    }
}