ferri-pdf 0.1.12

HTML and CSS to PDF renderer for print, in pure Rust
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
// Copyright 2019 the Resvg Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT

use std::{collections::HashMap, sync::Arc};

use kurbo::{ParamCurve, ParamCurveArclen};
use svgtypes::{FontFamily, parse_font_families};

use super::svgtree::{AId, EId, FromValue, SvgNode};
use super::{OptionLog, converter, style};
use crate::svg::usvg::*;

impl<'a, 'input: 'a> FromValue<'a, 'input> for TextAnchor {
    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
        match value {
            "start" => Some(TextAnchor::Start),
            "middle" => Some(TextAnchor::Middle),
            "end" => Some(TextAnchor::End),
            _ => None,
        }
    }
}

impl<'a, 'input: 'a> FromValue<'a, 'input> for AlignmentBaseline {
    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
        match value {
            "auto" => Some(AlignmentBaseline::Auto),
            "baseline" => Some(AlignmentBaseline::Baseline),
            "before-edge" => Some(AlignmentBaseline::BeforeEdge),
            "text-before-edge" => Some(AlignmentBaseline::TextBeforeEdge),
            "middle" => Some(AlignmentBaseline::Middle),
            "central" => Some(AlignmentBaseline::Central),
            "after-edge" => Some(AlignmentBaseline::AfterEdge),
            "text-after-edge" => Some(AlignmentBaseline::TextAfterEdge),
            "ideographic" => Some(AlignmentBaseline::Ideographic),
            "alphabetic" => Some(AlignmentBaseline::Alphabetic),
            "hanging" => Some(AlignmentBaseline::Hanging),
            "mathematical" => Some(AlignmentBaseline::Mathematical),
            _ => None,
        }
    }
}

impl<'a, 'input: 'a> FromValue<'a, 'input> for DominantBaseline {
    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
        match value {
            "auto" => Some(DominantBaseline::Auto),
            "use-script" => Some(DominantBaseline::UseScript),
            "no-change" => Some(DominantBaseline::NoChange),
            "reset-size" => Some(DominantBaseline::ResetSize),
            "ideographic" => Some(DominantBaseline::Ideographic),
            "alphabetic" => Some(DominantBaseline::Alphabetic),
            "hanging" => Some(DominantBaseline::Hanging),
            "mathematical" => Some(DominantBaseline::Mathematical),
            "central" => Some(DominantBaseline::Central),
            "middle" => Some(DominantBaseline::Middle),
            "text-after-edge" => Some(DominantBaseline::TextAfterEdge),
            "text-before-edge" => Some(DominantBaseline::TextBeforeEdge),
            _ => None,
        }
    }
}

impl<'a, 'input: 'a> FromValue<'a, 'input> for LengthAdjust {
    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
        match value {
            "spacing" => Some(LengthAdjust::Spacing),
            "spacingAndGlyphs" => Some(LengthAdjust::SpacingAndGlyphs),
            _ => None,
        }
    }
}

impl<'a, 'input: 'a> FromValue<'a, 'input> for FontStyle {
    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
        match value.split_ascii_whitespace().next()? {
            "normal" => Some(FontStyle::Normal),
            "italic" => Some(FontStyle::Italic),
            "left" => Some(FontStyle::Left),
            "right" => Some(FontStyle::Right),
            "oblique" => Some(FontStyle::Oblique),
            _ => None,
        }
    }
}

/// A text character position.
///
/// _Character_ is a Unicode codepoint.
#[derive(Clone, Copy, Debug)]
struct CharacterPosition {
    /// An absolute X axis position.
    x: Option<f32>,
    /// An absolute Y axis position.
    y: Option<f32>,
    /// A relative X axis offset.
    dx: Option<f32>,
    /// A relative Y axis offset.
    dy: Option<f32>,
}

pub(crate) fn convert(
    text_node: SvgNode,
    state: &converter::State,
    cache: &mut Cache,
    parent: &mut Group,
) {
    let writing_mode = convert_writing_mode(text_node);
    let wrapping = wrapping(text_node, writing_mode, state);
    let mut pos_list = resolve_positions_list(text_node, state);
    let mut rotate_list = resolve_rotate_list(text_node, state.opt);
    // SVG 2 ยง11.7: wrapped text takes only its initial current text position from the
    // positioning attributes.
    if wrapping.is_some() {
        for position in pos_list.iter_mut().skip(1) {
            (position.x, position.y) = (None, None);
        }
        for position in &mut pos_list {
            (position.dx, position.dy) = (None, None);
        }
        rotate_list.fill(0.0);
    }

    let chunks = collect_text_chunks(text_node, &pos_list, wrapping.is_some(), state, cache);
    // The copy holds the text's characters, which only its spans' styles divide differently;
    // one that does not lays out no first line.
    let first_line = text_node.first_line().and_then(|variant| {
        let line = variant
            .first_element_child()
            .filter(SvgNode::is_first_line)
            .unwrap_or(variant);
        if count_chars(variant, state.opt) != pos_list.len() {
            return None;
        }
        let line_chunks = collect_text_chunks(variant, &pos_list, wrapping.is_some(), state, cache);
        let same = line_chunks.len() == chunks.len()
            && line_chunks
                .iter()
                .zip(&chunks)
                .all(|(a, b)| a.text == b.text);
        same.then(|| FirstLine {
            chunks: line_chunks,
            strut: strut(line, state),
        })
    });

    let rendering_mode: TextRendering = text_node
        .find_attribute(AId::TextRendering)
        .unwrap_or(state.opt.text_rendering);

    // Nodes generated by markers must not have an ID. Otherwise we would have duplicates.
    let id = if state.parent_markers.is_empty() {
        text_node.element_id().to_string()
    } else {
        String::new()
    };

    let dummy = Rect::from_xywh(0.0, 0.0, 0.0, 0.0).unwrap();

    let mut text = Text {
        id,
        rendering_mode,
        dx: pos_list.iter().map(|v| v.dx.unwrap_or(0.0)).collect(),
        dy: pos_list.iter().map(|v| v.dy.unwrap_or(0.0)).collect(),
        rotate: rotate_list,
        writing_mode,
        chunks,
        abs_transform: parent.abs_transform,
        // All fields below will be reset by `text_to_paths`.
        bounding_box: dummy,
        abs_bounding_box: dummy,
        stroke_bounding_box: dummy,
        abs_stroke_bounding_box: dummy,
        flattened: Box::new(Group::empty()),
        layouted: vec![],
        non_scaling_stroke: converter::non_scaling_stroke(text_node, state),
        linear_light: parent.linear_light,
        strut: strut(text_node, state),
        first_line,
        wrapping,
        clip: None,
    };

    let Some(shadows) = text::convert(
        &mut text,
        state.font_provider.unwrap_or(&state.opt.font_resolver),
        cache,
    ) else {
        return;
    };

    // `text-overflow: clip` clips the text and its shadows to the wrapping area.
    let mut clipped = text.clip.map(|area| Group {
        clip_path: clip_path(area, cache),
        abs_transform: parent.abs_transform,
        ..Group::empty()
    });
    let target = clipped.as_mut().unwrap_or(parent);
    // CSS Text Decoration 3 ยง4: shadows paint beneath the text, in its user space.
    for mut shadow in shadows {
        if let Node::Group(group) = &mut shadow {
            group.abs_transform = target.abs_transform.pre_concat(group.transform);
            group.calculate_bounding_boxes();
        }
        target.children.push(shadow);
    }
    target.children.push(Node::Text(Box::new(text)));
    if let Some(mut group) = clipped {
        group.calculate_bounding_boxes();
        parent.children.push(Node::Group(Box::new(group)));
    }
}

/// A clip path keeping `area` of its user space.
fn clip_path(area: NonZeroRect, cache: &mut Cache) -> Option<Arc<ClipPath>> {
    let path = Path::new(
        String::new(),
        true,
        Some(Fill::default()),
        None,
        PaintOrder::default(),
        ShapeRendering::default(),
        Arc::new(tiny_skia_path::PathBuilder::from_rect(area.to_rect())),
        Transform::default(),
    )?;
    let mut root = Group::empty();
    root.children.push(Node::Path(Box::new(path)));
    root.calculate_bounding_boxes();
    Some(Arc::new(ClipPath {
        id: cache.gen_clip_path_id(),
        transform: Transform::default(),
        clip_path: None,
        root,
    }))
}

/// The wrapping area of `text_node` (SVG 2 ยง11.4.1): its computed `inline-size`, which CSS
/// Logical 1 ยง4.1 shares with `width` in horizontal text and `height` in vertical text, with
/// percentages of the viewport's. Zero, `auto` and the sizes of an unconstrained box create none.
fn wrapping(
    text_node: SvgNode,
    writing_mode: WritingMode,
    state: &converter::State,
) -> Option<Wrapping> {
    use crate::style::{IntrinsicSizing, Size};
    let style = own_text_style(text_node, state)?;
    let vertical = writing_mode == WritingMode::TopToBottom;
    let (size, basis) = if vertical {
        (&style.height, state.view_box.height())
    } else {
        (&style.width, state.view_box.width())
    };
    let basis = state
        .unit_viewport
        .map_or(basis, |viewport| viewport[usize::from(vertical)]);
    let length = |length: &crate::paint::LengthPercentage| {
        let points = crate::style::POINTS_PER_PIXEL;
        Some(WrapWidth::Length(length.resolve(basis * points) / points))
            .filter(|width| *width != WrapWidth::Length(0.0))
    };
    let width = match size {
        Size::Value(value) | Size::Intrinsic(IntrinsicSizing::FitContentLimit(value)) => {
            length(value)?
        }
        Size::Intrinsic(IntrinsicSizing::MinContent) => WrapWidth::MinContent,
        Size::Calculated(calculated) => length(&calculated.definite()?)?,
        Size::Auto
        | Size::Intrinsic(
            IntrinsicSizing::MaxContent | IntrinsicSizing::FitContent | IntrinsicSizing::Stretch,
        ) => return None,
    };
    Some(Wrapping {
        width,
        overflow: style.text_overflow,
    })
}

struct IterState {
    /// The text has a wrapping area, which `textLength` does not apply to (SVG 2 ยง11.2.1).
    wrapped: bool,
    chars_count: usize,
    chunk_bytes_count: usize,
    split_chunk: bool,
    /// Preserved segment breaks since the last chunk started.
    line_breaks: usize,
    text_flow: TextFlow,
    chunks: Vec<TextChunk>,
    /// The ancestries of the elements whose text has spans, and each element's own entry,
    /// shared so that spans cost their own elements, not their depth.
    ancestries: HashMap<usize, Arc<[Arc<Ancestor>]>>,
    ancestors: HashMap<usize, Arc<Ancestor>>,
}

impl IterState {
    /// The text element and the ancestors with boxes of `parent`'s spans in it, outermost
    /// first.
    fn ancestry(&mut self, parent: SvgNode, state: &converter::State) -> Arc<[Arc<Ancestor>]> {
        if let Some(ancestry) = self.ancestries.get(&parent.index()) {
            return ancestry.clone();
        }
        let mut ancestry = Vec::new();
        for node in parent.ancestors() {
            if !node.is_contents() {
                let ancestor = self.ancestors.entry(node.index()).or_insert_with(|| {
                    Arc::new(Ancestor {
                        element: node.index(),
                        style: text_style(node, state),
                        font: convert_font(node, state),
                        font_size: super::units::resolve_font_size(node, state),
                    })
                });
                ancestry.push(ancestor.clone());
            }
            if node.tag_name() == Some(EId::Text) {
                break;
            }
        }
        ancestry.reverse();
        let ancestry: Arc<[Arc<Ancestor>]> = ancestry.into();
        self.ancestries.insert(parent.index(), ancestry.clone());
        ancestry
    }
}

fn collect_text_chunks(
    text_node: SvgNode,
    pos_list: &[CharacterPosition],
    wrapped: bool,
    state: &converter::State,
    cache: &mut Cache,
) -> Vec<TextChunk> {
    let mut iter_state = IterState {
        wrapped,
        chars_count: 0,
        chunk_bytes_count: 0,
        split_chunk: false,
        line_breaks: 0,
        text_flow: TextFlow::Linear,
        chunks: Vec::new(),
        ancestries: HashMap::new(),
        ancestors: HashMap::new(),
    };

    collect_text_chunks_impl(text_node, pos_list, state, cache, &mut iter_state);

    iter_state.chunks
}

fn collect_text_chunks_impl(
    parent: SvgNode,
    pos_list: &[CharacterPosition],
    state: &converter::State,
    cache: &mut Cache,
    iter_state: &mut IterState,
) {
    for child in parent.children() {
        if child.is_element() {
            // The characters of an element that renders nothing are not addressable.
            if !child.is_visible_element(state.opt) {
                continue;
            }
            let is_path = child.tag_name() == Some(EId::TextPath) && !child.is_contents();
            let previous_flow = iter_state.text_flow.clone();
            if is_path {
                if parent
                    .ancestors()
                    .find(|node| !node.is_contents() && !node.is_first_line())
                    .and_then(|node| node.tag_name())
                    != Some(EId::Text)
                {
                    // `textPath` can be set only as a direct `text` element child.
                    iter_state.chars_count += count_chars(child, state.opt);
                    continue;
                }

                match resolve_text_flow(child, state) {
                    Some(v) => {
                        iter_state.text_flow = v;
                    }
                    None => {
                        // Skip an invalid text path and all it's children.
                        // We have to update the chars count,
                        // because `pos_list` was calculated including this text path.
                        iter_state.chars_count += count_chars(child, state.opt);
                        continue;
                    }
                }

                iter_state.split_chunk = true;
            }

            collect_text_chunks_impl(child, pos_list, state, cache, iter_state);

            iter_state.text_flow = previous_flow;

            // Next char after `textPath` should be split too.
            if is_path {
                iter_state.split_chunk = true;
            }

            continue;
        }

        collect_text_node(parent, child, pos_list, state, cache, iter_state);
    }
}

/// Adds the text node `child` of `parent` to the chunks, outside the recursion over elements
/// so that its frame stays small in deep content.
#[inline(never)]
fn collect_text_node(
    parent: SvgNode,
    child: SvgNode,
    pos_list: &[CharacterPosition],
    state: &converter::State,
    cache: &mut Cache,
    iter_state: &mut IterState,
) {
    let text_orientation = parent
        .find_attribute::<&str>(AId::TextOrientation)
        .and_then(crate::style::logical::TextOrientation::from_name)
        .unwrap_or_default();
    let rtl = parent.find_attribute::<&str>(AId::Direction) == Some(RIGHT_TO_LEFT)
        && !(convert_writing_mode(parent) == WritingMode::TopToBottom
            && text_orientation == crate::style::logical::TextOrientation::Upright);
    // SVG 2 ยง11.10.1.1: in right-to-left text `start` aligns the right side, `end` the left.
    let anchor = match parent.find_attribute(AId::TextAnchor).unwrap_or_default() {
        TextAnchor::Start if rtl => TextAnchor::End,
        TextAnchor::End if rtl => TextAnchor::Start,
        anchor => anchor,
    };

    // TODO: what to do when <= 0? UB?
    let font_size = super::units::resolve_font_size(parent, state);
    let font_size = match NonZeroPositiveF32::new(font_size) {
        Some(n) => n,
        None => {
            // Skip this span.
            iter_state.chars_count += child.text().chars().count();
            return;
        }
    };

    let font = convert_font(parent, state);

    let raw_paint_order: svgtypes::PaintOrder =
        parent.find_attribute(AId::PaintOrder).unwrap_or_default();
    let paint_order = converter::svg_paint_order_to_usvg(raw_paint_order);

    let mut dominant_baseline = parent
        .find_layout_attribute(AId::DominantBaseline)
        .unwrap_or_default();

    // `no-change` means "use parent".
    if dominant_baseline == DominantBaseline::NoChange {
        dominant_baseline = parent
            .parent_element()
            .unwrap()
            .find_layout_attribute(AId::DominantBaseline)
            .unwrap_or_default();
    }

    let font_optical_sizing = match parent.find_attribute::<&str>(AId::FontOpticalSizing) {
        Some("none") => FontOpticalSizing::None,
        _ => FontOpticalSizing::Auto, // "auto" or missing (browser default)
    };

    // The `::first-line` box takes no `textLength`: it applies to the element it wraps.
    let layout_parent = parent
        .ancestors()
        .find(|node| !node.is_contents() && !node.is_first_line())
        .unwrap_or(parent);
    let mut text_length = layout_parent
        .try_convert_length(AId::TextLength, Units::UserSpaceOnUse, state)
        .filter(|_| !iter_state.wrapped);
    // Negative values should be ignored.
    if let Some(n) = text_length {
        if n < 0.0 {
            text_length = None;
        }
    }

    let visibility: Visibility = parent.find_attribute(AId::Visibility).unwrap_or_default();
    let (alignment_baseline, parent_alignment) = alignment(parent, state, cache);
    let (baseline_shift, line_edge) = convert_baseline_shift(parent, state, cache);
    let ancestry = iter_state.ancestry(parent, state);

    let span = TextSpan {
        start: 0,
        end: 0,
        fill: style::resolve_fill(parent, true, state, cache),
        stroke: style::resolve_stroke(parent, true, state, cache),
        paint_order,
        font,
        font_size,
        style: text_style(parent, state),
        ancestry,
        single_character: child.text().chars().nth(1).is_none(),
        linear_light: parent.find_attribute::<&str>(AId::ColorInterpolation)
            == Some(converter::LINEAR_RGB),
        text_orientation,
        font_optical_sizing,
        decoration: resolve_decoration(parent, state, cache),
        visible: visibility == Visibility::Visible,
        dominant_baseline,
        alignment_baseline,
        parent_alignment,
        baseline_shift,
        line_edge,
        letter_spacing: parent.resolve_length(AId::LetterSpacing, state, 0.0),
        word_spacing: parent.resolve_length(AId::WordSpacing, state, 0.0),
        text_length,
        length_adjust: parent
            .find_layout_attribute(AId::LengthAdjust)
            .unwrap_or_default(),
    };

    let mut is_new_span = true;
    for c in child.text().chars() {
        let char_len = c.len_utf8();

        // SVG 2 ยง11.6.1: a preserved segment break is an addressable character that
        // starts a new line box; text before any other starts at the break's position.
        if c == super::svgtree::SEGMENT_BREAK {
            if iter_state.chunks.is_empty() {
                iter_state.chunks.push(TextChunk {
                    x: pos_list[iter_state.chars_count].x,
                    y: pos_list[iter_state.chars_count].y,
                    anchor,
                    rtl,
                    spans: Vec::new(),
                    text_flow: iter_state.text_flow.clone(),
                    text: String::new(),
                    line_breaks: 0,
                    inline_offset: 0.0,
                    hanging: [0.0; 2],
                    soft_wrapped: false,
                    overflowing: false,
                });
            }
            iter_state.line_breaks += 1;
            iter_state.split_chunk = true;
            iter_state.chars_count += 1;
            continue;
        }

        // Create a new chunk if:
        // - this is the first span (yes, position can be None)
        // - text character has an absolute coordinate assigned to it (via x/y attribute)
        // - `c` is the first char of the `textPath`
        // - `c` is the first char after `textPath`
        let is_new_chunk = pos_list[iter_state.chars_count].x.is_some()
            || pos_list[iter_state.chars_count].y.is_some()
            || iter_state.split_chunk
            || iter_state.chunks.is_empty();

        iter_state.split_chunk = false;

        if is_new_chunk {
            iter_state.chunk_bytes_count = 0;

            let mut span2 = span.clone();
            span2.start = 0;
            span2.end = char_len;

            iter_state.chunks.push(TextChunk {
                x: pos_list[iter_state.chars_count].x,
                y: pos_list[iter_state.chars_count].y,
                anchor,
                rtl,
                spans: vec![span2],
                text_flow: iter_state.text_flow.clone(),
                text: c.to_string(),
                line_breaks: std::mem::take(&mut iter_state.line_breaks),
                inline_offset: 0.0,
                hanging: [0.0; 2],
                soft_wrapped: false,
                overflowing: false,
            });
        } else if is_new_span {
            // Add this span to the last text chunk.
            let mut span2 = span.clone();
            span2.start = iter_state.chunk_bytes_count;
            span2.end = iter_state.chunk_bytes_count + char_len;

            if let Some(chunk) = iter_state.chunks.last_mut() {
                chunk.text.push(c);
                chunk.spans.push(span2);
            }
        } else {
            // Extend the last span.
            if let Some(chunk) = iter_state.chunks.last_mut() {
                chunk.text.push(c);
                if let Some(span) = chunk.spans.last_mut() {
                    debug_assert_ne!(span.end, 0);
                    span.end += char_len;
                }
            }
        }

        is_new_span = false;
        iter_state.chars_count += 1;
        iter_state.chunk_bytes_count += char_len;
    }
}

/// CSS Inline 3 ยง4.2.2: how far below the alignment point the parent box of `node` puts its
/// `alignment` baseline, as its dominant baseline sits at the point, in its first available
/// font.
fn parent_alignment(
    node: SvgNode,
    alignment: AlignmentBaseline,
    state: &converter::State,
    cache: &mut Cache,
) -> f32 {
    use crate::svg::usvg::text::layout::DatabaseExt;
    if matches!(
        alignment,
        AlignmentBaseline::Auto | AlignmentBaseline::Baseline
    ) {
        return 0.0;
    }
    let Some(box_parent) = node
        .ancestors()
        .skip(1)
        .find(|ancestor| !ancestor.is_contents())
    else {
        return 0.0;
    };
    let provider = state.font_provider.unwrap_or(&state.opt.font_resolver);
    let Some(font) = provider
        .select_font(&convert_font(box_parent, state), &mut cache.fontdb)
        .and_then(|id| cache.fontdb.load_font(id, provider.metric_overrides(id)))
    else {
        return 0.0;
    };
    let size = super::units::resolve_font_size(box_parent, state);
    let dominant = box_parent
        .find_layout_attribute(AId::DominantBaseline)
        .unwrap_or_default();
    font.dominant_baseline_shift(dominant, size) - font.alignment_baseline_shift(alignment, size)
}

/// The computed style the document gives `node`, for content it styles.
fn own_text_style(node: SvgNode, state: &converter::State) -> Option<Arc<crate::style::Style>> {
    if let Some(index) = node.attribute::<&str>(AId::TextStyle) {
        return index
            .parse::<usize>()
            .ok()
            .and_then(|index| state.opt.styling.text_styles.get(index))
            .cloned();
    }
    // A standalone document's own cascade styles every element of it.
    (state.opt.styling.text_styles.is_empty() && node.is_element())
        .then(|| standalone_style(node, state))
}

/// The computed style of an element of a standalone document (SVG 2 ยง6.4): its parent's
/// inherited values with the presentation attributes and declarations that won its cascade,
/// with the language of `lang` and the SVG 1.1 ยง10.10 `kerning: 0` that disables kerning.
/// Values that fail to compute fail the conversion.
fn standalone_style(node: SvgNode, state: &converter::State) -> Arc<crate::style::Style> {
    let key = node.key();
    let parent = || {
        node.parent_element()
            .map_or_else(Arc::default, |parent| standalone_style(parent, state))
    };
    let cached = state.standalone_styles.borrow().get(&key).cloned();
    match cached {
        Some(Some(style)) => return style,
        // The element's font-relative lengths select its face before its own font properties
        // compute, so they take the inherited ones.
        Some(None) => return parent(),
        None => {}
    }
    let parent = parent();
    state.standalone_styles.borrow_mut().insert(key, None);
    let tag = node.tag_name().map_or("", |tag| tag.to_str());
    let attributes: Vec<(&str, &str)> = node
        .attributes()
        .iter()
        .map(|attribute| (attribute.name.to_str(), attribute.value.as_str()))
        .collect();
    // Values compute unzoomed, as their lengths measure, and are used at the effective zoom.
    let zoom = node.effective_zoom();
    let size = super::units::resolve_font_size(node, state) / zoom * crate::style::POINTS_PER_PIXEL;
    let computed = super::units::with_relative(node, state, |relative| {
        crate::style::svg_cascade::computed_style(
            tag,
            parent.canonical(),
            &attributes,
            node.declared(),
            size,
            relative,
        )
    })
    .map(|mut style| {
        style.effective_zoom = zoom;
        if let Some(language) = node.attribute::<&str>(AId::Lang) {
            language.clone_into(&mut style.language);
        }
        if node.resolve_length(AId::Kerning, state, -1.0) == 0.0 {
            style.font_features.kerning = crate::style::FontKerning::None;
        }
        style.used()
    });
    let style = Arc::new(computed.unwrap_or_else(|error| {
        state
            .length_error
            .borrow_mut()
            .get_or_insert_with(|| Arc::new(error));
        (*parent).clone()
    }));
    state
        .standalone_styles
        .borrow_mut()
        .insert(key, Some(style.clone()));
    style
}

/// The baseline of `node`'s box that aligns with the same baseline of its parent, and how far
/// below the alignment point the parent puts it. The `vertical-align` longhand keeps its CSS
/// 2.1 ยง10.8.1 meaning, as the document's does: its keywords other than `baseline` align the
/// box by its layout bounds in place of `alignment-baseline` (CSS Inline 3 ยง4.2).
fn alignment(
    node: SvgNode,
    state: &converter::State,
    cache: &mut Cache,
) -> (AlignmentBaseline, f32) {
    let legacy = node
        .ancestors()
        .find(|ancestor| !ancestor.is_contents())
        .and_then(|element| own_text_style(element, state))
        .is_some_and(|style| style.table.vertical_align != crate::style::VerticalAlign::Baseline);
    let alignment = if legacy {
        AlignmentBaseline::Baseline
    } else {
        node.find_layout_attribute(AId::AlignmentBaseline)
            .unwrap_or_default()
    };
    (alignment, parent_alignment(node, alignment, state, cache))
}

/// The layout bounds of `node`'s inline box around its baseline, and its first available
/// font's ascent, descent and x-height, in user units.
fn box_metrics(
    node: SvgNode,
    state: &converter::State,
    cache: &mut Cache,
) -> Option<([f32; 2], [f32; 3])> {
    use crate::svg::usvg::text::layout::DatabaseExt;
    let provider = state.font_provider.unwrap_or(&state.opt.font_resolver);
    let font = provider
        .select_font(&convert_font(node, state), &mut cache.fontdb)
        .and_then(|id| cache.fontdb.load_font(id, provider.metric_overrides(id)))?;
    let size = super::units::resolve_font_size(node, state);
    let metrics = font.metrics;
    let vertical = convert_writing_mode(node) == WritingMode::TopToBottom;
    Some((
        layout::line_extents(&font, size, &text_style(node, state), vertical),
        [metrics.ascent, metrics.descent, metrics.x_height].map(|metric| metric * size),
    ))
}

/// The box `node`'s inline box aligns in.
fn box_parent<'a, 'input>(node: SvgNode<'a, 'input>) -> Option<SvgNode<'a, 'input>> {
    node.ancestors()
        .skip(1)
        .find(|ancestor| !ancestor.is_contents())
}

/// How far CSS 2.1 ยง10.8.1 `vertical-align` raises the baseline of `node`, whose computed
/// style is `style`, above its parent's, as the document's line boxes align: `text-top` and
/// `text-bottom` align its layout bounds with the parent's content area, `middle` their
/// midpoint with the parent's x-height midpoint, and HTML's middle alignment with the parent's
/// baseline. `top` and `bottom` align line box edges instead.
fn legacy_shift(
    node: SvgNode,
    style: &crate::style::Style,
    state: &converter::State,
    cache: &mut Cache,
) -> Option<crate::style::BaselineShift> {
    use crate::style::{BaselineShift as Shift, VerticalAlign};
    let raise = |pixels: f32| {
        Shift::Raise(crate::paint::LengthPercentage::Length(
            pixels * crate::style::POINTS_PER_PIXEL,
        ))
    };
    Some(match &style.table.vertical_align {
        VerticalAlign::Sub => Shift::Sub,
        VerticalAlign::Super => Shift::Super,
        VerticalAlign::Length(length) => Shift::Raise(length.clone()),
        VerticalAlign::Baseline | VerticalAlign::Top | VerticalAlign::Bottom => return None,
        VerticalAlign::TextTop => {
            let ([above, _], _) = box_metrics(node, state, cache)?;
            let (_, [ascent, ..]) = box_metrics(box_parent(node)?, state, cache)?;
            raise(ascent - above)
        }
        VerticalAlign::TextBottom => {
            let ([_, below], _) = box_metrics(node, state, cache)?;
            let (_, [_, descent, _]) = box_metrics(box_parent(node)?, state, cache)?;
            raise(below - descent)
        }
        VerticalAlign::Middle => {
            let ([above, below], _) = box_metrics(node, state, cache)?;
            let (_, [.., x_height]) = box_metrics(box_parent(node)?, state, cache)?;
            raise(x_height / 2.0 + (below - above) / 2.0)
        }
        VerticalAlign::BaselineMiddle => {
            let ([above, below], _) = box_metrics(node, state, cache)?;
            raise((below - above) / 2.0)
        }
    })
}

/// CSS Inline 3 ยง4.2.3.1 `shift` of `node`, whose computed style is `style`, as the document's
/// line boxes shift: `sub` and `super` by fractions of the parent's descent and ascent, and
/// percentages of its used line height, which `normal` takes from its first available font.
fn document_baseline_shift(
    node: SvgNode,
    shift: &crate::style::BaselineShift,
    style: &crate::style::Style,
    state: &converter::State,
    cache: &mut Cache,
) -> BaselineShift {
    use crate::text::line_boxes::{SUBSCRIPT_DESCENT_FRACTION, SUPERSCRIPT_ASCENT_FRACTION};
    let parent =
        |cache: &mut Cache| box_parent(node).and_then(|parent| box_metrics(parent, state, cache));
    match shift {
        crate::style::BaselineShift::Sub => parent(cache)
            .map_or(BaselineShift::Subscript, |(_, [_, descent, _])| {
                BaselineShift::Number(-descent * SUBSCRIPT_DESCENT_FRACTION)
            }),
        crate::style::BaselineShift::Super => parent(cache)
            .map_or(BaselineShift::Superscript, |(_, [ascent, ..])| {
                BaselineShift::Number(ascent * SUPERSCRIPT_ASCENT_FRACTION)
            }),
        crate::style::BaselineShift::Raise(raise) => {
            let size = super::units::resolve_font_size(node, state);
            let points = crate::style::POINTS_PER_PIXEL;
            let line_height = style
                .line_height
                .resolve(size * points)
                .map(|height| height / points)
                .or_else(|| {
                    let provider = state.font_provider.unwrap_or(&state.opt.font_resolver);
                    let id = provider.select_font(&convert_font(node, state), &mut cache.fontdb)?;
                    cache
                        .fontdb
                        .with_face_data(id, |data, index| {
                            ttf_parser::Face::parse(data, index).ok().map(|face| {
                                crate::fonts::FaceMetrics::of(&face).normal_line_height() * size
                            })
                        })
                        .flatten()
                })
                .unwrap_or(size);
            BaselineShift::Number(raise.resolve(line_height * points) / points)
        }
    }
}

/// The computed style of the text in `node`: the embedding document's, for content it styles,
/// else the standalone document's own.
fn text_style(node: SvgNode, state: &converter::State) -> Arc<crate::style::Style> {
    node.ancestors()
        .find_map(|node| own_text_style(node, state))
        .unwrap_or_default()
}

fn resolve_text_flow(node: SvgNode, state: &converter::State) -> Option<TextFlow> {
    let linked_node = node.attribute::<SvgNode>(AId::Href)?;
    let path = super::shapes::convert(linked_node, state, super::shapes::Purpose::Paint)?;

    // The reference path's transform needs to be applied
    let transform = linked_node.resolve_transform(AId::Transform, state);
    let path = if !transform.is_identity() {
        let mut path_copy = path.as_ref().clone();
        path_copy = path_copy.transform(transform)?;
        Arc::new(path_copy)
    } else {
        path
    };

    let start_offset =
        super::units::computed_length(node, node, AId::StartOffset, Units::UserSpaceOnUse, state)
            .and_then(|length| {
                super::units::checked_length(length.resolve(path_length(&path) as f32), state)
            })
            .unwrap_or(0.0);

    let id = NonEmptyString::new(linked_node.element_id().to_string())?;
    Some(TextFlow::Path(Arc::new(TextPath {
        id,
        start_offset,
        path,
    })))
}

/// The `slnt` axis value of a default oblique.
const CLOCKWISE_SLANT_AXIS: f32 = -12.0;

pub(super) fn convert_font(node: SvgNode, state: &converter::State) -> Font {
    let style: FontStyle = node.find_attribute(AId::FontStyle).unwrap_or_default();
    let width = resolve_font_width(node);
    let weight = resolve_font_weight(node);
    let slant = resolve_font_slant(node);
    let mut variations = parse_font_variation_settings(node);
    let explicit_variations = variations.clone();

    // Auto-map standard font properties to variation axes if not explicitly set.
    // This allows variable fonts to work with regular font-weight/font-stretch properties.
    let has_wght = variations.iter().any(|v| &v.tag == b"wght");
    let has_wdth = variations.iter().any(|v| &v.tag == b"wdth");
    let has_ital = variations.iter().any(|v| &v.tag == b"ital");
    let has_slnt = variations.iter().any(|v| &v.tag == b"slnt");

    // Map font-weight to wght axis (if not already set)
    if !has_wght && weight != crate::fonts::FontWeight::NORMAL {
        variations.push(FontVariation::new(*b"wght", weight.value()));
    }

    // Map font-stretch to wdth axis (if not already set)
    if !has_wdth && width != crate::fonts::FontWidth::NORMAL {
        variations.push(FontVariation::new(*b"wdth", width.value()));
    }

    // Map font-style: italic to ital axis (if not already set)
    if !has_ital && style == FontStyle::Italic {
        variations.push(FontVariation::new(*b"ital", 1.0));
    }

    // Map font-style: oblique and the directional italics to the slnt axis (if not already
    // set), which measures counter-clockwise.
    if !has_slnt {
        match style {
            FontStyle::Oblique => {
                variations.push(FontVariation::new(*b"slnt", -slant.value()));
            }
            FontStyle::Left => {
                variations.push(FontVariation::new(*b"slnt", CLOCKWISE_SLANT_AXIS));
            }
            FontStyle::Right => {
                variations.push(FontVariation::new(*b"slnt", -CLOCKWISE_SLANT_AXIS));
            }
            FontStyle::Normal | FontStyle::Italic => {}
        }
    }

    let font_families = if let Some(n) = node.ancestors().find(|n| n.has_attribute(AId::FontFamily))
    {
        n.attribute(AId::FontFamily).unwrap_or("")
    } else {
        ""
    };

    let mut families = parse_font_families(font_families)
        .ok()
        .log_none(|| {
            log::warn!(
                "Failed to parse {} value: '{}'. Falling back to {}.",
                AId::FontFamily,
                font_families,
                state.opt.font_family
            );
        })
        .unwrap_or_default();

    let default_family = families.is_empty();
    if default_family {
        families.push(FontFamily::Named(state.opt.font_family.clone()));
    }

    Font {
        families,
        default_family,
        style,
        slant,
        width,
        weight,
        variations,
        explicit_variations,
        synthesis: text_style(node, state).font_synthesis,
    }
}

/// Parses the `font-variation-settings` CSS property.
///
/// Syntax: `normal | [ <string> <number> ]#`
/// Example: `"wght" 700, "wdth" 50`
fn parse_font_variation_settings(node: SvgNode) -> Vec<FontVariation> {
    let value = if let Some(n) = node
        .ancestors()
        .find(|n| n.has_attribute(AId::FontVariationSettings))
    {
        let v = n.attribute(AId::FontVariationSettings).unwrap_or("");
        log::debug!("Found font-variation-settings: '{}'", v);
        v
    } else {
        return Vec::new();
    };

    // "normal" means no variations
    if value.eq_ignore_ascii_case("normal") || value.is_empty() {
        return Vec::new();
    }

    let mut variations = Vec::new();

    // Parse comma-separated list of "tag" value pairs
    for part in value.split(',') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }

        // Find the tag (quoted string) and value
        // Format: "wght" 700 or 'wght' 700
        let mut chars = part.chars().peekable();

        // Skip whitespace
        while chars.peek().map_or(false, |c| c.is_whitespace()) {
            chars.next();
        }

        // Parse quoted tag
        let quote = match chars.next() {
            Some('"') => '"',
            Some('\'') => '\'',
            _ => continue, // Invalid format
        };

        let mut tag_str = String::new();
        for c in chars.by_ref() {
            if c == quote {
                break;
            }
            tag_str.push(c);
        }

        // Tag must be exactly 4 characters
        if tag_str.len() != 4 {
            log::warn!(
                "Invalid font-variation-settings tag: '{}' (must be 4 characters)",
                tag_str
            );
            continue;
        }

        // Skip whitespace before value
        while chars.peek().map_or(false, |c| c.is_whitespace()) {
            chars.next();
        }

        // Parse the numeric value
        let value_str: String = chars.collect();
        let value_str = value_str.trim();

        let value = match value_str.parse::<f32>() {
            Ok(v) => v,
            Err(_) => {
                log::warn!("Invalid font-variation-settings value: '{}'", value_str);
                continue;
            }
        };

        let tag_bytes = tag_str.as_bytes();
        let tag = [tag_bytes[0], tag_bytes[1], tag_bytes[2], tag_bytes[3]];

        variations.push(FontVariation::new(tag, value));
    }

    variations
}

/// CSS Fonts 4 ยง2.3 `font-width` (`font-stretch`): a keyword or a percentage.
fn resolve_font_width(node: SvgNode) -> crate::fonts::FontWidth {
    use crate::fonts::FontWidth;
    let Some(n) = node.ancestors().find(|n| n.has_attribute(AId::FontStretch)) else {
        return FontWidth::NORMAL;
    };
    match n.attribute(AId::FontStretch).unwrap_or("") {
        "narrower" | "condensed" => FontWidth::CONDENSED,
        "ultra-condensed" => FontWidth::ULTRA_CONDENSED,
        "extra-condensed" => FontWidth::EXTRA_CONDENSED,
        "semi-condensed" => FontWidth::SEMI_CONDENSED,
        "semi-expanded" => FontWidth::SEMI_EXPANDED,
        "wider" | "expanded" => FontWidth::EXPANDED,
        "extra-expanded" => FontWidth::EXTRA_EXPANDED,
        "ultra-expanded" => FontWidth::ULTRA_EXPANDED,
        value => value
            .strip_suffix('%')
            .and_then(|number| number.parse::<f32>().ok())
            .and_then(|percentage| FontWidth::new(percentage).ok())
            .unwrap_or(FontWidth::NORMAL),
    }
}

/// The angle of `font-style: oblique <angle>` (CSS Fonts 4 ยง2.4), 14deg when omitted.
fn resolve_font_slant(node: SvgNode) -> crate::fonts::FontSlant {
    node.ancestors()
        .find(|n| n.has_attribute(AId::FontStyle))
        .and_then(|n| n.attribute::<&str>(AId::FontStyle))
        .and_then(|value| value.split_ascii_whitespace().nth(1))
        .and_then(|angle| <svgtypes::Angle as std::str::FromStr>::from_str(angle).ok())
        .and_then(|angle| crate::fonts::FontSlant::new(angle.to_degrees() as f32).ok())
        .unwrap_or(crate::fonts::FontSlant::DEFAULT)
}

const RIGHT_TO_LEFT: &str = "rtl";
/// CSS Fonts 4 ยง2.2 font weights, resolved from the root down: keywords, any number from 1 to
/// 1000, and the relative weights of the ยง2.2.1 table.
fn resolve_font_weight(node: SvgNode) -> crate::fonts::FontWeight {
    use crate::fonts::FontWeight;
    let nodes: Vec<_> = node.ancestors().collect();
    let mut weight = FontWeight::NORMAL;
    for n in nodes.iter().rev().skip(1) {
        // skip Root
        weight = match n.attribute(AId::FontWeight).unwrap_or("") {
            "normal" => FontWeight::NORMAL,
            "bold" => FontWeight::BOLD,
            "bolder" => weight.bolder(),
            "lighter" => weight.lighter(),
            number => number
                .parse::<f32>()
                .ok()
                .and_then(|number| FontWeight::new(number).ok())
                .unwrap_or(weight),
        };
    }
    weight
}

/// Resolves text's character positions.
///
/// This includes: x, y, dx, dy.
///
/// # The character
///
/// The first problem with this task is that the *character* itself
/// is basically undefined in the SVG spec. Sometimes it's an *XML character*,
/// sometimes a *glyph*, and sometimes just a *character*.
///
/// There is an ongoing [discussion](https://github.com/w3c/svgwg/issues/537)
/// on the SVG working group that addresses this by stating that a character
/// is a Unicode code point. But it's not final.
///
/// Also, according to the SVG 2 spec, *character* is *a Unicode code point*.
///
/// Anyway, we treat a character as a Unicode code point.
///
/// # Algorithm
///
/// To resolve positions, we have to iterate over descendant nodes and
/// if the current node is a `tspan` and has x/y/dx/dy attribute,
/// than the positions from this attribute should be assigned to the characters
/// of this `tspan` and it's descendants.
///
/// Positions list can have more values than characters in the `tspan`,
/// so we have to clamp it, because values should not overlap, e.g.:
///
/// (we ignore whitespaces for example purposes,
/// so the `text` content is `Text` and not `T ex t`)
///
/// ```text
/// <text>
///   a
///   <tspan x="10 20 30">
///     bc
///   </tspan>
///   d
/// </text>
/// ```
///
/// In this example, the `d` position should not be set to `30`.
/// And the result should be: `[None, 10, 20, None]`
///
/// Another example:
///
/// ```text
/// <text>
///   <tspan x="100 110 120 130">
///     a
///     <tspan x="50">
///       bc
///     </tspan>
///   </tspan>
///   d
/// </text>
/// ```
///
/// The result should be: `[100, 50, 120, None]`
fn resolve_positions_list(text_node: SvgNode, state: &converter::State) -> Vec<CharacterPosition> {
    // Allocate a list that has all characters positions set to `None`.
    let total_chars = count_chars(text_node, state.opt);
    let mut list = vec![
        CharacterPosition {
            x: None,
            y: None,
            dx: None,
            dy: None,
        };
        total_chars
    ];

    let mut offset = 0;
    for child in std::iter::once(text_node).chain(addressable(text_node, state.opt)) {
        if child.is_element() {
            // We must ignore text positions on `textPath`.
            if child.is_contents()
                || !matches!(child.tag_name(), Some(EId::Text) | Some(EId::Tspan))
            {
                continue;
            }

            let child_chars = count_chars(child, state.opt);
            macro_rules! push_list {
                ($aid:expr, $field:ident) => {
                    if let Some(num_list) = super::units::convert_list(child, child, $aid, state) {
                        // Note that we are using not the total count,
                        // but the amount of characters in the current `tspan` (with children).
                        let len = std::cmp::min(num_list.len(), child_chars);
                        for i in 0..len {
                            list[offset + i].$field = Some(num_list[i]);
                        }
                    }
                };
            }

            push_list!(AId::X, x);
            push_list!(AId::Y, y);
            push_list!(AId::Dx, dx);
            push_list!(AId::Dy, dy);
        } else if child.is_text() {
            // Advance the offset.
            offset += child.text().chars().count();
        }
    }

    list
}

/// Resolves characters rotation.
///
/// The algorithm is well explained
/// [in the SVG spec](https://www.w3.org/TR/SVG11/text.html#TSpanElement) (scroll down a bit).
///
/// ![](https://www.w3.org/TR/SVG11/images/text/tspan05-diagram.png)
///
/// Note: this algorithm differs from the position resolving one.
fn resolve_rotate_list(text_node: SvgNode, opt: &Options) -> Vec<f32> {
    // Allocate a list that has all characters angles set to `0.0`.
    let mut list = vec![0.0; count_chars(text_node, opt)];
    let mut last = 0.0;
    let mut offset = 0;
    for child in std::iter::once(text_node).chain(addressable(text_node, opt)) {
        if child.is_element() && !child.is_contents() {
            if let Some(rotate) = child.attribute::<Vec<f32>>(AId::Rotate) {
                for i in 0..count_chars(child, opt) {
                    if let Some(a) = rotate.get(i).cloned() {
                        list[offset + i] = a;
                        last = a;
                    } else {
                        // If the rotate list doesn't specify the rotation for
                        // this character - use the last one.
                        list[offset + i] = last;
                    }
                }
            }
        } else if child.is_text() {
            // Advance the offset.
            offset += child.text().chars().count();
        }
    }

    list
}

/// Resolves node's `text-decoration` property.
fn resolve_decoration(
    tspan: SvgNode,
    state: &converter::State,
    cache: &mut Cache,
) -> TextDecoration {
    use crate::paint::DecorationLine;
    // The decoration `node` declares: its computed one where the document styles it, else the
    // lines of its attribute.
    let declared = |node: SvgNode| -> Option<crate::style::TextDecoration> {
        if node.is_contents() {
            return None;
        }
        if let Some(style) = own_text_style(node, state) {
            return Some(style.text_decorations.declared);
        }
        let mut lines = crate::style::DecorationLines::default();
        for name in node
            .attribute::<&str>(AId::TextDecoration)?
            .split_ascii_whitespace()
        {
            match name {
                UNDERLINE => lines.underline = true,
                OVERLINE => lines.overline = true,
                LINE_THROUGH => lines.line_through = true,
                _ => {}
            }
        }
        Some(crate::style::TextDecoration {
            lines,
            ..crate::style::TextDecoration::default()
        })
    };

    // The nearest ancestor declaring a line decorates the text with it, possibly from outside
    // the `text` element; the fill and stroke are those of that ancestor or, nearer, of the
    // `text` element (SVG 2 ยง11.11).
    let mut gen_style = |line: DecorationLine| {
        let (node, decoration) = tspan.ancestors().find_map(|node| {
            declared(node)
                .filter(|decoration| crate::text::decoration::draws(decoration, line))
                .map(|decoration| (node, decoration))
        })?;
        let paint_node = tspan
            .ancestors()
            .find(|ancestor| *ancestor == node || ancestor.tag_name() == Some(EId::Text))
            .unwrap_or(node);
        Some(TextDecorationStyle {
            fill: style::resolve_fill(paint_node, true, state, cache),
            stroke: style::resolve_stroke(paint_node, true, state, cache),
            declared: decoration,
            style: text_style(node, state),
            element: node.index(),
        })
    };

    TextDecoration {
        underline: gen_style(DecorationLine::Underline),
        overline: gen_style(DecorationLine::Overline),
        line_through: gen_style(DecorationLine::LineThrough),
    }
}

/// The `text-decoration-line` keywords of the `text-decoration` attribute.
const UNDERLINE: &str = "underline";
const OVERLINE: &str = "overline";
const LINE_THROUGH: &str = "line-through";

/// The baseline shifts of `node` and its ancestors in the text, innermost first, up to the
/// nearest that aligns its subtree with a line box edge instead. Shifts of the `vertical-align`
/// longhand add to those of `baseline-shift` (CSS Inline 3 ยง4.2).
fn convert_baseline_shift(
    node: SvgNode,
    state: &converter::State,
    cache: &mut Cache,
) -> (Vec<BaselineShift>, Option<LineEdge>) {
    use crate::style::VerticalAlign;
    let mut shift = Vec::new();
    let mut edge = None;
    let nodes: Vec<_> = node
        .ancestors()
        .take_while(|n| n.tag_name() != Some(EId::Text))
        .collect();
    for n in nodes.into_iter().filter(|node| !node.is_contents()) {
        if let Some(style) = own_text_style(n, state) {
            // Edge alignment replaces the element's shifts and its ancestors'.
            if matches!(
                style.table.vertical_align,
                VerticalAlign::Top | VerticalAlign::Bottom
            ) {
                edge = Some(LineEdge {
                    bottom: style.table.vertical_align == VerticalAlign::Bottom,
                    root: n.index(),
                    strut: strut(n, state),
                });
                break;
            }
            let legacy = legacy_shift(n, &style, state, cache);
            for value in legacy.iter().chain([&style.baseline.shift]) {
                shift.push(document_baseline_shift(n, value, &style, state, cache));
            }
        } else if let Some(length) =
            super::units::computed_length(n, n, AId::BaselineShift, Units::UserSpaceOnUse, state)
        {
            let basis = super::units::resolve_font_size(n, state);
            if let Some(value) = super::units::checked_length(length.resolve(basis), state) {
                shift.push(BaselineShift::Number(value));
            }
        } else if let Some(s) = n.attribute(AId::BaselineShift) {
            match s {
                "sub" => shift.push(BaselineShift::Subscript),
                "super" => shift.push(BaselineShift::Superscript),
                _ => shift.push(BaselineShift::Baseline),
            }
        }
    }

    if shift
        .iter()
        .all(|base| matches!(base, BaselineShift::Baseline))
    {
        shift.clear();
    }

    (shift, edge)
}

/// The font and computed style of `node`'s inline box.
fn strut(node: SvgNode, state: &converter::State) -> Strut {
    Strut {
        font: convert_font(node, state),
        font_size: super::units::resolve_font_size(node, state),
        style: text_style(node, state),
    }
}

/// The addressable characters in `node` (SVG 2 ยง11.1): those outside the elements inside it
/// that render nothing.
fn count_chars(node: SvgNode, opt: &Options) -> usize {
    addressable(node, opt)
        .filter(|n| n.is_text())
        .fold(0, |w, n| w + n.text().chars().count())
}

/// The descendants of `node` in tree order outside the elements inside it that render
/// nothing, whose characters positioning attributes do not address (SVG 2 ยง11.1).
fn addressable<'a, 'input: 'a>(
    node: SvgNode<'a, 'input>,
    opt: &'a Options,
) -> impl Iterator<Item = SvgNode<'a, 'input>> + 'a {
    let mut pending: Vec<_> = node.children().collect();
    pending.reverse();
    std::iter::from_fn(move || {
        while let Some(next) = pending.pop() {
            if next.is_element() {
                if !next.is_visible_element(opt) {
                    continue;
                }
                let start = pending.len();
                pending.extend(next.children());
                pending[start..].reverse();
            }
            return Some(next);
        }
        None
    })
}

/// Converts the writing mode.
///
/// [SVG 2] references [CSS Writing Modes Level 3] for the definition of the
/// 'writing-mode' property, there are only two writing modes:
/// horizontal left-to-right and vertical right-to-left.
///
/// That specification introduces new values for the property. The SVG 1.1
/// values are obsolete but must still be supported by converting the specified
/// values to computed values as follows:
///
/// - `lr`, `lr-tb`, `rl`, `rl-tb` => `horizontal-tb`
/// - `tb`, `tb-rl` => `vertical-rl`
///
/// The current `vertical-lr` behaves exactly the same as `vertical-rl`.
///
/// Also, looks like no one really supports the `rl` and `rl-tb`, except `Batik`.
/// And I'm not sure if its behaviour is correct.
///
/// So we will ignore it as well, mainly because I have no idea how exactly
/// it should affect the rendering.
///
/// [SVG 2]: https://www.w3.org/TR/SVG2/text.html#WritingModeProperty
/// [CSS Writing Modes Level 3]: https://www.w3.org/TR/css-writing-modes-3/#svg-writing-mode-css
pub(super) fn convert_writing_mode(text_node: SvgNode) -> WritingMode {
    if let Some(n) = text_node
        .ancestors()
        .find(|n| n.has_attribute(AId::WritingMode))
    {
        match n.attribute(AId::WritingMode).unwrap_or("lr-tb") {
            "tb" | "tb-rl" | "vertical-rl" | "vertical-lr" => WritingMode::TopToBottom,
            _ => WritingMode::LeftToRight,
        }
    } else {
        WritingMode::LeftToRight
    }
}

fn path_length(path: &tiny_skia_path::Path) -> f64 {
    let mut prev_mx = path.points()[0].x;
    let mut prev_my = path.points()[0].y;
    let mut prev_x = prev_mx;
    let mut prev_y = prev_my;

    fn create_curve_from_line(px: f32, py: f32, x: f32, y: f32) -> kurbo::CubicBez {
        let line = kurbo::Line::new(
            kurbo::Point::new(px as f64, py as f64),
            kurbo::Point::new(x as f64, y as f64),
        );
        let p1 = line.eval(0.33);
        let p2 = line.eval(0.66);
        kurbo::CubicBez::new(line.p0, p1, p2, line.p1)
    }

    let mut length = 0.0;
    for seg in path.segments() {
        let curve = match seg {
            tiny_skia_path::PathSegment::MoveTo(p) => {
                prev_mx = p.x;
                prev_my = p.y;
                prev_x = p.x;
                prev_y = p.y;
                continue;
            }
            tiny_skia_path::PathSegment::LineTo(p) => {
                create_curve_from_line(prev_x, prev_y, p.x, p.y)
            }
            tiny_skia_path::PathSegment::QuadTo(p1, p) => kurbo::QuadBez::new(
                kurbo::Point::new(prev_x as f64, prev_y as f64),
                kurbo::Point::new(p1.x as f64, p1.y as f64),
                kurbo::Point::new(p.x as f64, p.y as f64),
            )
            .raise(),
            tiny_skia_path::PathSegment::CubicTo(p1, p2, p) => kurbo::CubicBez::new(
                kurbo::Point::new(prev_x as f64, prev_y as f64),
                kurbo::Point::new(p1.x as f64, p1.y as f64),
                kurbo::Point::new(p2.x as f64, p2.y as f64),
                kurbo::Point::new(p.x as f64, p.y as f64),
            ),
            tiny_skia_path::PathSegment::Close => {
                create_curve_from_line(prev_x, prev_y, prev_mx, prev_my)
            }
        };

        length += curve.arclen(0.5);
        prev_x = curve.p3.x as f32;
        prev_y = curve.p3.y as f32;
    }

    length
}