lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
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
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
//! Built-in construction data and private operation-local appearance resolution.

#![deny(missing_docs)]

use std::sync::{Arc, Mutex, OnceLock};

use sha2::{Digest, Sha256};

use super::{
    AnnotationTextRoles, AnnotationTheme, AxisSpacing, AxisTextRoles, AxisTheme,
    CompositionTextRoles, ContrastTextRoles, FrameSides, FrameTheme, GuideTextRoles, LegendTheme,
    MarkTheme, RootTextRoles, StrokeTheme, Theme, TickTheme, TypographyTheme,
};
use crate::font::canonical::PreparedFontEnvironment;
use crate::layout::{
    PhysicalTextAlignment, ResolvedTextPlan, TextLineHeight, TextPlanInput, TextPlanProvenance,
};
use crate::style::LinePattern;
use crate::theme::{color_from_rgb, Color};
use crate::theme::{
    AccentPalette, ColorScales, DivergingGradient, OpaqueColor, QualitativePalette,
    SequentialGradient,
};
use crate::{text::TextWeight, Error};

/// Built-in axis tick-label font size in actual CSS pixels.
const TICK_FONT_SIZE: u32 = 16;

const MUTED_TEXT: (u8, u8, u8) = (80, 80, 80);
const SIGNIFICANCE_FONT_SIZE: u32 = 16;

/// A theme's full resolved visual specification. Layout and renderers consume
/// this value to produce concrete backend styles and layout decisions.
#[derive(Debug, Clone)]
pub(crate) struct ResolvedTheme {
    pub(crate) text_layouts: crate::text::roles::TextRoles,
    appearance: Theme,
    /// An explicit Plot inside Canvas composes over the Canvas owner's surface.
    pub(crate) canvas_surface_override: Option<Color>,
}

impl std::ops::Deref for ResolvedTheme {
    type Target = Theme;
    fn deref(&self) -> &Theme {
        &self.appearance
    }
}

impl std::ops::DerefMut for ResolvedTheme {
    fn deref_mut(&mut self) -> &mut Theme {
        &mut self.appearance
    }
}

#[derive(Debug, Default)]
struct TextQueryCache {
    profiles: Vec<usize>,
    entries: Vec<CachedTextQuery>,
    exact: Vec<TextQueryIndex>,
    shaping: Vec<TextQueryIndex>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct TextQueryIndex {
    fingerprint: [u8; 32],
    entry: usize,
}

impl TextQueryCache {
    fn profile_entry(&self, input: &TextPlanInput<'_>) -> Option<usize> {
        let (mut low, mut high) = (0, self.profiles.len());
        while low < high {
            let middle = low + (high - low) / 2;
            let index = self.profiles[middle];
            match self.compare_profile(index, input) {
                std::cmp::Ordering::Less => low = middle + 1,
                std::cmp::Ordering::Greater => high = middle,
                std::cmp::Ordering::Equal => {
                    if self.entries[index].appearance.stack.same(input.stack) {
                        return Some(index);
                    }
                    // Distinct literal stacks can share source/size/weight. They
                    // stay distinct; inspect only this equal-source interval.
                    for direction in [false, true] {
                        let mut position = middle;
                        loop {
                            position = if direction {
                                position + 1
                            } else {
                                let Some(previous) = position.checked_sub(1) else {
                                    break;
                                };
                                previous
                            };
                            if position == self.profiles.len() {
                                break;
                            }
                            let index = self.profiles[position];
                            if self.compare_profile(index, input) != std::cmp::Ordering::Equal {
                                break;
                            }
                            if self.entries[index].appearance.stack.same(input.stack) {
                                return Some(index);
                            }
                        }
                    }
                    return None;
                }
            }
        }
        None
    }

    fn compare_profile(&self, index: usize, input: &TextPlanInput<'_>) -> std::cmp::Ordering {
        let entry = &self.entries[index];
        let metadata = (
            entry.direction as u8,
            entry.source.len(),
            entry.appearance.font_size.to_bits(),
            entry.appearance.weight as u8,
        )
            .cmp(&(
                input.direction as u8,
                input.source.len(),
                input.font_size.to_bits(),
                input.weight as u8,
            ));
        if metadata != std::cmp::Ordering::Equal {
            return metadata;
        }
        if std::ptr::eq(entry.source.as_str(), input.source) {
            return std::cmp::Ordering::Equal;
        }
        for index in 0..input.source.len() {
            let ordering = entry.source.as_bytes()[index].cmp(&input.source.as_bytes()[index]);
            if ordering != std::cmp::Ordering::Equal {
                return ordering;
            }
        }
        std::cmp::Ordering::Equal
    }

    fn profile_insertion_point(&self, input: &TextPlanInput<'_>) -> usize {
        let (mut low, mut high) = (0, self.profiles.len());
        while low < high {
            let middle = low + (high - low) / 2;
            if self.compare_profile(self.profiles[middle], input) == std::cmp::Ordering::Less {
                low = middle + 1;
            } else {
                high = middle;
            }
        }
        low
    }

    fn query_key(&self, input: &TextPlanInput<'_>, preferred_lines: Option<usize>) -> TextQueryKey {
        let shaping_entry = self.profile_entry(input);

        let shaping_state = if let Some(index) = shaping_entry {
            self.entries[index].shaping_state.clone()
        } else {
            CachedTextQuery::shaping_state(input)
        };
        TextQueryKey {
            shaping_entry,
            shaping_fingerprint: shaping_state.clone().finalize().into(),
            fingerprint: CachedTextQuery::presentation_fingerprint(
                shaping_state.clone(),
                input,
                preferred_lines,
            ),
            shaping_state,
            observed_entries: self.entries.len(),
        }
    }
    fn lower_bound(index: &[TextQueryIndex], fingerprint: [u8; 32]) -> usize {
        let (mut low, mut high) = (0, index.len());
        while low < high {
            let middle = low + (high - low) / 2;
            if index[middle].fingerprint < fingerprint {
                low = middle + 1;
            } else {
                high = middle;
            }
        }
        low
    }

    fn find_query(
        &self,
        index: &[TextQueryIndex],
        fingerprint: [u8; 32],
        key: (&TextPlanInput<'_>, Option<usize>),
        exact: bool,

        shaping_entry: Option<usize>,
    ) -> Option<usize> {
        let (input, preferred_lines) = key;
        let start = Self::lower_bound(index, fingerprint);
        for candidate in &index[start..] {
            if candidate.fingerprint != fingerprint {
                break;
            }
            let query = &self.entries[candidate.entry];
            if shaping_entry == Some(query.shaping_entry)
                && (!exact
                    || (query.width == input.maximum_width_quanta
                        && query.matches_presentation(input, preferred_lines)))
            {
                return Some(candidate.entry);
            }
        }
        None
    }

    fn reserve<T>(values: &mut Vec<T>) -> Result<(), Error> {
        if values.len() < values.capacity() {
            return Ok(());
        }
        let capacity = values
            .len()
            .checked_add(1)
            .and_then(|required| {
                values
                    .capacity()
                    .checked_mul(2)
                    .map(|doubled| required.max(doubled))
            })
            .ok_or_else(|| Error::Render("text query cache capacity overflow".into()))?;

        crate::operation::vector(values, capacity - values.len())?;
        values
            .try_reserve_exact(capacity - values.len())
            .map_err(|_| Error::Render("cannot reserve text query cache".into()))
    }

    fn insertion_point(index: &[TextQueryIndex], value: TextQueryIndex) -> usize {
        let (mut low, mut high) = (0, index.len());
        while low < high {
            let middle = low + (high - low) / 2;
            if index[middle] < value {
                low = middle + 1;
            } else {
                high = middle;
            }
        }
        low
    }
}

#[derive(Debug)]
struct CachedTextQuery {
    direction: crate::text::TextDirection,
    shaping_entry: usize,
    shaping_state: Sha256,
    source: Arc<String>,
    appearance: TextTheme,
    alignment: PhysicalTextAlignment,
    owner: String,
    pair_ordinal: u32,
    exact_override: bool,
    width: i64,
    preferred_lines: Option<usize>,
    unwrapped_width: Option<i64>,
    result: CachedTextResult,
}

#[derive(Debug, Clone)]
enum CachedTextResult {
    Plan(ResolvedTextPlan),
    /// Lookup-only result: reuse analysis, never this plan's width-specific lines.
    Reflow(ResolvedTextPlan),
    PreferredWidth(i64),
}

struct TextQueryKey {
    observed_entries: usize,
    shaping_entry: Option<usize>,
    shaping_state: Sha256,
    shaping_fingerprint: [u8; 32],
    fingerprint: [u8; 32],
}

impl CachedTextQuery {
    fn shaping_state(input: &TextPlanInput<'_>) -> Sha256 {
        let mut hash = Sha256::new();
        // The complete, unnormalized source fixes paragraph bidi and scripts;
        // language and Unicode policy are fixed for this renderer. The memo is
        // shared only together with its immutable operation font environment.
        hash.update((input.source.len() as u64).to_le_bytes());
        hash.update(input.source.as_bytes());
        hash.update([input.direction as u8]);
        input.stack.hash_into(&mut hash);

        hash.update(input.font_size.to_le_bytes());
        hash.update([match input.weight {
            TextWeight::Normal => 0,
            TextWeight::Semibold => 1,
            TextWeight::Bold => 2,
        }]);
        hash
    }

    fn presentation_fingerprint(
        mut hash: Sha256,
        input: &TextPlanInput<'_>,
        preferred_lines: Option<usize>,
    ) -> [u8; 32] {
        hash.update((input.provenance.owner.len() as u64).to_le_bytes());
        hash.update(input.provenance.owner.as_bytes());
        hash.update(input.provenance.pair_ordinal.to_le_bytes());
        hash.update(input.maximum_width_quanta.to_le_bytes());
        hash.update([match input.alignment {
            PhysicalTextAlignment::Start => 0,
            PhysicalTextAlignment::Center => 1,
            PhysicalTextAlignment::End => 2,
        }]);
        match input.line_height {
            TextLineHeight::Multiplier(value) => {
                hash.update([0]);
                hash.update(value.to_bits().to_le_bytes());
            }
            TextLineHeight::ResolvedQuanta(value) => {
                hash.update([1]);
                hash.update(value.to_le_bytes());
            }
        }
        hash.update([
            input.paint.red(),
            input.paint.green(),
            input.paint.blue(),
            u8::from(input.exact_override),
        ]);
        hash.update(input.paint.get_alpha().to_bits().to_le_bytes());
        hash.update([u8::from(preferred_lines.is_some())]);
        if let Some(lines) = preferred_lines {
            hash.update((lines as u64).to_le_bytes());
        }
        hash.finalize().into()
    }

    fn matches_presentation(
        &self,
        input: &TextPlanInput<'_>,
        preferred_lines: Option<usize>,
    ) -> bool {
        self.appearance.paint == input.paint
            && input.line_height
                == TextLineHeight::Multiplier(self.appearance.line_height_multiplier)
            && self.alignment == input.alignment
            && self.pair_ordinal == input.provenance.pair_ordinal
            && self.exact_override == input.exact_override
            && self.preferred_lines == preferred_lines
            && crate::font::canonical::same_bytes(&self.owner, &input.provenance.owner)
    }

    fn matches_width(&self, width: i64) -> bool {
        self.width == width
            || self
                .unwrapped_width
                .is_some_and(|required| required <= width)
    }
}

impl PartialEq for ResolvedTheme {
    fn eq(&self, other: &Self) -> bool {
        self.non_text_eq(other)
            && self.axes == other.axes
            && self.legend == other.legend
            && self.composition == other.composition
            && self.typography == other.typography
            && self.text_layouts == other.text_layouts
    }
}

impl ResolvedTheme {
    pub(crate) fn apply_text_defaults(&mut self, kind: crate::plots::PlotKind) {
        if kind == crate::plots::PlotKind::Heatmap {
            for side in 0..2 {
                if self.text_layouts.ticks[side].is_none() {
                    self.text_layouts.ticks[side] = Some(
                        crate::text::TextLayout::default()
                            .wrapping(crate::text::TextWrapping::NoSoftWrap)
                            .overflow(crate::text::TextOverflow::ellipsis(
                                crate::text::TextEllipsis::new(crate::text::TextElision::End)
                                    .marker("...")
                                    .distinct(true),
                                crate::text::TextFailure::Error,
                            )),
                    );
                }
            }
        }
    }
    pub(crate) fn tick_text_appearance(
        &self,
        side: crate::layout::AxisSide,
    ) -> crate::text::TextAppearance<'_> {
        crate::text::TextAppearance::from(&self.typography.axes.tick_label).layout(
            self.text_layouts.ticks[usize::from(side == crate::layout::AxisSide::Left)].as_ref(),
        )
    }
    pub(crate) fn guide_text_appearance(
        &self,
        role: crate::guides::GuideTextRole,
    ) -> crate::text::TextAppearance<'_> {
        crate::text::TextAppearance::from(if role == crate::guides::GuideTextRole::Title {
            &self.typography.guides.legend_title
        } else {
            &self.typography.guides.legend_label
        })
        .layout(self.text_layouts.guide[role.index()].as_ref())
    }
    pub(crate) fn new(appearance: Theme) -> Result<Self, Error> {
        appearance.validate()?;
        Ok(Self {
            appearance,
            text_layouts: crate::text::roles::TextRoles::default(),
            canvas_surface_override: None,
        })
    }

    fn non_text_eq(&self, other: &Self) -> bool {
        self.color_scales == other.color_scales
            && self.surfaces == other.surfaces
            && self.canvas_surface_override == other.canvas_surface_override
            && self.marks == other.marks
            && self.annotations == other.annotations
    }
}

impl ResolvedTheme {
    #[expect(
        clippy::type_complexity,
        clippy::ref_option,
        reason = "retains the original optional direction projection and comparison boundary"
    )]
    pub(crate) fn same_validated(
        &self,
        other: &Self,
        direction: &Option<(
            [(f64, f64); 2],
            crate::layout::PixelRect,
            [Option<Vec<(f64, f64)>>; 2],
            Option<String>,
        )>,
        current: Option<crate::text::orientation::TextReferenceResolver<'_, '_>>,
    ) -> Result<bool, Error> {
        if !self.axes.same_validated(&other.axes)? {
            return Ok(false);
        }
        if !self.legend.same(&other.legend) {
            return Ok(false);
        }
        if !self.composition.same(&other.composition) {
            return Ok(false);
        }
        if !self.non_text_eq(other)
            || !direction
                .as_ref()
                .zip(current)
                .is_none_or(|(saved, current)| current.matches_snapshot(saved))
            || self.text_layouts != other.text_layouts
        {
            return Ok(false);
        }
        for (left, right) in self
            .typography
            .roles()
            .into_iter()
            .zip(other.typography.roles())
        {
            if !left.same(right) {
                return Ok(false);
            }
        }
        Ok(true)
    }

    /// Select a complete text role over one final variable-fill paint before
    /// font preparation, using owner-local panel/root surfaces and backdrop.
    pub(crate) fn contrasting_text(&self, fill: Color) -> Result<&TextTheme, Error> {
        super::contrast::select(
            fill,
            self.surfaces.get_plot_panel(),
            self.canvas_surface_override
                .unwrap_or(self.surfaces.get_canvas_root()),
            self.annotations.get_planning_backdrop().into(),
            self.typography.get_annotations().get_contrast().get_light(),
            self.typography.get_annotations().get_contrast().get_dark(),
        )
    }
}

/// One operation's font preparation and optional text/guide memo tables.
#[derive(Debug, Default)]
pub(crate) struct TextService {
    pub(crate) fonts: OnceLock<PreparedFontEnvironment>,
    queries: Mutex<TextQueryCache>,
    pub(crate) guides: Mutex<crate::decorations::legend::GuideMeasurements>,
}

impl TextService {
    /// Initialize this operation's canonical system-font environment.
    pub(crate) fn prepare_font_environment(&self) -> Result<(), Error> {
        self.prepared_font_environment().map(|_| ())
    }

    pub(crate) fn prepare_font_environment_from_census(
        &self,
        census: &mut crate::layout::PreparedTextCensus,
        presence: Vec<u64>,
        prepared_stage: &mut crate::layout::kernel::PreparedStage<'_>,
    ) -> Result<(), Error> {
        if self.fonts.get().is_none() {
            let environment = census
                .prepare_system_fonts(presence, prepared_stage)
                .map_err(|error| Error::from(error).with_prefix("font preflight"))?;
            self.fonts
                .set(environment)
                .map_err(|_| Error::Render("font environment already prepared".into()))?;
        }
        Ok(())
    }

    /// Borrow this operation's prepared canonical font environment.
    pub(crate) fn prepared_font_environment(&self) -> Result<&PreparedFontEnvironment, Error> {
        #[cfg(test)]
        if self.fonts.get().is_none() {
            let environment = PreparedFontEnvironment::discover_system()
                .map_err(|error| Error::from(error).with_prefix("font preflight"))?;
            let _ = self.fonts.set(environment);
        }
        self.fonts.get().ok_or_else(|| {
            Error::Render("font environment was requested before canonical text preparation".into())
        })
    }
}

impl crate::text::TextRequestContext<'_, '_> {
    pub(crate) fn measure_appearance_text<'a>(
        &self,
        source: &str,
        appearance: impl Into<crate::text::TextAppearance<'a>>,
        alignment: PhysicalTextAlignment,
        owner: &str,
    ) -> Result<ResolvedTextPlan, Error> {
        crate::layout::fit::measured(crate::layout::text::request::measure_quanta(
            self,
            source,
            appearance.into(),
            i64::MAX,
            alignment,
            owner,
            &crate::layout::fit::ROOT_SCOPE,
        ))
        .map_err(crate::layout::fit::PlanError::into_error)
    }
    /// Plan one foundational appearance within an exact finite pixel width.
    #[cfg(test)]
    pub(crate) fn plan_text(
        &self,
        source: &str,
        appearance: &TextTheme,
        maximum_width: f64,
        alignment: PhysicalTextAlignment,
        owner: &str,
        exact_override: bool,
    ) -> Result<ResolvedTextPlan, Error> {
        if !maximum_width.is_finite() || maximum_width <= 0.0 {
            return Err(Error::Render(
                format!("{owner} has no positive finite width available for text layout").into(),
            ));
        }
        let maximum_width_quanta = crate::layout::maximum_width_quanta(maximum_width)
            .map_err(|error| Error::from(error).with_prefix(&format!("{owner} text planning")))?;
        self.plan_text_quanta(
            source,
            appearance,
            maximum_width_quanta,
            alignment,
            owner,
            exact_override,
        )
    }

    /// Common label width from contextual legal spans and the assigned row capacity.
    #[expect(
        clippy::cast_precision_loss,
        reason = "axis label requirements are normalized layout quanta consumed by pixel adapters"
    )]
    pub(crate) fn intrinsic_tick_label_width<'a>(
        &self,
        labels: impl Iterator<Item = &'a str> + Clone,
        available_height: f64,
    ) -> Result<f64, crate::Error> {
        self.text.prepare_font_environment()?;
        let environment = self.text.prepared_font_environment()?;

        let appearance = self.typography.get_axes().get_tick_label();
        let height = crate::layout::maximum_width_quanta(available_height)
            .map_err(|error| Error::from(error).with_prefix("axis row height"))?;
        let count = i64::try_from(labels.clone().count().max(1))
            .map_err(|_| crate::Error::Render("axis row count overflowed".into()))?;
        let pitch = crate::layout::maximum_width_quanta(appearance.line_pitch_pixels())
            .map_err(|error| Error::from(error).with_prefix("axis row pitch"))?;
        if height < 0 || pitch <= 0 {
            return Err(crate::Error::Render(
                "axis row allocation requires nonnegative height and positive text pitch".into(),
            ));
        }
        let preferred_lines = usize::try_from(((height / count - 4096).max(0) / pitch).max(1))
            .map_err(|_| crate::Error::Render("axis row capacity overflowed".into()))?;
        let mut width = 1_i64;
        for source in labels {
            let mut input = crate::layout::TextPlanInput {
                size_trace: None,
                direction: crate::text::TextDirection::Auto,
                source,
                stack: &appearance.stack,
                weight: appearance.weight,
                font_size: appearance.font_size,
                line_height: crate::layout::TextLineHeight::Multiplier(
                    appearance.line_height_multiplier,
                ),
                maximum_width_quanta: i64::MAX,
                alignment: PhysicalTextAlignment::End,
                paint: appearance.paint,
                provenance: crate::layout::TextPlanProvenance {
                    pair_ordinal: 0,
                    owner: "y-axis tick label".into(),
                },
                exact_override: false,
            };
            input.provenance.pair_ordinal = environment
                .admit_text(&appearance.stack, appearance.weight.into(), source, None)
                .map_err(|error| Error::from(error).with_prefix("axis intrinsic text admission"))?;

            let (cached, query_key) = self.cached_text_query(&input, Some(preferred_lines))?;
            let preferred_width = if let Some(CachedTextResult::PreferredWidth(width)) = cached {
                width
            } else {
                let analysis = if let Some(CachedTextResult::Reflow(plan)) = cached {
                    plan
                } else {
                    let plan = environment.plan_text(input.clone()).map_err(|error| {
                        Error::from(error).with_prefix("axis intrinsic text analysis")
                    })?;
                    self.cache_text_query(
                        &input,
                        appearance,
                        None,
                        CachedTextResult::Plan(plan.clone()),
                        TextQueryKey {
                            fingerprint: CachedTextQuery::presentation_fingerprint(
                                query_key.shaping_state.clone(),
                                &input,
                                None,
                            ),
                            shaping_state: query_key.shaping_state.clone(),
                            ..query_key
                        },
                    )?;
                    plan
                };
                let requirements =
                    analysis
                        .intrinsic_from_analysis(preferred_lines)
                        .map_err(|error| {
                            Error::from(error).with_prefix("axis intrinsic text requirements")
                        })?;
                self.cache_text_query(
                    &input,
                    appearance,
                    Some(preferred_lines),
                    CachedTextResult::PreferredWidth(requirements.preferred_width_quanta),
                    query_key,
                )?;
                requirements.preferred_width_quanta
            };
            width = width.max(preferred_width);
        }
        Ok(width as f64 / 1024.0)
    }

    /// Measure one foundational appearance without introducing a wrap boundary.
    pub(crate) fn measure_text(
        &self,
        source: &str,
        appearance: &TextTheme,
        alignment: PhysicalTextAlignment,
        owner: &str,
        exact_override: bool,
    ) -> Result<ResolvedTextPlan, Error> {
        self.plan_text_quanta(
            source,
            appearance,
            i64::MAX,
            alignment,
            owner,
            exact_override,
        )
    }

    fn plan_text_quanta(
        &self,
        source: &str,
        appearance: &TextTheme,
        maximum_width_quanta: i64,
        alignment: PhysicalTextAlignment,
        owner: &str,
        exact_override: bool,
    ) -> Result<ResolvedTextPlan, Error> {
        self.plan_text_quanta_scoped(
            source,
            appearance,
            maximum_width_quanta,
            alignment,
            owner,
            exact_override,
            crate::text::TextDirection::Auto,
            &crate::layout::fit::ROOT_SCOPE,
        )
        .map_err(crate::layout::fit::PlanError::into_error)
    }

    #[expect(
        clippy::too_many_arguments,
        reason = "the shared adapter preserves every immutable text-plan input and the consuming fit scope"
    )]
    pub(crate) fn plan_text_quanta_scoped(
        &self,
        source: &str,
        appearance: &TextTheme,
        maximum_width_quanta: i64,
        alignment: PhysicalTextAlignment,
        owner: &str,
        exact_override: bool,
        direction: crate::text::TextDirection,
        scope: &crate::layout::fit::FitScope,
    ) -> Result<ResolvedTextPlan, crate::layout::fit::PlanError> {
        let mut input = TextPlanInput {
            size_trace: self.trial.size_trace.cloned(),
            direction,
            source,
            stack: appearance.get_stack(),
            weight: appearance.get_weight(),
            font_size: appearance.get_font_size(),
            line_height: TextLineHeight::Multiplier(appearance.get_line_height()),
            maximum_width_quanta,
            alignment,
            paint: appearance.get_color(),
            provenance: TextPlanProvenance {
                pair_ordinal: 0,
                owner: owner.to_owned(),
            },
            exact_override,
        };
        let environment = self.text.prepared_font_environment()?;
        input.provenance.pair_ordinal = environment
            .admit_text(
                appearance.get_stack(),
                appearance.get_weight().into(),
                source,
                None,
            )
            .map_err(|error| Error::from(error).with_prefix(&format!("{owner} text admission")))?;

        // Size trials are deliberately not optional-cache entries: failed glyph
        // arrays and their certificates die with this local candidate.
        if self.trial.size_trace.is_some() {
            return environment.plan_text(input).map_err(|error| match error {
                crate::layout::TextPlanError::Fit(miss) => scope
                    .failure(
                        crate::layout::fit::FitKind::Text,
                        format!("{owner} text planning: {miss}"),
                    )
                    .into(),
                error => crate::layout::fit::PlanError::Fatal(
                    Error::from(error).with_prefix(&format!("{owner} text planning")),
                ),
            });
        }
        let (cached, query_key) = self.cached_text_query(&input, None)?;

        let result = match cached {
            Some(CachedTextResult::Plan(plan)) => return Ok(plan),
            Some(CachedTextResult::Reflow(plan)) => {
                let (source, stack) = plan.analysis_profile().map_err(Error::from)?;
                plan.reflow(TextPlanInput {
                    source,
                    stack,
                    ..input.clone()
                })
            }
            _ => environment.plan_text(input.clone()),
        };
        let plan = result.map_err(|error| match error {
            crate::layout::TextPlanError::Fit(miss) => scope
                .failure(
                    crate::layout::fit::FitKind::Text,
                    format!("{owner} text planning: {miss}"),
                )
                .into(),
            error => crate::layout::fit::PlanError::Fatal(
                Error::from(error).with_prefix(&format!("{owner} text planning")),
            ),
        })?;
        self.cache_text_query(
            &input,
            appearance,
            None,
            CachedTextResult::Plan(plan.clone()),
            query_key,
        )?;

        Ok(plan)
    }

    fn cached_text_query(
        &self,
        input: &TextPlanInput<'_>,
        preferred_lines: Option<usize>,
    ) -> Result<(Option<CachedTextResult>, TextQueryKey), Error> {
        let cache = self
            .text
            .queries
            .lock()
            .map_err(|_| Error::Render("text query cache lock poisoned".into()))?;
        let query_key = cache.query_key(input, preferred_lines);
        let shaping_fingerprint = query_key.shaping_fingerprint;
        let fingerprint = query_key.fingerprint;
        let key = (input, preferred_lines);
        if let Some(index) = cache.find_query(
            &cache.exact,
            fingerprint,
            key,
            true,
            query_key.shaping_entry,
        ) {
            return Ok((Some(cache.entries[index].result.clone()), query_key));
        }
        if let Some(index) = cache.find_query(
            &cache.shaping,
            shaping_fingerprint,
            key,
            false,
            query_key.shaping_entry,
        ) {
            let query = &cache.entries[index];

            if query.matches_width(input.maximum_width_quanta)
                && query.matches_presentation(input, preferred_lines)
            {
                return Ok((Some(query.result.clone()), query_key));
            }
            if let CachedTextResult::Plan(plan) = &query.result {
                return Ok((Some(CachedTextResult::Reflow(plan.clone())), query_key));
            }
        }
        Ok((None, query_key))
    }

    #[expect(
        clippy::too_many_lines,
        reason = "key proof, storage reservation, index insertion and payload freezing stay in one cache transaction"
    )]
    fn cache_text_query(
        &self,
        input: &TextPlanInput<'_>,
        appearance: &TextTheme,
        preferred_lines: Option<usize>,
        result: CachedTextResult,
        mut query_key: TextQueryKey,
    ) -> Result<(), Error> {
        let mut cache = self
            .text
            .queries
            .lock()
            .map_err(|_| Error::Render("text query cache lock poisoned".into()))?;
        // This root-local memo is optional and bounded, never an all-width table.
        if cache.entries.len() == 256 {
            return Ok(());
        }

        if query_key.shaping_entry.is_none() && cache.entries.len() != query_key.observed_entries {
            query_key.shaping_entry = cache.profile_entry(input);
        }

        let shaping_fingerprint = query_key.shaping_fingerprint;
        let fingerprint = query_key.fingerprint;
        let key = (input, preferred_lines);
        if cache
            .find_query(
                &cache.exact,
                fingerprint,
                key,
                true,
                query_key.shaping_entry,
            )
            .is_some()
        {
            return Ok(());
        }
        let new_shaping = matches!(&result, CachedTextResult::Plan(_))
            && cache
                .find_query(
                    &cache.shaping,
                    shaping_fingerprint,
                    key,
                    false,
                    query_key.shaping_entry,
                )
                .is_none();

        TextQueryCache::reserve(&mut cache.entries)?;
        TextQueryCache::reserve(&mut cache.exact)?;
        if new_shaping {
            TextQueryCache::reserve(&mut cache.shaping)?;
            TextQueryCache::reserve(&mut cache.profiles)?;
        }
        let exact_record = TextQueryIndex {
            fingerprint,
            entry: cache.entries.len(),
        };
        let shaping_record = TextQueryIndex {
            fingerprint: shaping_fingerprint,
            entry: cache.entries.len(),
        };
        let exact_position = TextQueryCache::insertion_point(&cache.exact, exact_record);
        let shaping_position = if new_shaping {
            Some(TextQueryCache::insertion_point(
                &cache.shaping,
                shaping_record,
            ))
        } else {
            None
        };
        let profile_position = if new_shaping {
            Some(cache.profile_insertion_point(input))
        } else {
            None
        };
        let copy = |text: &str| -> Result<String, Error> {
            let mut owned = String::new();
            crate::operation::string(&owned, text.len())?;
            owned
                .try_reserve_exact(text.len())
                .map_err(|_| Error::Render("cannot reserve text query key".into()))?;
            owned.push_str(text);
            Ok(owned)
        };
        let appearance = TextTheme::new(
            appearance.get_stack().clone(),
            appearance.get_color(),
            appearance.get_font_size(),
            appearance.get_weight(),
            appearance.get_line_height(),
        )?;
        let source = if let Some(index) = query_key.shaping_entry {
            Arc::clone(&cache.entries[index].source)
        } else {
            Arc::new(copy(input.source)?)
        };
        cache.entries.push(CachedTextQuery {
            direction: input.direction,
            shaping_entry: query_key.shaping_entry.unwrap_or(exact_record.entry),
            shaping_state: query_key.shaping_state,
            unwrapped_width: match &result {
                CachedTextResult::Plan(plan) => plan
                    .unwrapped_fit_width()
                    .map_err(|error| Error::from(error).with_prefix("cached paragraph fit"))?,
                CachedTextResult::PreferredWidth(_) | CachedTextResult::Reflow(_) => None,
            },
            source,
            appearance,
            alignment: input.alignment,
            owner: copy(&input.provenance.owner)?,
            pair_ordinal: input.provenance.pair_ordinal,
            exact_override: input.exact_override,
            width: input.maximum_width_quanta,
            preferred_lines,
            result,
        });
        cache.exact.insert(exact_position, exact_record);
        if let Some(position) = shaping_position {
            cache.shaping.insert(position, shaping_record);
        }
        if let Some(position) = profile_position {
            cache.profiles.insert(position, exact_record.entry);
        }
        Ok(())
    }
}

#[cfg(test)]
const fn pair_ordinal(weight: TextWeight) -> u32 {
    match weight {
        TextWeight::Normal => 0,
        TextWeight::Semibold => 1,
        TextWeight::Bold => 2,
    }
}

/// Paints applied to renderer-owned drawing surfaces.
#[derive(Debug, Clone, PartialEq)]
pub struct SurfaceTheme {
    /// Canvas root paint.
    pub(crate) canvas_root: Color,
    /// Plot panel paint.
    pub(crate) plot_panel: Color,
}

impl SurfaceTheme {
    /// Construct complete surface paints; transparent paints are valid.
    pub fn new(canvas_root: Color, plot_panel: Color) -> Result<Self, Error> {
        Ok(Self {
            canvas_root,
            plot_panel,
        })
    }

    /// Inspect the complete Canvas root paint.
    pub fn get_canvas_root(&self) -> Color {
        self.canvas_root
    }

    /// Inspect the complete Plot panel paint.
    pub fn get_plot_panel(&self) -> Color {
        self.plot_panel
    }

    /// Replace only the Canvas root paint.
    pub fn canvas_root(self, canvas_root: Color) -> Result<Self, Error> {
        Self::new(canvas_root, self.plot_panel)
    }

    /// Replace only the Plot panel paint.
    pub fn plot_panel(self, plot_panel: Color) -> Result<Self, Error> {
        Self::new(self.canvas_root, plot_panel)
    }
}

/// Complete text appearance for one semantic typography role.
#[derive(Debug, Clone, PartialEq)]
pub struct TextTheme {
    /// Ordered literal named and host-generic family preferences.
    pub(crate) stack: crate::font::canonical::FontStack,
    /// Text paint.
    pub(crate) paint: Color,
    /// Font size in actual CSS pixels.
    pub(crate) font_size: f64,
    /// Closed renderer-owned font weight.
    pub(crate) weight: TextWeight,
    /// Finite positive multiple of the font size used for line pitch.
    pub(crate) line_height_multiplier: f64,
}

// Public construction/edits admit only finite positive leading, so complete
// field equality is reflexive and has no signed-zero normalization ambiguity.
impl Eq for TextTheme {}

impl TextTheme {
    /// Construct one complete text role, using actual CSS pixels and a multiplier.
    pub fn new(
        stack: crate::font::canonical::FontStack,
        color: Color,
        font_size: f64,
        weight: TextWeight,
        line_height: f64,
    ) -> Result<Self, Error> {
        let value = Self {
            stack,
            paint: color,
            font_size,
            weight,
            line_height_multiplier: line_height,
        };
        value.validate()?;
        Ok(value)
    }

    pub(crate) fn validate(&self) -> Result<(), Error> {
        if !self.font_size.is_finite() || self.font_size <= 0.0 {
            return Err(Error::Data(
                "text font size must be positive CSS pixels".into(),
            ));
        }
        if !self.line_height_multiplier.is_finite() || self.line_height_multiplier <= 0.0 {
            return Err(Error::Data(
                "text line height must be a finite positive multiplier".into(),
            ));
        }
        Ok(())
    }

    /// Borrow this role's complete ordered font preferences.
    pub fn get_stack(&self) -> &crate::font::canonical::FontStack {
        &self.stack
    }

    /// Inspect the complete text paint.
    pub fn get_color(&self) -> Color {
        self.paint
    }

    /// Inspect the positive font size in actual CSS pixels.
    pub fn get_font_size(&self) -> f64 {
        self.font_size
    }

    /// Inspect the closed font weight.
    pub fn get_weight(&self) -> TextWeight {
        self.weight
    }

    /// Inspect the retained multiplier, without multiplying by the font size.
    pub fn get_line_height(&self) -> f64 {
        self.line_height_multiplier
    }

    /// Replace only the complete font stack.
    pub fn stack(self, stack: crate::font::canonical::FontStack) -> Result<Self, Error> {
        Self::new(
            stack,
            self.paint,
            self.font_size,
            self.weight,
            self.line_height_multiplier,
        )
    }

    /// Replace only the complete text paint.
    pub fn color(self, color: Color) -> Result<Self, Error> {
        Self::new(
            self.stack,
            color,
            self.font_size,
            self.weight,
            self.line_height_multiplier,
        )
    }

    /// Replace only the positive CSS font size.
    pub fn font_size(self, font_size: f64) -> Result<Self, Error> {
        Self::new(
            self.stack,
            self.paint,
            font_size,
            self.weight,
            self.line_height_multiplier,
        )
    }

    /// Replace only the font weight.
    pub fn weight(self, weight: TextWeight) -> Result<Self, Error> {
        Self::new(
            self.stack,
            self.paint,
            self.font_size,
            weight,
            self.line_height_multiplier,
        )
    }

    /// Replace only the finite positive line-height multiplier.
    pub fn line_height(self, line_height: f64) -> Result<Self, Error> {
        Self::new(
            self.stack,
            self.paint,
            self.font_size,
            self.weight,
            line_height,
        )
    }

    pub(crate) fn same(&self, other: &Self) -> bool {
        self.font_size.to_bits() == other.font_size.to_bits()
            && self.weight == other.weight
            && self.paint == other.paint
            && self.line_height_multiplier.to_bits() == other.line_height_multiplier.to_bits()
            && self.stack.same(&other.stack)
    }

    pub(crate) fn try_copy(&self) -> Result<Self, Error> {
        Self::new(
            self.stack.try_copy().map_err(Error::from)?,
            self.get_color(),
            self.get_font_size(),
            self.get_weight(),
            self.get_line_height(),
        )
    }
    /// Resolve this role's current line pitch in pixels.
    pub(crate) fn line_pitch_pixels(&self) -> f64 {
        self.font_size * self.line_height_multiplier
    }
}

#[allow(
    clippy::too_many_arguments,
    clippy::too_many_lines,
    reason = "the four closed presets provide one compact table of preserved scalar values"
)]
fn resolved_theme(
    colors: &[(u8, u8, u8)],
    foreground: (u8, u8, u8),
    axis_width: f32,
    bracket_width: f32,
    title_font_size: u32,
    subtitle_font_size: u32,
    caption_font_size: u32,
    axis_title_font_size: u32,
    grid_color: (u8, u8, u8),
) -> Result<Theme, Error> {
    let stack = crate::font::canonical::builtin_font_stack();
    let foreground_paint = color_from_rgb(foreground);
    let muted_paint = color_from_rgb(MUTED_TEXT);
    let opaque = |&(r, g, b): &(u8, u8, u8)| OpaqueColor::rgb(r, g, b);
    let color_scales = ColorScales::new(
        QualitativePalette::extendable(colors.iter().map(opaque))?,
        SequentialGradient::new(crate::theme::HEATMAP_SEQUENTIAL_STOPS)?,
        DivergingGradient::new(crate::theme::HEATMAP_DIVERGING_STOPS)?,
    )?;
    let accents = AccentPalette::new(colors.iter().map(opaque))?;
    let stroke = |width, pattern| StrokeTheme::new(foreground_paint, width, pattern);
    let text = |paint, font_size: u32, line_height| {
        TextTheme::new(
            stack.clone(),
            paint,
            f64::from(font_size),
            TextWeight::Normal,
            line_height,
        )
    };

    let value = Theme {
        color_scales,
        surfaces: SurfaceTheme::new(Color::rgb(255, 255, 255), Color::rgb(255, 255, 255))?,
        typography: TypographyTheme::new(
            RootTextRoles::new(
                text(
                    foreground_paint,
                    title_font_size,
                    plus_six_line_height(title_font_size),
                )?,
                text(
                    muted_paint,
                    subtitle_font_size,
                    plus_six_line_height(subtitle_font_size),
                )?,
                text(
                    muted_paint,
                    caption_font_size,
                    plus_six_line_height(caption_font_size),
                )?,
            )?,
            AxisTextRoles::new(
                text(foreground_paint, axis_title_font_size, 1.2)?,
                text(foreground_paint, TICK_FONT_SIZE, 1.2)?,
            )?,
            GuideTextRoles::new(
                text(Color::rgb(60, 60, 60), 12, 1.2)?,
                text(Color::rgb(40, 40, 40), 11, 1.2)?,
            )?,
            CompositionTextRoles::new(
                text(foreground_paint, subtitle_font_size, 1.2)?,
                text(foreground_paint, title_font_size, 1.2)?,
                text(foreground_paint, title_font_size, 1.2)?,
                text(foreground_paint, axis_title_font_size, 1.2)?,
            )?,
            AnnotationTextRoles::new(
                text(foreground_paint, SIGNIFICANCE_FONT_SIZE, 1.2)?,
                text(foreground_paint, 14, 1.2)?,
                text(foreground_paint, 14, 1.2)?,
                text(foreground_paint, 10, 1.2)?,
                text(foreground_paint, 14, 1.2)?,
                ContrastTextRoles::new(
                    text(Color::rgb(255, 255, 255), 11, 1.2)?,
                    text(Color::rgb(0, 0, 0), 11, 1.2)?,
                )?,
            )?,
        )?,
        legend: LegendTheme::builtin()?,
        axes: AxisTheme::new(
            Some(FrameTheme::new(
                FrameSides::new(true, true, true, true)?,
                stroke(axis_width, LinePattern::Solid)?,
            )?),
            Some(FrameTheme::new(
                FrameSides::new(false, false, true, true)?,
                stroke(axis_width, LinePattern::Solid)?,
            )?),
            Some(TickTheme::new(stroke(axis_width, LinePattern::Solid)?, 5)?),
            Some(StrokeTheme::new(
                color_from_rgb(grid_color),
                0.5,
                LinePattern::MediumDash,
            )?),
            AxisSpacing::new(
                super::RelativeSpacing::ratio(8, 16)?,
                super::RelativeSpacing::ratio(6, 16)?,
                super::RelativeSpacing::ratio(8, axis_title_font_size)?,
                super::RelativeSpacing::ratio(16, axis_title_font_size)?,
                super::RelativeSpacing::ratio(16, axis_title_font_size)?,
                super::RelativeSpacing::ratio(12, axis_title_font_size)?,
            )?,
        )?,
        marks: MarkTheme::builtin(accents, opaque(&foreground), axis_width)?,
        annotations: AnnotationTheme::builtin(foreground_paint, bracket_width)?,
        composition: super::CompositionTheme::builtin(
            title_font_size,
            subtitle_font_size,
            caption_font_size,
            axis_title_font_size,
        )?,
    };
    Theme::new(
        value.surfaces,
        value.typography,
        value.axes,
        value.legend,
        value.composition,
        value.marks,
        value.annotations,
        value.color_scales,
    )
}

fn plus_six_line_height(font_size: u32) -> f64 {
    (f64::from(font_size) + 6.0) / f64::from(font_size)
}

pub(super) fn publication_theme() -> Result<Theme, Error> {
    // Okabe-Ito 8-color qualitative palette (colorblind-safe).
    resolved_theme(
        &[
            (0, 114, 178),
            (213, 94, 0),
            (0, 158, 115),
            (204, 121, 167),
            (86, 180, 233),
            (230, 159, 0),
            (240, 228, 66),
            (0, 0, 0),
        ],
        (0, 0, 0),
        0.8,
        1.0,
        20,
        15,
        15,
        17,
        (220, 220, 220),
    )
}

pub(super) fn nature_theme() -> Result<Theme, Error> {
    resolved_theme(
        &[
            (40, 86, 130),
            (130, 160, 188),
            (200, 215, 230),
            (120, 130, 90),
            (180, 175, 130),
        ],
        (40, 40, 40),
        0.8,
        0.8,
        19,
        14,
        14,
        16,
        (230, 230, 230),
    )
}

pub(super) fn science_theme() -> Result<Theme, Error> {
    resolved_theme(
        &[
            (255, 0, 0),
            (0, 0, 255),
            (0, 175, 0),
            (255, 175, 0),
            (160, 32, 240),
        ],
        (0, 0, 0),
        1.0,
        1.0,
        21,
        16,
        15,
        17,
        (200, 200, 200),
    )
}

pub(super) fn chi_theme() -> Result<Theme, Error> {
    resolved_theme(
        &[
            (171, 199, 232),
            (243, 169, 175),
            (174, 224, 174),
            (244, 213, 152),
            (197, 176, 213),
        ],
        (60, 60, 60),
        0.8,
        0.8,
        19,
        15,
        15,
        17,
        (220, 220, 220),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    fn indexed_query_input<'a>(
        source: &'a str,
        appearance: &'a TextTheme,
        owner: &str,
    ) -> TextPlanInput<'a> {
        TextPlanInput {
            size_trace: None,
            direction: crate::text::TextDirection::Auto,
            source,
            stack: &appearance.stack,
            weight: appearance.weight,
            font_size: appearance.font_size,
            line_height: TextLineHeight::Multiplier(appearance.line_height_multiplier),
            maximum_width_quanta: 100 * 1024,
            alignment: PhysicalTextAlignment::Start,
            paint: appearance.paint,
            provenance: TextPlanProvenance {
                pair_ordinal: pair_ordinal(appearance.weight),
                owner: owner.into(),
            },
            exact_override: false,
        }
    }

    #[test]
    #[expect(
        clippy::too_many_lines,
        reason = "one root verifies indexed lookup, stable collision order, and complete matching"
    )]
    fn indexed_text_queries_preserve_matching_and_collision_order() {
        let root = Theme::publication().resolve().unwrap();
        let text = TextService::default();
        let root = crate::text::TextRequestContext::new(&root, &text);
        root.text
            .fonts
            .set(PreparedFontEnvironment::synthetic())
            .unwrap();
        let environment = root.text.prepared_font_environment().unwrap();
        let resources = environment.operation().unwrap();
        environment.validate_operation(&resources).unwrap();
        let mut appearance = root.typography.root.caption.clone();
        appearance.stack = crate::font::canonical::named_stack(&["Test Sans"]);
        appearance.font_size = 10.0;
        let mut first = None;
        for index in 0..128 {
            let plan = root
                .plan_text(
                    "A",
                    &appearance,
                    100.0,
                    PhysicalTextAlignment::Start,
                    &format!("owner {index:03}"),
                    false,
                )
                .unwrap();
            if index == 0 {
                first = Some(plan);
            }
        }
        {
            let cache = root.text.queries.lock().unwrap();
            assert_eq!(cache.entries.len(), 128);
            assert_eq!(cache.exact.len(), 128);
            assert_eq!(
                cache.shaping.len(),
                1,
                "one analysis representative per compatible font/source profile"
            );
            assert!(cache.exact.windows(2).all(|pair| pair[0] < pair[1]));
        }

        let hit = root
            .plan_text(
                "A",
                &appearance,
                100.0,
                PhysicalTextAlignment::Start,
                "owner 000",
                false,
            )
            .unwrap();
        assert!(first.unwrap().shares_payload(&hit));

        root.plan_text(
            "AA",
            &appearance,
            100.0,
            PhysicalTextAlignment::Start,
            "collision",
            false,
        )
        .unwrap();
        let collision = indexed_query_input("AA", &appearance, "collision");
        let mut cache = root.text.queries.lock().unwrap();
        let expected = cache.entries.len() - 1;
        let TextQueryCache { exact, shaping, .. } = &mut *cache;
        for index in [exact, shaping] {
            for entry in index.iter_mut() {
                entry.fingerprint = [0; 32];
            }
            index.sort_unstable();
        }

        assert_eq!(
            cache.find_query(
                &cache.exact,
                [0; 32],
                (&collision, None),
                true,
                Some(expected)
            ),
            Some(expected)
        );

        assert_eq!(
            cache.find_query(
                &cache.shaping,
                [0; 32],
                (&collision, None),
                false,
                Some(expected)
            ),
            Some(expected)
        );

        let mut wrong_provenance = collision.clone();
        wrong_provenance.provenance.pair_ordinal += 1;
        assert!(cache
            .find_query(
                &cache.exact,
                [0; 32],
                (&wrong_provenance, None),
                true,
                Some(expected)
            )
            .is_none());
        assert_eq!(
            cache.find_query(
                &cache.shaping,
                [0; 32],
                (&wrong_provenance, None),
                false,
                Some(expected)
            ),
            Some(expected)
        );
    }

    #[test]
    fn retained_profile_does_not_trust_a_reused_mutable_input_address() {
        let theme = Theme::publication().resolve().unwrap();
        let text = TextService::default();
        let theme = crate::text::TextRequestContext::new(&theme, &text);
        theme
            .text
            .fonts
            .set(PreparedFontEnvironment::synthetic_faces(&[(
                "Literal",
                &['A', 'X'],
            )]))
            .unwrap();
        let appearance = TextTheme {
            stack: crate::font::canonical::named_stack(&["Literal"]),
            font_size: 10.0,
            ..theme.typography.root.caption.clone()
        };
        let mut source = String::with_capacity(16);
        source.push('A');
        let address = source.as_ptr();
        let first = theme
            .plan_text(
                &source,
                &appearance,
                100.0,
                PhysicalTextAlignment::Start,
                "mutable input",
                false,
            )
            .unwrap();
        source.replace_range(.., "X");
        assert_eq!(source.as_ptr(), address);
        let second = theme
            .plan_text(
                &source,
                &appearance,
                100.0,
                PhysicalTextAlignment::Start,
                "mutable input",
                false,
            )
            .unwrap();
        assert!(!first.shares_payload(&second));
        assert_eq!(second.source, "X");
        assert_eq!(theme.text.queries.lock().unwrap().profiles.len(), 2);
    }

    #[test]
    fn later_font_admissions_preserve_cached_shapes_and_complete_request_payloads() {
        let theme = Theme::publication().resolve().unwrap();
        let text = TextService::default();
        let theme = crate::text::TextRequestContext::new(&theme, &text);
        theme
            .text
            .fonts
            .set(PreparedFontEnvironment::synthetic_faces(&[
                ("Base", &['A']),
                ("Complete", &['A', '\u{301}']),
            ]))
            .unwrap();
        let appearance = TextTheme {
            stack: crate::font::canonical::named_stack(&["Base", "Complete"]),
            ..theme.typography.root.caption.clone()
        };
        let measure = |source| {
            theme
                .measure_text(
                    source,
                    &appearance,
                    PhysicalTextAlignment::Start,
                    "actual source",
                    true,
                )
                .unwrap()
        };
        let first = measure("A");
        let marked = measure("A\u{301}");
        assert_ne!(first.lines[0].runs[0].face, marked.lines[0].runs[0].face);
        let counts = crate::font::canonical::planning_counts();
        assert!(first.shares_payload(&measure("A")));
        assert!(marked.shares_payload(&measure("A\u{301}")));
        assert_eq!(crate::font::canonical::planning_counts(), counts);
        theme
            .text
            .prepared_font_environment()
            .unwrap()
            .operation()
            .unwrap()
            .seal_fonts()
            .unwrap();
        let counts = crate::font::canonical::planning_counts();
        assert!(first.shares_payload(&measure("A")));
        assert!(marked.shares_payload(&measure("A\u{301}")));
        assert_eq!(crate::font::canonical::planning_counts(), counts);
        assert_eq!(theme.text.queries.lock().unwrap().entries.len(), 2);
    }

    #[test]
    fn text_cache_stops_optional_insertion_without_refusing_rendering() {
        let root = Theme::publication().resolve().unwrap();
        let text = TextService::default();
        let root = crate::text::TextRequestContext::new(&root, &text);
        root.text
            .fonts
            .set(PreparedFontEnvironment::synthetic())
            .unwrap();
        let mut appearance = root.typography.root.caption.clone();
        appearance.stack = crate::font::canonical::named_stack(&["Test Sans"]);
        let render = |owner: &str| {
            root.measure_text("A", &appearance, PhysicalTextAlignment::Start, owner, false)
                .unwrap()
        };
        let first = render("first");
        for index in 1..256 {
            render(&format!("owner {index}"));
        }
        assert_eq!(root.text.queries.lock().unwrap().entries.len(), 256);
        assert_eq!(render("uncached owner").source, "A");
        assert_eq!(root.text.queries.lock().unwrap().entries.len(), 256);
        assert!(first.shares_payload(&render("first")));
    }
}