inset-embedder 0.19.0

dart:ui host traits and value types for Inset
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
//! Flutter counterpart: `engine/src/flutter/lib/ui/text.dart`, the paragraph half:
//! `TextStyle`, `ParagraphStyle`, `ParagraphBuilder`, `Paragraph`, and the position, range,
//! box, and line-metric value types.
//!
//! Flutter's engine implements these on top of Skia's paragraph library; here they wrap valo's.
//! Offsets are UTF-16 code units, as in Dart; valo works in UTF-8 bytes and the wrapper
//! translates.

use std::fmt;
use std::ops::Range;

use crate::fonts::FontCollection;
use crate::text::{
    FontFeature, FontStyle, FontVariation, FontWeight, TextAlign, TextBaseline, TextDecoration,
    TextDecorationStyle, TextDirection, TextHeightBehavior, TextLeadingDistribution,
};
use crate::{Canvas, Color, Offset, Paint, Rect, Shadow};

/// A position in a string of text.
///
/// A `TextPosition` can be used to describe a caret position in between characters. The
/// [`offset`](Self::offset) points to the position between `offset - 1` and `offset`
/// characters of the string, and the [`affinity`](Self::affinity) is used to describe which
/// character this position affiliates with.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TextPosition {
    /// The index of the character that immediately follows the position in the string
    /// representation of the text.
    pub offset: i32,
    /// Disambiguates cases where the offset could be at the end of one line or the
    /// start of the next.
    pub affinity: TextAffinity,
}

impl TextPosition {
    /// Creates an object representing a particular position in a string, with downstream
    /// affinity.
    pub const fn new(offset: i32) -> TextPosition {
        TextPosition {
            offset,
            affinity: TextAffinity::Downstream,
        }
    }

    /// Creates an object representing a particular position in a string.
    pub const fn with_affinity(offset: i32, affinity: TextAffinity) -> TextPosition {
        TextPosition { offset, affinity }
    }
}

/// A way to disambiguate a [`TextPosition`] when its offset could match two
/// different locations in the rendered string.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextAffinity {
    /// The position has affinity for the upstream side of the text position, i.e. in the
    /// direction of the beginning of the string.
    Upstream,
    /// The position has affinity for the downstream side of the text position, i.e. in the
    /// direction of the end of the string.
    #[default]
    Downstream,
}

/// A range of characters in a string of text.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TextRange {
    /// The index of the first character in the range.
    ///
    /// If [`start`](Self::start) and [`end`](Self::end) are both -1, the text range is empty.
    pub start: i32,
    /// The next index after the characters in this range.
    pub end: i32,
}

impl TextRange {
    /// A text range that starts and ends at offset -1: the empty range.
    pub const EMPTY: TextRange = TextRange { start: -1, end: -1 };

    /// Creates a new [`TextRange`]. The `start` and `end` must be at least -1.
    pub const fn new(start: i32, end: i32) -> TextRange {
        debug_assert!(start >= -1);
        debug_assert!(end >= -1);
        TextRange { start, end }
    }

    /// A text range that starts and ends at `offset`.
    pub const fn collapsed(offset: i32) -> TextRange {
        debug_assert!(offset >= -1);
        TextRange {
            start: offset,
            end: offset,
        }
    }

    /// Whether this range represents a valid position in the text.
    pub fn is_valid(&self) -> bool {
        self.start >= 0 && self.end >= 0
    }

    /// Whether this range is empty (but still potentially placed inside the text).
    pub fn is_collapsed(&self) -> bool {
        self.start == self.end
    }

    /// Whether the start of this range precedes the end.
    pub fn is_normalized(&self) -> bool {
        self.end >= self.start
    }

    /// The text before this range.
    pub fn text_before<'a>(&self, text: &'a str) -> &'a str {
        debug_assert!(self.is_normalized());
        let start = byte_of_code_unit(text, self.start as usize);
        &text[..start]
    }

    /// The text after this range.
    pub fn text_after<'a>(&self, text: &'a str) -> &'a str {
        debug_assert!(self.is_normalized());
        let end = byte_of_code_unit(text, self.end as usize);
        &text[end..]
    }

    /// The text inside this range.
    pub fn text_inside<'a>(&self, text: &'a str) -> &'a str {
        debug_assert!(self.is_normalized());
        let start = byte_of_code_unit(text, self.start as usize);
        let end = byte_of_code_unit(text, self.end as usize);
        &text[start..end]
    }
}

/// Layout constraints for [`Paragraph`] objects.
///
/// Instances of this class are typically used with [`Paragraph::layout`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ParagraphConstraints {
    /// The width the paragraph should use whey computing the positions of glyphs.
    ///
    /// If possible, the paragraph will select a soft line break prior to reaching this width.
    /// If no soft line break is available, the paragraph will select a hard line break prior
    /// to reaching this width. If that would force a line break without any glyphs, the
    /// paragraph will place the first glyph on the line anyway.
    pub width: f64,
}

impl ParagraphConstraints {
    /// Creates constraints for laying out a paragraph.
    pub const fn new(width: f64) -> ParagraphConstraints {
        ParagraphConstraints { width }
    }
}

/// A rectangle enclosing a run of text.
///
/// This is similar to [`Rect`] but includes an inherent [`TextDirection`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextBox {
    /// The left edge of the text box, relative to the parent widget.
    pub left: f64,
    /// The top edge of the text box, relative to the parent widget.
    pub top: f64,
    /// The right edge of the text box, relative to the parent widget.
    pub right: f64,
    /// The bottom edge of the text box, relative to the parent widget.
    pub bottom: f64,
    /// The direction in which text inside this box flows.
    pub direction: TextDirection,
}

impl TextBox {
    /// Creates an object that describes a box containing text.
    pub const fn from_ltrbd(
        left: f64,
        top: f64,
        right: f64,
        bottom: f64,
        direction: TextDirection,
    ) -> TextBox {
        TextBox {
            left,
            top,
            right,
            bottom,
            direction,
        }
    }

    /// Returns a rect of the same size as this box.
    pub fn to_rect(&self) -> Rect {
        Rect::from_ltrb(self.left, self.top, self.right, self.bottom)
    }

    /// The [`left`](Self::left) edge of the box for left-to-right text; the
    /// [`right`](Self::right) edge of the box for right-to-left text.
    pub fn start(&self) -> f64 {
        match self.direction {
            TextDirection::Ltr => self.left,
            TextDirection::Rtl => self.right,
        }
    }

    /// The [`right`](Self::right) edge of the box for left-to-right text; the
    /// [`left`](Self::left) edge of the box for right-to-left text.
    pub fn end(&self) -> f64 {
        match self.direction {
            TextDirection::Ltr => self.right,
            TextDirection::Rtl => self.left,
        }
    }
}

/// Where to vertically align the placeholder relative to the surrounding text.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PlaceholderAlignment {
    Baseline,
    AboveBaseline,
    BelowBaseline,
    Top,
    Bottom,
    Middle,
}

/// Defines various ways to vertically bound the boxes returned by
/// [`Paragraph::get_boxes_for_range`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum BoxHeightStyle {
    #[default]
    Tight,
    Max,
    IncludeLineSpacingMiddle,
    IncludeLineSpacingTop,
    IncludeLineSpacingBottom,
    Strut,
}

/// Defines various ways to horizontally bound the boxes returned by
/// [`Paragraph::get_boxes_for_range`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum BoxWidthStyle {
    #[default]
    Tight,
    Max,
}

/// The measurements of a character (or a sequence of visually connected characters) within
/// a paragraph.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlyphInfo {
    /// The layout bounding rect of the associated character, in the paragraph's coordinates.
    pub grapheme_cluster_layout_bounds: Rect,
    /// The UTF-16 range of the associated character in the text.
    pub grapheme_cluster_code_unit_range: TextRange,
    /// The writing direction within the glyph.
    pub writing_direction: TextDirection,
}

/// [`LineMetrics`] stores the measurements and statistics of a single line in the paragraph.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LineMetrics {
    /// True if this line ends with an explicit line break (e.g. `\n`) or is the end of the
    /// paragraph. False otherwise.
    pub hard_break: bool,
    /// The rise from the [`baseline`](Self::baseline) as calculated from the font and style
    /// for this line.
    pub ascent: f64,
    /// The drop from the [`baseline`](Self::baseline) as calculated from the font and style
    /// for this line.
    pub descent: f64,
    /// The rise from the [`baseline`](Self::baseline) as calculated from the font and style
    /// for this line ignoring the `TextStyle.height`.
    pub unscaled_ascent: f64,
    /// Total height of the line from the top edge to the bottom edge.
    pub height: f64,
    /// Width of the line from the left edge of the leftmost glyph to the right edge of the
    /// rightmost glyph.
    pub width: f64,
    /// The x coordinate of left edge of the line.
    pub left: f64,
    /// The y coordinate of the baseline for this line from the top of the paragraph.
    pub baseline: f64,
    /// The number of this line in the overall paragraph, with the first line being index zero.
    pub line_number: i32,
}

/// An opaque object that determines the size, position, and rendering of text.
///
/// Every field is optional, as in Dart: a field left `None` inherits from the style below it
/// on the [`ParagraphBuilder`]'s stack, or from the paragraph style.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TextStyle {
    pub color: Option<Color>,
    pub decoration: Option<TextDecoration>,
    pub decoration_color: Option<Color>,
    pub decoration_style: Option<TextDecorationStyle>,
    pub decoration_thickness: Option<f64>,
    pub font_weight: Option<FontWeight>,
    pub font_style: Option<FontStyle>,
    pub text_baseline: Option<TextBaseline>,
    pub font_family: Option<String>,
    pub font_family_fallback: Option<Vec<String>>,
    pub font_size: Option<f64>,
    pub letter_spacing: Option<f64>,
    pub word_spacing: Option<f64>,
    pub height: Option<f64>,
    pub leading_distribution: Option<TextLeadingDistribution>,
    pub background: Option<Paint>,
    pub foreground: Option<Paint>,
    pub shadows: Option<Vec<Shadow>>,
    pub font_features: Option<Vec<FontFeature>>,
    pub font_variations: Option<Vec<FontVariation>>,
}

impl TextStyle {
    /// Creates a new text style with every field unset.
    pub fn new() -> TextStyle {
        TextStyle::default()
    }

    /// The style with `other`'s set fields laid over this one, the engine's `pushStyle`
    /// inheritance.
    fn merged_with(&self, other: &TextStyle) -> TextStyle {
        TextStyle {
            color: other.color.or(self.color),
            decoration: other.decoration.or(self.decoration),
            decoration_color: other.decoration_color.or(self.decoration_color),
            decoration_style: other.decoration_style.or(self.decoration_style),
            decoration_thickness: other.decoration_thickness.or(self.decoration_thickness),
            font_weight: other.font_weight.or(self.font_weight),
            font_style: other.font_style.or(self.font_style),
            text_baseline: other.text_baseline.or(self.text_baseline),
            font_family: other
                .font_family
                .clone()
                .or_else(|| self.font_family.clone()),
            font_family_fallback: other
                .font_family_fallback
                .clone()
                .or_else(|| self.font_family_fallback.clone()),
            font_size: other.font_size.or(self.font_size),
            letter_spacing: other.letter_spacing.or(self.letter_spacing),
            word_spacing: other.word_spacing.or(self.word_spacing),
            height: other.height.or(self.height),
            leading_distribution: other.leading_distribution.or(self.leading_distribution),
            background: other.background.clone().or_else(|| self.background.clone()),
            foreground: other.foreground.clone().or_else(|| self.foreground.clone()),
            shadows: other.shadows.clone().or_else(|| self.shadows.clone()),
            font_features: other
                .font_features
                .clone()
                .or_else(|| self.font_features.clone()),
            font_variations: other
                .font_variations
                .clone()
                .or_else(|| self.font_variations.clone()),
        }
    }

    /// The host span style: unset fields take the host's defaults (14px, black).
    fn to_native(&self) -> valo::TextStyle {
        let mut style = valo::TextStyle::default();
        let mut families = Vec::new();
        if let Some(family) = &self.font_family {
            families.push(family.clone());
        }
        if let Some(fallback) = &self.font_family_fallback {
            families.extend(fallback.iter().cloned());
        }
        style.families = families;
        if let Some(weight) = self.font_weight {
            style.weight = weight.value as u16;
        }
        style.italic = self.font_style == Some(FontStyle::Italic);
        if let Some(size) = self.font_size {
            style.size = size as f32;
        }
        if let Some(foreground) = &self.foreground {
            style.color = foreground.color;
        } else if let Some(color) = self.color {
            style.color = color.into();
        }
        style.foreground = self.foreground.clone();
        style.background = self.background.clone();
        if let Some(letter_spacing) = self.letter_spacing {
            style.letter_spacing = letter_spacing as f32;
        }
        if let Some(word_spacing) = self.word_spacing {
            style.word_spacing = word_spacing as f32;
        }
        style.height = match self.height {
            Some(height) if height != crate::text::K_TEXT_HEIGHT_NONE => Some(height as f32),
            _ => None,
        };
        style.decoration = native_decoration(
            self.decoration,
            self.decoration_color,
            self.decoration_thickness,
        );
        if let Some(shadows) = &self.shadows {
            style.shadows = shadows
                .iter()
                .map(|shadow| valo::Shadow {
                    color: shadow.color.into(),
                    offset: shadow.offset.into(),
                    blur: shadow.blur_sigma() as f32,
                })
                .collect();
        }
        style
    }
}

/// Underline before overline before line-through: valo draws one decoration per run.
fn native_decoration(
    decoration: Option<TextDecoration>,
    color: Option<Color>,
    thickness: Option<f64>,
) -> Option<valo::Decoration> {
    let decoration = decoration?;
    let kind = if decoration.contains(TextDecoration::UNDERLINE) {
        valo::DecorationKind::Underline
    } else if decoration.contains(TextDecoration::OVERLINE) {
        valo::DecorationKind::Overline
    } else if decoration.contains(TextDecoration::LINE_THROUGH) {
        valo::DecorationKind::LineThrough
    } else {
        return None;
    };
    Some(valo::Decoration {
        kind,
        color: color.map(Into::into),
        thickness: thickness.unwrap_or(1.0) as f32,
    })
}

/// An opaque object that determines the configuration used by [`ParagraphBuilder`] to
/// position lines within a [`Paragraph`] of text.
///
/// The font fields (`font_family`, `font_size`, `height`, `font_weight`, `font_style`) are
/// the style for text that no pushed [`TextStyle`] covers.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ParagraphStyle {
    pub text_align: Option<TextAlign>,
    pub text_direction: Option<TextDirection>,
    pub max_lines: Option<i32>,
    pub font_family: Option<String>,
    pub font_size: Option<f64>,
    pub height: Option<f64>,
    pub text_height_behavior: Option<TextHeightBehavior>,
    pub font_weight: Option<FontWeight>,
    pub font_style: Option<FontStyle>,
    pub ellipsis: Option<String>,
}

impl ParagraphStyle {
    /// Creates a new paragraph style with every field unset.
    pub fn new() -> ParagraphStyle {
        ParagraphStyle::default()
    }

    /// The text style the paragraph style implies for text with no pushed style.
    fn base_text_style(&self) -> TextStyle {
        TextStyle {
            font_family: self.font_family.clone(),
            font_size: self.font_size,
            height: self.height,
            font_weight: self.font_weight,
            font_style: self.font_style,
            ..TextStyle::default()
        }
    }

    fn to_native(&self) -> valo::ParagraphStyle {
        valo::ParagraphStyle {
            align: native_align(self.text_align, self.text_direction),
            direction: self.text_direction.map(native_direction),
            preserve_trailing_whitespace: false,
            max_lines: self.max_lines.map(|max_lines| max_lines as u32),
            ellipsis: self.ellipsis.clone(),
        }
    }
}

/// valo stores a physical alignment: `Start` / `End` resolve against the direction, LTR when
/// none is given.
fn native_align(align: Option<TextAlign>, direction: Option<TextDirection>) -> valo::TextAlign {
    match align {
        None | Some(TextAlign::Left) => valo::TextAlign::Left,
        Some(TextAlign::Right) => valo::TextAlign::Right,
        Some(TextAlign::Center) => valo::TextAlign::Center,
        Some(TextAlign::Justify) => valo::TextAlign::Justify,
        Some(TextAlign::Start) => match direction {
            Some(TextDirection::Rtl) => valo::TextAlign::Right,
            _ => valo::TextAlign::Left,
        },
        Some(TextAlign::End) => match direction {
            Some(TextDirection::Rtl) => valo::TextAlign::Left,
            _ => valo::TextAlign::Right,
        },
    }
}

fn native_placeholder_alignment(alignment: PlaceholderAlignment) -> valo::PlaceholderAlignment {
    match alignment {
        PlaceholderAlignment::Baseline => valo::PlaceholderAlignment::Baseline,
        PlaceholderAlignment::AboveBaseline => valo::PlaceholderAlignment::AboveBaseline,
        PlaceholderAlignment::BelowBaseline => valo::PlaceholderAlignment::BelowBaseline,
        PlaceholderAlignment::Top => valo::PlaceholderAlignment::Top,
        PlaceholderAlignment::Bottom => valo::PlaceholderAlignment::Bottom,
        PlaceholderAlignment::Middle => valo::PlaceholderAlignment::Middle,
    }
}

fn native_baseline(baseline: TextBaseline) -> valo::TextBaseline {
    match baseline {
        TextBaseline::Alphabetic => valo::TextBaseline::Alphabetic,
        TextBaseline::Ideographic => valo::TextBaseline::Ideographic,
    }
}

fn native_direction(direction: TextDirection) -> valo::TextDirection {
    match direction {
        TextDirection::Ltr => valo::TextDirection::Ltr,
        TextDirection::Rtl => valo::TextDirection::Rtl,
    }
}

/// Builds a [`Paragraph`] containing text with the given styling information.
///
/// To set the paragraph's alignment, truncation, and ellipsizing behavior, pass an
/// appropriately-configured [`ParagraphStyle`] object to [`ParagraphBuilder::new`].
///
/// Then, call combinations of [`push_style`](Self::push_style), [`add_text`](Self::add_text),
/// and [`pop`](Self::pop) to add styled text to the object.
///
/// Finally, call [`build`](Self::build) to obtain the constructed [`Paragraph`] object. After
/// this point, the builder is no longer usable.
///
/// After constructing a [`Paragraph`], call [`Paragraph::layout`] on it and then paint it
/// with [`CanvasText::draw_paragraph`].
pub struct ParagraphBuilder {
    paragraph_style: ParagraphStyle,
    style_stack: Vec<TextStyle>,
    pieces: Vec<Piece>,
    placeholder_scales: Vec<f64>,
}

/// One addition to a [`ParagraphBuilder`], kept until [`ParagraphBuilder::build`] has the fonts
/// to shape it.
enum Piece {
    Text(String, valo::TextStyle),
    Placeholder(valo::PlaceholderStyle, valo::TextStyle),
}

impl ParagraphBuilder {
    /// Creates a new [`ParagraphBuilder`] object, which is used to create a [`Paragraph`].
    pub fn new(style: ParagraphStyle) -> ParagraphBuilder {
        let base = style.base_text_style();
        ParagraphBuilder {
            paragraph_style: style,
            style_stack: vec![base],
            pieces: Vec::new(),
            placeholder_scales: Vec::new(),
        }
    }

    /// The number of placeholders currently in the paragraph.
    pub fn placeholder_count(&self) -> i32 {
        self.placeholder_scales.len() as i32
    }

    /// The scales of the placeholders in the paragraph.
    pub fn placeholder_scales(&self) -> &[f64] {
        &self.placeholder_scales
    }

    /// Applies the given style to the added text until [`pop`](Self::pop) is called.
    ///
    /// Fields the style leaves unset inherit from the style below it.
    pub fn push_style(&mut self, style: TextStyle) {
        let current = self
            .style_stack
            .last()
            .expect("the base style is never popped");
        let merged = current.merged_with(&style);
        self.style_stack.push(merged);
    }

    /// Ends the effect of the most recent call to [`push_style`](Self::push_style).
    ///
    /// Internally, the paragraph builder maintains a stack of text styles. Text added to the
    /// paragraph is affected by all the styles in the stack. Calling [`pop`](Self::pop)
    /// removes the topmost style in the stack, leaving the remaining styles in effect.
    pub fn pop(&mut self) {
        if self.style_stack.len() > 1 {
            self.style_stack.pop();
        }
    }

    /// Adds the given text to the paragraph.
    ///
    /// The text will be styled according to the current stack of text styles.
    pub fn add_text(&mut self, text: &str) {
        let style = self.current_style();
        self.pieces.push(Piece::Text(text.to_owned(), style));
    }

    /// Adds an inline placeholder space to the paragraph.
    ///
    /// The paragraph will contain a rectangular space with no text of the dimensions
    /// specified.
    ///
    /// The `width` and `height` parameters specify the size of the placeholder rectangle.
    ///
    /// The `alignment` parameter specifies how the placeholder rectangle will be vertically
    /// aligned with the surrounding text. When [`PlaceholderAlignment::Baseline`],
    /// [`PlaceholderAlignment::AboveBaseline`], and [`PlaceholderAlignment::BelowBaseline`]
    /// alignment modes are used, the baseline needs to be set with the `baseline`.
    /// When using [`PlaceholderAlignment::Baseline`], `baseline_offset` indicates the distance
    /// of the baseline down from the top of the rectangle. The default `baseline_offset`
    /// is the `height`.
    ///
    /// Examples:
    ///
    /// * For a 30x50 placeholder with the bottom edge aligned with the bottom of the text, use:
    ///   `add_placeholder(30.0, 50.0, PlaceholderAlignment::Bottom, 1.0, None, None)`
    /// * For a 30x50 placeholder that is vertically centered around the text, use:
    ///   `add_placeholder(30.0, 50.0, PlaceholderAlignment::Middle, 1.0, None, None)`.
    /// * For a 30x50 placeholder that sits completely on top of the alphabetic baseline, use:
    ///   `add_placeholder(30.0, 50.0, PlaceholderAlignment::AboveBaseline, 1.0, None,
    ///   Some(TextBaseline::Alphabetic))`
    /// * For a 30x50 placeholder with 40 pixels above and 10 pixels below the alphabetic
    ///   baseline, use: `add_placeholder(30.0, 50.0, PlaceholderAlignment::Baseline, 1.0,
    ///   Some(40.0), Some(TextBaseline::Alphabetic))`
    ///
    /// Lines are permitted to break around each placeholder.
    ///
    /// Decorations will be drawn based on the font defined in the most recently
    /// pushed [`TextStyle`]. The decorations are drawn as if unicode text were present
    /// in the placeholder space, and will draw the same regardless of the height and
    /// alignment of the placeholder. To hide or manually adjust decorations to fit,
    /// a text style with the desired decoration behavior should be pushed before
    /// adding a placeholder.
    ///
    /// Any decorations drawn through a placeholder will exist on the same canvas/layer
    /// as the text. This means any content drawn on top of the space reserved by
    /// the placeholder will be drawn over the decoration, possibly obscuring the
    /// decoration.
    ///
    /// Placeholders are represented by a unicode 0xFFFC "object replacement character"
    /// in the text buffer. For each placeholder, one object replacement character is
    /// added on to the text buffer.
    ///
    /// The `scale` parameter will scale the `width` and `height` by the specified amount,
    /// and keep track of the scale. The scales of placeholders added can be accessed
    /// through [`placeholder_scales`](Self::placeholder_scales). This is primarily used for
    /// accessibility scaling.
    pub fn add_placeholder(
        &mut self,
        width: f64,
        height: f64,
        alignment: PlaceholderAlignment,
        scale: f64,
        baseline_offset: Option<f64>,
        baseline: Option<TextBaseline>,
    ) {
        // Require a baseline to be specified if using a baseline-based alignment.
        debug_assert!(
            !matches!(
                alignment,
                PlaceholderAlignment::AboveBaseline
                    | PlaceholderAlignment::BelowBaseline
                    | PlaceholderAlignment::Baseline
            ) || baseline.is_some()
        );
        // Default the baselineOffset to height if null. This will place the placeholder
        // fully above the baseline, similar to [PlaceholderAlignment.aboveBaseline].
        let baseline_offset = baseline_offset.unwrap_or(height);
        let placeholder = valo::PlaceholderStyle {
            width: (width * scale) as f32,
            height: (height * scale) as f32,
            alignment: native_placeholder_alignment(alignment),
            baseline: native_baseline(baseline.unwrap_or(TextBaseline::Alphabetic)),
            baseline_offset: (baseline_offset * scale) as f32,
        };
        let style = self.current_style();
        self.pieces.push(Piece::Placeholder(placeholder, style));
        self.placeholder_scales.push(scale);
    }

    /// The style on top of the stack, in valo's terms.
    fn current_style(&self) -> valo::TextStyle {
        self.style_stack
            .last()
            .expect("the base style is never popped")
            .to_native()
    }

    /// Applies the given paragraph style and returns a [`Paragraph`] containing the added
    /// text and associated styling, shaped against `fonts`.
    ///
    /// After calling this function, the paragraph builder object is invalid and cannot be
    /// used further.
    pub fn build(self, fonts: &mut FontCollection) -> Paragraph {
        let direction = self
            .paragraph_style
            .text_direction
            .unwrap_or(TextDirection::Ltr);
        let mut builder = valo::ParagraphBuilder::new(fonts);
        builder.style(self.paragraph_style.to_native());
        for piece in &self.pieces {
            match piece {
                Piece::Text(text, style) => builder.add_text(text, style),
                Piece::Placeholder(placeholder, style) => {
                    builder.add_placeholder(*placeholder, style)
                }
            };
        }
        let inner = builder.build();
        Paragraph {
            code_units: CodeUnits::of(inner.text()),
            inner,
            direction,
            layout_width: 0.0,
            disposed: false,
        }
    }
}

/// The map between Dart's UTF-16 code unit offsets and valo's UTF-8 byte offsets.
#[derive(Clone, Debug)]
struct CodeUnits {
    /// `byte_of[code_unit]` for every code unit boundary, plus the end.
    byte_of: Vec<usize>,
    /// The number of UTF-16 code units.
    len: usize,
}

impl CodeUnits {
    fn of(text: &str) -> CodeUnits {
        let mut byte_of = Vec::with_capacity(text.len() + 1);
        for (byte, ch) in text.char_indices() {
            byte_of.push(byte);
            if ch.len_utf16() == 2 {
                // A surrogate pair: the second code unit sits inside the character.
                byte_of.push(byte);
            }
        }
        byte_of.push(text.len());
        let len = byte_of.len() - 1;
        CodeUnits { byte_of, len }
    }

    fn byte(&self, code_unit: i32) -> usize {
        let clamped = code_unit.clamp(0, self.len as i32) as usize;
        self.byte_of[clamped]
    }

    /// The first code unit at or before `byte` (a surrogate pair's two units share a byte).
    fn code_unit(&self, byte: usize) -> i32 {
        let first_at_or_after = self.byte_of.partition_point(|candidate| *candidate < byte);
        match self.byte_of.get(first_at_or_after) {
            Some(candidate) if *candidate == byte => first_at_or_after as i32,
            _ => first_at_or_after.saturating_sub(1) as i32,
        }
    }
}

/// The byte offset of the given UTF-16 code unit in `text`.
fn byte_of_code_unit(text: &str, code_unit: usize) -> usize {
    CodeUnits::of(text).byte(code_unit as i32)
}

/// A paragraph of text.
///
/// A paragraph retains the size and position of each glyph in the text and can be
/// efficiently resized and painted.
///
/// To create a [`Paragraph`] object, use a [`ParagraphBuilder`].
///
/// Paragraphs can be displayed on a [`Canvas`] using [`CanvasText::draw_paragraph`].
pub struct Paragraph {
    inner: valo::Paragraph,
    code_units: CodeUnits,
    direction: TextDirection,
    /// The width given to the last [`layout`](Self::layout); Skia's `getMaxWidth`.
    layout_width: f64,
    disposed: bool,
}

impl Paragraph {
    /// The amount of horizontal space this paragraph occupies.
    ///
    /// Valid only after [`layout`](Self::layout) has been called. As in Skia, this is the
    /// width the paragraph was laid out at (possibly infinite), not the widest line: the
    /// lines are aligned within it.
    pub fn width(&self) -> f64 {
        self.layout_width
    }

    /// The amount of vertical space this paragraph occupies.
    ///
    /// Valid only after [`layout`](Self::layout) has been called.
    pub fn height(&self) -> f64 {
        f64::from(self.inner.height())
    }

    /// The distance from the left edge of the leftmost glyph to the right edge of the
    /// rightmost glyph in the paragraph.
    pub fn longest_line(&self) -> f64 {
        f64::from(self.inner.longest_line())
    }

    /// The minimum width that this paragraph could be without failing to paint its
    /// contents within itself.
    pub fn min_intrinsic_width(&self) -> f64 {
        f64::from(self.inner.min_intrinsic_width())
    }

    /// Returns the smallest width beyond which increasing the width never decreases the
    /// height.
    pub fn max_intrinsic_width(&self) -> f64 {
        f64::from(self.inner.max_intrinsic_width())
    }

    /// The distance from the top of the paragraph to the alphabetic baseline of the first
    /// line, in logical pixels.
    pub fn alphabetic_baseline(&self) -> f64 {
        self.inner
            .lines()
            .first()
            .map_or(0.0, |line| f64::from(line.baseline))
    }

    /// The distance from the top of the paragraph to the ideographic baseline of the first
    /// line, in logical pixels.
    ///
    /// The host has no ideographic metrics; this is the bottom of the first line.
    pub fn ideographic_baseline(&self) -> f64 {
        self.inner
            .lines()
            .first()
            .map_or(0.0, |line| f64::from(line.baseline + line.descent))
    }

    /// True if there is more vertical content, but the text was truncated, either because we
    /// reached `max_lines` lines of text or because the `max_lines` was `None`, `ellipsis`
    /// was not `None`, and one of the lines exceeded the width constraint.
    pub fn did_exceed_max_lines(&self) -> bool {
        self.inner.truncated()
    }

    /// Computes the size and position of each glyph in the paragraph.
    ///
    /// The [`ParagraphConstraints`] control how wide the text is allowed to be.
    pub fn layout(&mut self, constraints: ParagraphConstraints) {
        debug_assert!(!self.disposed);
        self.layout_width = constraints.width;
        self.inner.layout(constraints.width as f32);
    }

    /// Returns a list of text boxes that enclose the given text range.
    ///
    /// The host returns tight boxes only: `box_height_style` and `box_width_style` do not
    /// change the result.
    pub fn get_boxes_for_range(
        &self,
        start: i32,
        end: i32,
        box_height_style: BoxHeightStyle,
        box_width_style: BoxWidthStyle,
    ) -> Vec<TextBox> {
        let _ = (box_height_style, box_width_style);
        let range = self.code_units.byte(start)..self.code_units.byte(end);
        self.inner
            .rects_for_range(range)
            .into_iter()
            .map(|rect| text_box(rect, self.direction))
            .collect()
    }

    /// Returns a list of text boxes that enclose all placeholders in the paragraph.
    ///
    /// The order of the boxes are in the same order as passed in through
    /// [`ParagraphBuilder::add_placeholder`].
    ///
    /// Coordinates of the [`TextBox`] are relative to the upper-left corner of the paragraph,
    /// where positive y values indicate down.
    pub fn get_boxes_for_placeholders(&self) -> Vec<TextBox> {
        self.inner
            .placeholder_boxes()
            .into_iter()
            .map(|placeholder| {
                let direction = match placeholder.direction {
                    valo::TextDirection::Ltr => TextDirection::Ltr,
                    valo::TextDirection::Rtl => TextDirection::Rtl,
                };
                text_box(placeholder.rect, direction)
            })
            .collect()
    }

    /// Returns the text position closest to the given offset.
    pub fn get_position_for_offset(&self, offset: Offset) -> TextPosition {
        let position = self.inner.glyph_position_at(offset.into());
        TextPosition::with_affinity(
            self.code_units.code_unit(position.offset),
            if position.downstream {
                TextAffinity::Downstream
            } else {
                TextAffinity::Upstream
            },
        )
    }

    /// Returns the [`GlyphInfo`] of the glyph closest to the given `offset` in the paragraph
    /// coordinate system, or `None` if if the text is empty, or is entirely clipped or
    /// ellipsized away.
    pub fn get_closest_glyph_info_for_offset(&self, offset: Offset) -> Option<GlyphInfo> {
        let position = self.inner.glyph_position_at(offset.into());
        let anchor = if position.downstream {
            position.offset
        } else {
            position.offset.saturating_sub(1)
        };
        self.glyph_info_at_byte(anchor)
    }

    /// Returns the [`GlyphInfo`] located at the given UTF-16 `code_unit_offset` in the
    /// paragraph, or `None` if the given `code_unit_offset` is out of the visible lines' range.
    pub fn get_glyph_info_at(&self, code_unit_offset: i32) -> Option<GlyphInfo> {
        if code_unit_offset < 0 || code_unit_offset as usize >= self.code_units.len {
            return None;
        }
        self.glyph_info_at_byte(self.code_units.byte(code_unit_offset))
    }

    /// The glyph whose cluster contains `byte`: its layout box spans the glyph's advance
    /// horizontally and the line vertically.
    fn glyph_info_at_byte(&self, byte: usize) -> Option<GlyphInfo> {
        for line in self.inner.lines() {
            if !line.range.contains(&byte) {
                continue;
            }
            let top = line.baseline - line.ascent;
            let bottom = line.baseline + line.descent;
            let cluster_starts = cluster_starts(line);
            for run in &line.runs {
                for glyph in &run.glyphs {
                    let cluster = cluster_range(&cluster_starts, glyph.cluster, line.range.end);
                    if !cluster.contains(&byte) {
                        continue;
                    }
                    let (left, right) = if glyph.advance >= 0.0 {
                        (glyph.x, glyph.x + glyph.advance)
                    } else {
                        (glyph.x + glyph.advance, glyph.x)
                    };
                    return Some(GlyphInfo {
                        grapheme_cluster_layout_bounds: Rect::from_ltrb(
                            f64::from(left),
                            f64::from(top),
                            f64::from(right),
                            f64::from(bottom),
                        ),
                        grapheme_cluster_code_unit_range: TextRange::new(
                            self.code_units.code_unit(cluster.start),
                            self.code_units.code_unit(cluster.end),
                        ),
                        writing_direction: if run.rtl {
                            TextDirection::Rtl
                        } else {
                            TextDirection::Ltr
                        },
                    });
                }
            }
        }
        None
    }

    /// Returns the [`TextRange`] of the word at the given [`TextPosition`].
    pub fn get_word_boundary(&self, position: TextPosition) -> TextRange {
        let range = self
            .inner
            .word_boundary(self.code_units.byte(position.offset));
        self.text_range(range)
    }

    /// Returns the [`TextRange`] of the line at the given [`TextPosition`].
    ///
    /// The newline (if any) is not returned as part of the range.
    pub fn get_line_boundary(&self, position: TextPosition) -> TextRange {
        let byte = self.code_units.byte(position.offset);
        let Some(line) = self.line_containing(byte, position.affinity) else {
            return TextRange::EMPTY;
        };
        let text = self.inner.text();
        let mut end = line.range.end;
        if end > line.range.start && text.as_bytes().get(end - 1) == Some(&b'\n') {
            end -= 1;
        }
        self.text_range(line.range.start..end)
    }

    fn line_containing(&self, byte: usize, affinity: TextAffinity) -> Option<&valo::Line> {
        let lines = self.inner.lines();
        let index = lines.iter().position(|line| {
            let starts_next_line = byte == line.range.start && affinity == TextAffinity::Upstream;
            (line.range.contains(&byte) && !starts_next_line) || byte == line.range.end
        });
        index.and_then(|index| lines.get(index)).or_else(|| {
            let last = lines.last()?;
            (byte >= last.range.end).then_some(last)
        })
    }

    fn text_range(&self, range: Range<usize>) -> TextRange {
        TextRange::new(
            self.code_units.code_unit(range.start),
            self.code_units.code_unit(range.end),
        )
    }

    /// Returns the full list of [`LineMetrics`] that describe in detail the various metrics
    /// of each laid out line.
    pub fn compute_line_metrics(&self) -> Vec<LineMetrics> {
        let lines = self.inner.lines();
        let text = self.inner.text();
        lines
            .iter()
            .enumerate()
            .map(|(index, line)| {
                let is_last = index + 1 == lines.len();
                let ends_with_newline = line.range.end > line.range.start
                    && text.as_bytes().get(line.range.end - 1) == Some(&b'\n');
                LineMetrics {
                    hard_break: is_last || ends_with_newline,
                    ascent: f64::from(line.ascent),
                    descent: f64::from(line.descent),
                    unscaled_ascent: f64::from(line.ascent),
                    height: f64::from(line.ascent + line.descent),
                    width: f64::from(line.width),
                    left: f64::from(line.left),
                    baseline: f64::from(line.baseline),
                    line_number: index as i32,
                }
            })
            .collect()
    }

    /// Returns the [`LineMetrics`] for the line at `line_number`, or `None` if the given
    /// `line_number` is greater than or equal to [`number_of_lines`](Self::number_of_lines).
    pub fn get_line_metrics_at(&self, line_number: i32) -> Option<LineMetrics> {
        if line_number < 0 {
            return None;
        }
        self.compute_line_metrics()
            .into_iter()
            .nth(line_number as usize)
    }

    /// The total number of visible lines in the paragraph.
    ///
    /// Returns a non-negative number. If `max_lines` is set, the value of this getter never
    /// exceeds `max_lines`.
    pub fn number_of_lines(&self) -> i32 {
        self.inner.lines().len() as i32
    }

    /// Returns the line number of the line that contains the code unit that
    /// `code_unit_offset` points to, or `None` if the `code_unit_offset` is out of range.
    pub fn get_line_number_at(&self, code_unit_offset: i32) -> Option<i32> {
        if code_unit_offset < 0 || code_unit_offset as usize >= self.code_units.len {
            return None;
        }
        let byte = self.code_units.byte(code_unit_offset);
        self.inner
            .lines()
            .iter()
            .position(|line| line.range.contains(&byte))
            .map(|index| index as i32)
    }

    /// Release the resources used by this object. The object is no longer usable after this
    /// method is called.
    pub fn dispose(&mut self) {
        debug_assert!(!self.disposed);
        self.disposed = true;
    }

    /// Whether this reference to the underlying paragraph is disposed.
    pub fn debug_disposed(&self) -> bool {
        self.disposed
    }

    /// The host paragraph, for drawing.
    pub(crate) fn native(&self) -> &valo::Paragraph {
        &self.inner
    }
}

fn text_box(rect: valo::Rect, direction: TextDirection) -> TextBox {
    TextBox::from_ltrbd(
        f64::from(rect.x),
        f64::from(rect.y),
        f64::from(rect.x + rect.width),
        f64::from(rect.y + rect.height),
        direction,
    )
}

/// Every cluster start on the line, in text order. A cluster runs from its start to the next
/// start on the line, whichever run that glyph sits in.
fn cluster_starts(line: &valo::Line) -> Vec<usize> {
    let mut starts: Vec<usize> = line
        .runs
        .iter()
        .flat_map(|run| run.glyphs.iter().map(|glyph| glyph.cluster))
        .collect();
    starts.sort_unstable();
    starts.dedup();
    starts
}

fn cluster_range(cluster_starts: &[usize], start: usize, line_end: usize) -> Range<usize> {
    let next = cluster_starts
        .iter()
        .find(|candidate| **candidate > start)
        .copied()
        .unwrap_or(line_end);
    start..next.max(start + 1)
}

impl fmt::Debug for Paragraph {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Paragraph")
            .field("text", &self.inner.text())
            .field("width", &self.width())
            .field("height", &self.height())
            .finish()
    }
}

/// Paragraph drawing on a [`Canvas`] (Dart's `Canvas.drawParagraph`).
pub trait CanvasText {
    /// Draws the text in the given [`Paragraph`] into this canvas at the given [`Offset`].
    ///
    /// The [`Paragraph`] object must have had [`Paragraph::layout`] called on it first.
    fn draw_paragraph(&mut self, paragraph: &Paragraph, offset: Offset);
}

impl CanvasText for Canvas {
    fn draw_paragraph(&mut self, paragraph: &Paragraph, offset: Offset) {
        valo::DrawParagraphExt::draw_paragraph(self, paragraph.native(), offset);
    }
}

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

    #[test]
    fn code_units_map_surrogate_pairs_to_one_character() {
        let units = CodeUnits::of("a😀b");
        assert_eq!(units.len, 4);
        assert_eq!(units.byte(0), 0);
        assert_eq!(units.byte(1), 1);
        assert_eq!(
            units.byte(2),
            1,
            "the second half of the pair maps to the same byte"
        );
        assert_eq!(units.byte(3), 5);
        assert_eq!(units.byte(4), 6);
        assert_eq!(units.code_unit(5), 3);
        assert_eq!(units.code_unit(6), 4);
    }

    /// A span's foreground and background paints reach valo whole, as Flutter's paragraph builder
    /// hands its `TextStyle`'s paints to Skia's; the colour stays the foreground's, for a
    /// decoration with no colour of its own.
    #[test]
    fn a_spans_paints_reach_valo() {
        let outline = Paint {
            color: Color::from_argb(255, 0, 0, 0).into(),
            style: valo::PaintStyle::Stroke(valo::Stroke::new(2.0)),
            ..Paint::default()
        };
        let box_behind = Paint::from_color(Color::from_argb(160, 0, 0, 0).into());
        let style = TextStyle {
            foreground: Some(outline.clone()),
            background: Some(box_behind.clone()),
            ..TextStyle::default()
        };
        let native = style.to_native();
        assert_eq!(native.foreground, Some(outline.clone()));
        assert_eq!(native.background, Some(box_behind));
        assert_eq!(native.color, outline.color);
    }

    #[test]
    fn text_range_slices_by_code_unit() {
        let range = TextRange::new(1, 3);
        assert_eq!(range.text_inside("a😀b"), "😀");
        assert_eq!(range.text_before("a😀b"), "a");
        assert_eq!(range.text_after("a😀b"), "b");
        assert!(TextRange::EMPTY.is_collapsed());
        assert!(!TextRange::EMPTY.is_valid());
    }

    #[test]
    fn text_box_start_and_end_follow_direction() {
        let ltr = TextBox::from_ltrbd(1.0, 2.0, 3.0, 4.0, TextDirection::Ltr);
        let rtl = TextBox::from_ltrbd(1.0, 2.0, 3.0, 4.0, TextDirection::Rtl);
        assert_eq!(ltr.start(), 1.0);
        assert_eq!(ltr.end(), 3.0);
        assert_eq!(rtl.start(), 3.0);
        assert_eq!(rtl.end(), 1.0);
        assert_eq!(ltr.to_rect(), Rect::from_ltrb(1.0, 2.0, 3.0, 4.0));
    }

    fn text_styles(builder: &ParagraphBuilder) -> Vec<&valo::TextStyle> {
        builder
            .pieces
            .iter()
            .filter_map(|piece| match piece {
                Piece::Text(_, style) => Some(style),
                Piece::Placeholder(..) => None,
            })
            .collect()
    }

    #[test]
    fn placeholders_are_counted_with_their_scales() {
        let mut builder = ParagraphBuilder::new(ParagraphStyle::new());
        builder.add_text("a");
        builder.add_placeholder(10.0, 20.0, PlaceholderAlignment::Middle, 2.0, None, None);
        builder.add_placeholder(5.0, 5.0, PlaceholderAlignment::Bottom, 1.0, None, None);
        assert_eq!(builder.placeholder_count(), 2);
        assert_eq!(builder.placeholder_scales(), [2.0, 1.0]);
    }

    #[test]
    fn pushed_styles_inherit_unset_fields() {
        let mut builder = ParagraphBuilder::new(ParagraphStyle {
            font_size: Some(20.0),
            ..ParagraphStyle::default()
        });
        builder.push_style(TextStyle {
            color: Some(Color::from_argb(255, 255, 0, 0)),
            ..TextStyle::default()
        });
        builder.add_text("x");
        builder.pop();
        builder.add_text("y");
        let styles = text_styles(&builder);
        assert_eq!(styles[0].size, 20.0, "the child keeps the paragraph's size");
        assert_eq!(styles[0].color, Color::from_argb(255, 255, 0, 0).into());
        assert_eq!(styles[1].size, 20.0);
        assert_eq!(
            styles[1].color,
            valo::Color::BLACK,
            "popping restores the base"
        );
    }

    #[test]
    fn start_and_end_alignment_resolve_against_direction() {
        assert_eq!(
            native_align(Some(TextAlign::Start), Some(TextDirection::Rtl)),
            valo::TextAlign::Right
        );
        assert_eq!(
            native_align(Some(TextAlign::End), None),
            valo::TextAlign::Right,
            "no direction reads as LTR"
        );
    }

    #[test]
    fn unspecified_font_family_stays_unset_on_the_native_style() {
        let mut builder = ParagraphBuilder::new(ParagraphStyle::new());
        builder.add_text("x");
        assert!(
            text_styles(&builder)[0].families.is_empty(),
            "dart:ui leaves fontFamily unset; the collection's default manager supplies the face"
        );
    }
}

#[cfg(test)]
mod layout_tests {
    //! Shaping needs real fonts: these shape against the OS fonts.

    use super::*;
    use crate::Platform;

    fn fonts() -> FontCollection {
        let mut fonts = FontCollection::new();
        fonts.add_source(valo_system_fonts::SystemFonts::load());
        fonts
    }

    fn paragraph(text: &str, style: ParagraphStyle, width: f64) -> Paragraph {
        let mut builder = ParagraphBuilder::new(style);
        builder.push_style(TextStyle {
            font_size: Some(20.0),
            ..TextStyle::default()
        });
        builder.add_text(text);
        let mut paragraph = builder.build(&mut fonts());
        paragraph.layout(ParagraphConstraints::new(width));
        paragraph
    }

    #[test]
    fn a_laid_out_paragraph_has_a_size_and_one_line() {
        let paragraph = paragraph("Hello", ParagraphStyle::new(), f64::INFINITY);
        assert_eq!(
            paragraph.width(),
            f64::INFINITY,
            "the layout width, as in Skia"
        );
        assert!(paragraph.longest_line() > 0.0);
        assert!(paragraph.height() > 0.0);
        assert_eq!(paragraph.number_of_lines(), 1);
        assert!(paragraph.alphabetic_baseline() > 0.0);
        assert!(paragraph.alphabetic_baseline() < paragraph.height());
        assert!(!paragraph.did_exceed_max_lines());
        assert_eq!(paragraph.max_intrinsic_width(), paragraph.longest_line());
    }

    #[test]
    fn a_narrow_width_wraps_onto_more_lines() {
        let wide = paragraph("one two three four", ParagraphStyle::new(), f64::INFINITY);
        let narrow = paragraph(
            "one two three four",
            ParagraphStyle::new(),
            wide.longest_line() / 2.0,
        );
        assert!(narrow.number_of_lines() > 1);
        assert!(narrow.height() > wide.height());
        let metrics = narrow.compute_line_metrics();
        assert_eq!(metrics.len() as i32, narrow.number_of_lines());
        assert!(
            metrics.last().unwrap().hard_break,
            "the last line is a hard break"
        );
        assert!(!metrics[0].hard_break, "a wrapped line is a soft break");
        assert_eq!(metrics[1].line_number, 1);
    }

    #[test]
    fn max_lines_with_an_ellipsis_truncates() {
        let wide = paragraph("one two three four", ParagraphStyle::new(), f64::INFINITY);
        let style = ParagraphStyle {
            max_lines: Some(1),
            ellipsis: Some("\u{2026}".to_owned()),
            ..ParagraphStyle::default()
        };
        let clipped = paragraph("one two three four", style, wide.longest_line() / 2.0);
        assert_eq!(clipped.number_of_lines(), 1);
        assert!(clipped.did_exceed_max_lines());
    }

    #[test]
    fn positions_boxes_and_boundaries_use_code_units() {
        let paragraph = paragraph("ab cd", ParagraphStyle::new(), f64::INFINITY);
        let start = paragraph.get_position_for_offset(Offset::new(0.0, 1.0));
        assert_eq!(start.offset, 0);
        let end =
            paragraph.get_position_for_offset(Offset::new(paragraph.longest_line() + 50.0, 1.0));
        assert_eq!(end.offset, 5);

        let boxes =
            paragraph.get_boxes_for_range(0, 2, BoxHeightStyle::Tight, BoxWidthStyle::Tight);
        assert_eq!(boxes.len(), 1);
        assert!(boxes[0].right > boxes[0].left);
        assert_eq!(boxes[0].direction, TextDirection::Ltr);

        assert_eq!(
            paragraph.get_word_boundary(TextPosition::new(4)),
            TextRange::new(3, 5)
        );
        assert_eq!(
            paragraph.get_line_boundary(TextPosition::new(1)),
            TextRange::new(0, 5)
        );
        assert_eq!(paragraph.get_line_number_at(4), Some(0));
        assert_eq!(paragraph.get_line_number_at(5), None);

        let glyph = paragraph.get_glyph_info_at(3).expect("the c glyph");
        assert_eq!(glyph.grapheme_cluster_code_unit_range, TextRange::new(3, 4));
        assert!(glyph.grapheme_cluster_layout_bounds.width() > 0.0);
        assert!(paragraph.get_glyph_info_at(5).is_none());
    }

    #[test]
    fn a_surrogate_pair_is_one_glyph_of_two_code_units() {
        let paragraph = paragraph("a😀b", ParagraphStyle::new(), f64::INFINITY);
        let glyph = paragraph.get_glyph_info_at(1).expect("the emoji");
        assert_eq!(glyph.grapheme_cluster_code_unit_range, TextRange::new(1, 3));
        assert_eq!(
            paragraph
                .get_glyph_info_at(3)
                .unwrap()
                .grapheme_cluster_code_unit_range,
            TextRange::new(3, 4)
        );
    }

    /// Either half of a glyph finds that glyph, and a point past the end of the line finds the
    /// last glyph.
    #[test]
    fn the_closest_glyph_is_the_one_under_the_point() {
        let paragraph = paragraph("abc", ParagraphStyle::new(), f64::INFINITY);
        let b = paragraph.get_glyph_info_at(1).expect("the b glyph");
        let bounds = b.grapheme_cluster_layout_bounds;
        let y = bounds.center().dy();
        for x in [bounds.left + 0.5, bounds.right - 0.5] {
            let closest = paragraph
                .get_closest_glyph_info_for_offset(Offset::new(x, y))
                .expect("a glyph");
            assert_eq!(
                closest.grapheme_cluster_code_unit_range,
                TextRange::new(1, 2)
            );
        }
        let past_the_end = paragraph
            .get_closest_glyph_info_for_offset(Offset::new(1000.0, y))
            .expect("a glyph");
        assert_eq!(
            past_the_end.grapheme_cluster_code_unit_range,
            TextRange::new(2, 3)
        );
    }

    #[test]
    fn placeholder_boxes_come_in_the_order_added_at_their_scaled_size() {
        let mut builder = ParagraphBuilder::new(ParagraphStyle::new());
        builder.push_style(TextStyle {
            font_size: Some(20.0),
            ..TextStyle::default()
        });
        builder.add_text("ab");
        builder.add_placeholder(
            30.0,
            50.0,
            PlaceholderAlignment::Baseline,
            1.0,
            Some(40.0),
            Some(TextBaseline::Alphabetic),
        );
        builder.add_text("cd");
        builder.add_placeholder(10.0, 10.0, PlaceholderAlignment::Bottom, 2.0, None, None);
        let mut paragraph = builder.build(&mut fonts());
        paragraph.layout(ParagraphConstraints::new(f64::INFINITY));

        let boxes = paragraph.get_boxes_for_placeholders();
        assert_eq!(boxes.len(), 2);
        let baseline = paragraph.alphabetic_baseline();
        let (first, second) = (boxes[0], boxes[1]);
        assert!((first.right - first.left - 30.0).abs() < 1e-3);
        assert!(
            (first.top - (baseline - 40.0)).abs() < 1e-3,
            "40 above the baseline"
        );
        assert!(
            (first.bottom - (baseline + 10.0)).abs() < 1e-3,
            "10 below it"
        );
        assert!(
            (second.right - second.left - 20.0).abs() < 1e-3,
            "scaled by 2"
        );
        assert!((second.bottom - second.top - 20.0).abs() < 1e-3);
        assert!(second.left > first.right, "after the text between them");
        assert_eq!(
            paragraph.get_line_boundary(TextPosition::new(0)),
            TextRange::new(0, 6),
            "each placeholder is one code unit"
        );
    }

    #[test]
    fn drawing_records_the_paragraph() {
        let paragraph = paragraph("Hi", ParagraphStyle::new(), f64::INFINITY);
        let mut canvas = Canvas::new();
        canvas.draw_paragraph(&paragraph, Offset::new(10.0, 10.0));
        let picture = canvas.build();
        assert!(!picture.ops().is_empty());
    }

    #[test]
    fn unspecified_family_at_black_weight_covers_latin() {
        let mut fonts = FontCollection::new();
        crate::set_default_font_manager(
            &mut fonts,
            Box::new(crate::SystemFontSource::platform()),
            &crate::InertPlatform.default_font_families(),
        );
        let mut builder = ParagraphBuilder::new(ParagraphStyle::new());
        builder.push_style(TextStyle {
            font_size: Some(10.2),
            font_weight: Some(FontWeight::W900),
            ..TextStyle::default()
        });
        builder.add_text("DEBUG");
        let mut paragraph = builder.build(&mut fonts);
        paragraph.layout(ParagraphConstraints::new(f64::INFINITY));
        assert!(paragraph.longest_line() > 0.0);
        assert!(
            fonts.take_unanswered().is_empty(),
            "the engine default family covers Latin at weight 900"
        );
        for line in paragraph.inner.lines() {
            for run in &line.runs {
                assert!(
                    run.glyphs.iter().all(|glyph| glyph.id != 0),
                    "no .notdef tofu"
                );
            }
        }
    }
}