ferri-pdf 0.1.9

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
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
// Copyright 2018 the Resvg Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT

use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::str::FromStr;
use std::sync::Arc;

use fontdb::Database;
use fontdb::ID;
use rustybuzz::ttf_parser::GlyphId;
use svgtypes::{Length, LengthUnit as Unit, PaintOrderKind, TransformOrigin};
use tiny_skia_path::PathBuilder;

use super::motion::Placement;
use super::svgtree::{self, AId, EId, FromValue, SvgNode};
use super::units::{self, convert_length};
use super::{Error, Options, marker};
use crate::svg::usvg::flatten::BitmapImage;
use crate::svg::usvg::parser::paint_server::process_paint;
use crate::svg::usvg::text::flatten::DatabaseExt;
use crate::svg::usvg::*;

/// CSS Transforms 1 §2 `transform-box` reference boxes measured from content.
pub(super) const FILL_BOX: &str = "fill-box";
pub(super) const STROKE_BOX: &str = "stroke-box";
const PERCENT: f32 = 100.0;
/// SVG 2 §13.9 `color-interpolation: linearRGB`.
pub(super) const LINEAR_RGB: &str = "linearRGB";

#[derive(Clone)]
pub(super) struct State<'a> {
    pub(crate) length_error: std::rc::Rc<std::cell::RefCell<Option<Arc<crate::style::StyleError>>>>,
    /// The computed styles of a standalone document's elements, as text computes them; `None`
    /// while an element's own is computing.
    pub(crate) standalone_styles: std::rc::Rc<
        std::cell::RefCell<HashMap<svgtree::NodeKey, Option<Arc<crate::style::Style>>>>,
    >,
    pub(crate) parent_clip_path: Option<SvgNode<'a, 'a>>,
    pub(crate) parent_markers: Vec<SvgNode<'a, 'a>>,
    /// Stores the resolved fill and stroke of a use node
    /// or a path element (for markers)
    pub(crate) context_element: Option<(Option<Fill>, Option<Stroke>)>,
    pub(crate) fe_image_link: bool,
    /// A viewBox of the parent SVG element.
    pub(crate) view_box: NonZeroRect,
    pub(crate) unit_viewport: Option<[f32; 2]>,
    /// A size of the parent `use` element.
    /// Used only during nested `svg` size resolving.
    /// Width and height can be set independently.
    pub(crate) use_size: (Option<f32>, Option<f32>),
    pub(crate) opt: &'a Options<'a>,
    /// Resolves an image reference, given how deep it would draw.
    pub(crate) image_resolver: Option<&'a dyn Fn(&str, &Options, Nesting) -> Option<ImageKind>>,
    pub(crate) font_provider: Option<&'a dyn FontProvider>,
}

impl<'a> State<'a> {
    pub(super) fn new(opt: &'a Options<'a>, view_box: NonZeroRect) -> Self {
        Self {
            length_error: Default::default(),
            standalone_styles: Default::default(),
            parent_clip_path: None,
            context_element: None,
            parent_markers: Vec::new(),
            fe_image_link: false,
            view_box,
            unit_viewport: None,
            use_size: (None, None),
            opt,
            image_resolver: None,
            font_provider: None,
        }
    }
}

#[derive(Clone, PartialEq, Eq, Hash)]
pub(crate) struct ResourceKey {
    pub(super) source: String,
    zoom: u32,
    font_size: u32,
    viewport: [u32; 2],
    bounds: Option<[u32; 4]>,
}

impl ResourceKey {
    pub(super) fn new(
        source: SvgNode,
        target: SvgNode,
        state: &State,
        bounds: Option<NonZeroRect>,
    ) -> Self {
        Self {
            source: source.element_id().to_owned(),
            zoom: target.effective_zoom().to_bits(),
            font_size: units::resolve_font_size(target, state).to_bits(),
            viewport: state
                .unit_viewport
                .unwrap_or([state.view_box.width(), state.view_box.height()])
                .map(f32::to_bits),
            bounds: bounds.map(|bounds| {
                [bounds.x(), bounds.y(), bounds.width(), bounds.height()].map(f32::to_bits)
            }),
        }
    }
}

/// How deep conversion nests: its groups, and the resources it references, each referenced
/// from inside the last. A document drawn as an image converts nested in its drawing.
#[derive(Clone, Copy, Debug, Default)]
pub struct Nesting {
    pub(crate) groups: usize,
    pub(crate) references: usize,
}

#[derive(Clone)]
pub(crate) struct Cache {
    /// This fontdb is initialized from [`Options::fontdb`] and then populated
    /// over the course of conversion.
    pub fontdb: Arc<Database>,
    pub(crate) style_error: Option<Arc<crate::style::StyleError>>,
    /// The groups converting, each inside the last: the tree's and those of the resources
    /// it references.
    depth: usize,
    /// The resources converting, each referenced from inside the last.
    references: usize,
    /// The deepest `depth` reached, with the depth of the SVG images drawn there.
    deepest: usize,
    /// Content nested past `MAX_CONVERSION_DEPTH` or `MAX_REFERENCE_DEPTH` was omitted.
    pub(crate) limited: bool,
    /// The elements converted where they render, each as many times as references draw it.
    converted: usize,
    /// Elements past `MAX_SVG_NODES` converted were omitted.
    truncated: bool,

    cache_outline: HashMap<(ID, GlyphId), Option<tiny_skia_path::Path>>,
    /// Keyed by the bits of each painting's location, palette and foreground as well.
    cache_colr: HashMap<(ID, GlyphId, Vec<u32>), Option<Tree>>,
    cache_svg: HashMap<(ID, GlyphId), Option<Node>>,
    cache_raster: HashMap<(ID, GlyphId), Option<BitmapImage>>,
    cache_has_opsz: HashMap<ID, bool>,

    pub clip_paths: HashMap<ResourceKey, Arc<ClipPath>>,
    pub masks: HashMap<ResourceKey, Arc<Mask>>,
    pub filters: HashMap<ResourceKey, Arc<filter::Filter>>,
    pub paint: HashMap<ResourceKey, Paint>,

    // used for ID generation
    all_ids: HashSet<u64>,
    linear_gradient_index: usize,
    radial_gradient_index: usize,
    sweep_gradient_index: usize,
    pattern_index: usize,
    clip_path_index: usize,
    mask_index: usize,
    filter_index: usize,
    image_index: usize,
    /// The perspective, in points, that each converted element with one gives its children.
    pub(crate) perspectives: HashMap<svgtree::NodeKey, crate::style::transform::Matrix3d>,
    /// The fill and stroke bounding boxes of the content of each element measured so far for
    /// its reference box, in the tree or resource converting.
    measured: HashMap<(svgtree::NodeKey, Measured), [Rect; 2]>,
    /// How many measurements converting content nest, each inside the last.
    measuring: usize,
}

macro_rules! font_lookup {
    ($method_name:ident, $cache_map:ident, $font_variant:ident, $return_type:ty) => {
        pub(crate) fn $method_name(&mut self, font: ID, glyph: GlyphId) -> Option<$return_type> {
            let key = (font, glyph);
            match self.$cache_map.get(&key) {
                Some(cache_hit) => cache_hit.clone(),
                None => {
                    let lookup = self.fontdb.$font_variant(font, glyph);
                    self.$cache_map.insert(key, lookup.clone());
                    lookup
                }
            }
        }
    };
}

impl Cache {
    pub(crate) fn new(fontdb: Arc<Database>) -> Self {
        Self {
            fontdb,
            style_error: None,
            depth: 0,
            references: 0,
            deepest: 0,
            limited: false,
            converted: 0,
            truncated: false,

            cache_outline: HashMap::new(),
            cache_colr: HashMap::new(),
            cache_svg: HashMap::new(),
            cache_raster: HashMap::new(),
            cache_has_opsz: HashMap::new(),

            clip_paths: HashMap::new(),
            masks: HashMap::new(),
            filters: HashMap::new(),
            paint: HashMap::new(),

            all_ids: HashSet::new(),
            linear_gradient_index: 0,
            radial_gradient_index: 0,
            sweep_gradient_index: 0,
            pattern_index: 0,
            clip_path_index: 0,
            mask_index: 0,
            filter_index: 0,
            image_index: 0,
            perspectives: HashMap::new(),
            measured: HashMap::new(),
            measuring: 0,
        }
    }

    // TODO: macros?
    /// How deep the groups and references converting nest.
    pub(crate) fn nesting(&self) -> Nesting {
        Nesting {
            groups: self.depth,
            references: self.references,
        }
    }

    /// Whether an SVG image whose groups nest `depth` deep may draw inside the groups
    /// converting: rendering nests its groups in theirs within `MAX_CONVERSION_DEPTH`.
    pub(crate) fn draws_nested(&mut self, depth: usize) -> bool {
        let nested = self.depth + depth;
        if nested > MAX_CONVERSION_DEPTH {
            self.limited = true;
            return false;
        }
        self.deepest = self.deepest.max(nested);
        true
    }

    /// What `convert` makes of the content of a resource that an element references, which
    /// is omitted, as an invalid reference is, past `MAX_REFERENCE_DEPTH` nested references.
    /// The resource converts whole, for the caches that keep it, and measures its own content:
    /// its elements convert again in other contexts.
    pub(crate) fn referenced<T>(
        &mut self,
        convert: impl FnOnce(&mut Self) -> Option<T>,
    ) -> Option<T> {
        if self.references >= MAX_REFERENCE_DEPTH {
            self.limited = true;
            return None;
        }
        let measured = std::mem::take(&mut self.measured);
        let measuring = std::mem::replace(&mut self.measuring, 0);
        self.references += 1;
        let converted = convert(self);
        self.references -= 1;
        self.measured = measured;
        self.measuring = measuring;
        converted
    }

    pub(crate) fn gen_linear_gradient_id(&mut self) -> NonEmptyString {
        loop {
            self.linear_gradient_index += 1;
            let new_id = format!("linearGradient{}", self.linear_gradient_index);
            let new_hash = string_hash(&new_id);
            if !self.all_ids.contains(&new_hash) {
                return NonEmptyString::new(new_id).unwrap();
            }
        }
    }

    pub(crate) fn gen_radial_gradient_id(&mut self) -> NonEmptyString {
        loop {
            self.radial_gradient_index += 1;
            let new_id = format!("radialGradient{}", self.radial_gradient_index);
            let new_hash = string_hash(&new_id);
            if !self.all_ids.contains(&new_hash) {
                return NonEmptyString::new(new_id).unwrap();
            }
        }
    }

    pub(crate) fn gen_sweep_gradient_id(&mut self) -> NonEmptyString {
        loop {
            self.sweep_gradient_index += 1;
            let new_id = format!("sweepGradient{}", self.sweep_gradient_index);
            let new_hash = string_hash(&new_id);
            if !self.all_ids.contains(&new_hash) {
                return NonEmptyString::new(new_id).unwrap();
            }
        }
    }

    pub(crate) fn gen_pattern_id(&mut self) -> NonEmptyString {
        loop {
            self.pattern_index += 1;
            let new_id = format!("pattern{}", self.pattern_index);
            let new_hash = string_hash(&new_id);
            if !self.all_ids.contains(&new_hash) {
                return NonEmptyString::new(new_id).unwrap();
            }
        }
    }

    pub(crate) fn gen_clip_path_id(&mut self) -> NonEmptyString {
        loop {
            self.clip_path_index += 1;
            let new_id = format!("clipPath{}", self.clip_path_index);
            let new_hash = string_hash(&new_id);
            if !self.all_ids.contains(&new_hash) {
                return NonEmptyString::new(new_id).unwrap();
            }
        }
    }

    pub(crate) fn gen_mask_id(&mut self) -> NonEmptyString {
        loop {
            self.mask_index += 1;
            let new_id = format!("mask{}", self.mask_index);
            let new_hash = string_hash(&new_id);
            if !self.all_ids.contains(&new_hash) {
                return NonEmptyString::new(new_id).unwrap();
            }
        }
    }

    pub(crate) fn gen_filter_id(&mut self) -> NonEmptyString {
        loop {
            self.filter_index += 1;
            let new_id = format!("filter{}", self.filter_index);
            let new_hash = string_hash(&new_id);
            if !self.all_ids.contains(&new_hash) {
                return NonEmptyString::new(new_id).unwrap();
            }
        }
    }

    pub(crate) fn gen_image_id(&mut self) -> NonEmptyString {
        loop {
            self.image_index += 1;
            let new_id = format!("image{}", self.image_index);
            let new_hash = string_hash(&new_id);
            if !self.all_ids.contains(&new_hash) {
                return NonEmptyString::new(new_id).unwrap();
            }
        }
    }

    font_lookup!(fontdb_outline, cache_outline, outline, tiny_skia_path::Path);

    pub(crate) fn fontdb_colr(
        &mut self,
        font: ID,
        glyph: GlyphId,
        paint: &flatten::ColrPaint<'_>,
    ) -> Option<Tree> {
        let key = (font, glyph, paint.key());
        if let Some(cached) = self.cache_colr.get(&key) {
            return cached.clone();
        }
        let lookup = self.fontdb.colr(font, glyph, paint);
        self.cache_colr.insert(key, lookup.clone());
        lookup
    }
    font_lookup!(fontdb_svg, cache_svg, svg, Node);
    font_lookup!(fontdb_raster, cache_raster, raster, BitmapImage);

    pub(crate) fn has_opsz_axis(&mut self, font: ID) -> bool {
        if let Some(&cached) = self.cache_has_opsz.get(&font) {
            return cached;
        }
        let has_opsz = self.fontdb.has_opsz_axis(font);
        self.cache_has_opsz.insert(font, has_opsz);
        has_opsz
    }
}

// TODO: is there a simpler way?
fn string_hash(s: &str) -> u64 {
    let mut h = std::collections::hash_map::DefaultHasher::new();
    s.hash(&mut h);
    h.finish()
}

impl<'a, 'input: 'a> SvgNode<'a, 'input> {
    pub(crate) fn convert_length(
        &self,
        aid: AId,
        object_units: Units,
        state: &State,
        def: Length,
    ) -> f32 {
        let positioned =
            !(self.is_contents() && matches!(aid, AId::X | AId::Y | AId::Width | AId::Height));
        if positioned && let Some(value) = self.try_convert_length(aid, object_units, state) {
            return value;
        }
        let automatic = convert_length(def, *self, aid, object_units, state);
        if positioned && matches!(aid, AId::Width | AId::Height) {
            return units::automatic_size(*self, aid, automatic, state);
        }
        automatic
    }

    pub(super) fn convert_user_length(&self, aid: AId, state: &State, def: Length) -> f32 {
        self.convert_length(aid, Units::UserSpaceOnUse, state, def)
    }

    pub(super) fn parse_viewbox(&self, zoom: f32) -> Option<NonZeroRect> {
        let vb: svgtypes::ViewBox = self.attribute(AId::ViewBox)?;
        NonZeroRect::from_xywh(
            vb.x as f32 * zoom,
            vb.y as f32 * zoom,
            vb.w as f32 * zoom,
            vb.h as f32 * zoom,
        )
    }

    pub(super) fn resolve_length(&self, aid: AId, state: &State, def: f32) -> f32 {
        debug_assert!(
            !matches!(aid, AId::BaselineShift | AId::FontSize),
            "{} cannot be resolved via this function",
            aid
        );

        if let Some(n) = self.length_owner(aid) {
            if let Some(length) = units::computed_length(n, n, aid, Units::UserSpaceOnUse, state) {
                let basis = units::convert_user_length(
                    Length::new(100.0, Unit::Percent),
                    *self,
                    aid,
                    state,
                );
                let value = length
                    .zoomed(self.effective_zoom() / n.effective_zoom())
                    .resolve(basis);
                return units::checked_length(value, state).unwrap_or(def * self.effective_zoom());
            }
        }

        def * self.effective_zoom()
    }

    pub(super) fn resolve_valid_length(
        &self,
        aid: AId,
        state: &State,
        def: f32,
    ) -> Option<NonZeroPositiveF32> {
        let n = self.resolve_length(aid, state, def);
        NonZeroPositiveF32::new(n)
    }

    pub(crate) fn try_convert_length(
        &self,
        aid: AId,
        object_units: Units,
        state: &State,
    ) -> Option<f32> {
        let value = units::computed_length(*self, *self, aid, object_units, state)?;
        let basis = convert_length(
            Length::new(100.0, Unit::Percent),
            *self,
            aid,
            object_units,
            state,
        );
        units::checked_length(value.resolve(basis), state)
    }

    pub(super) fn has_valid_transform(&self, aid: AId) -> bool {
        // Do not use Node::attribute::<Transform>, because it will always
        // return a valid transform.

        let attr = match self.attribute(aid) {
            Some(attr) => attr,
            None => return true,
        };

        let ts = match svgtypes::Transform::from_str(attr) {
            Ok(v) => v,
            Err(_) => return true,
        };

        let ts = Transform::from_row(
            ts.a as f32,
            ts.b as f32,
            ts.c as f32,
            ts.d as f32,
            ts.e as f32,
            ts.f as f32,
        );
        ts.is_valid()
    }

    pub(super) fn is_contents(&self) -> bool {
        self.attribute(AId::Display) == Some("contents")
            && match self.tag_name() {
                Some(EId::G | EId::Switch | EId::Use | EId::Tspan | EId::TextPath) => true,
                Some(EId::Svg) => self.parent_element().is_some(),
                _ => false,
            }
    }

    pub(super) fn find_layout_attribute<T: FromValue<'a, 'input>>(&self, aid: AId) -> Option<T> {
        let node = self.ancestors().find(|node| !node.is_contents())?;
        node.attribute(aid).or_else(|| {
            node.parent_element()?
                .ancestors()
                .find(|parent| !parent.is_contents())?
                .attribute(aid)
        })
    }

    pub(super) fn is_visible_element(&self, opt: &crate::svg::usvg::Options) -> bool {
        (match self.attribute(AId::Display) {
            Some("none") => false,
            Some("contents") => self.is_contents(),
            _ => true,
        }) && (self.is_contents() || self.has_valid_transform(AId::Transform))
            && super::switch::is_condition_passed(*self, opt)
    }
}

pub(super) trait SvgColorExt {
    fn split_alpha(self) -> (Color, Opacity);
}

impl SvgColorExt for svgtypes::Color {
    fn split_alpha(self) -> (Color, Opacity) {
        (
            Color::new_rgb(self.red, self.green, self.blue),
            Opacity::new_u8(self.alpha),
        )
    }
}

#[cfg(test)]
thread_local! {
    static NODE_BUDGET: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
}

/// The most elements conversion converts, each as many times as references draw it.
fn node_budget() -> usize {
    #[cfg(test)]
    if let Some(budget) = NODE_BUDGET.with(std::cell::Cell::get) {
        return budget;
    }
    MAX_SVG_NODES
}

/// What `run` returns converting at most `budget` elements on this thread.
#[cfg(test)]
pub(crate) fn with_node_budget<T>(budget: usize, run: impl FnOnce() -> T) -> T {
    let outer = NODE_BUDGET.with(|limit| limit.replace(Some(budget)));
    let output = run();
    NODE_BUDGET.with(|limit| limit.set(outer));
    output
}

/// Converts an input `Document` into a `Tree`.
///
/// # Errors
///
/// - If `Document` doesn't have an SVG node - returns an empty tree.
/// - If `Document` doesn't have a valid size - returns `Error::InvalidSize`.
pub(crate) fn convert_doc(
    svg_doc: &svgtree::Document,
    opt: &Options,
    viewport: Option<Size>,
    image_resolver: Option<&dyn Fn(&str, &Options, Nesting) -> Option<ImageKind>>,
    font_provider: Option<&dyn FontProvider>,
) -> Result<Tree, Error> {
    let svg = svg_doc.root_element();
    let (size, restore_viewbox) = match viewport {
        Some(size) => (Ok(size), false),
        None => resolve_svg_size(&svg, opt, font_provider),
    };
    let size = size?;
    let view_box = ViewBox {
        rect: svg
            .parse_viewbox(svg.effective_zoom())
            .unwrap_or_else(|| size.to_non_zero_rect(0.0, 0.0)),
        aspect: svg.attribute(AId::PreserveAspectRatio).unwrap_or_default(),
    };

    let background_color = svg
        .attribute::<&str>(AId::BackgroundColor)
        .and_then(|s| svgtypes::Paint::from_str(s).ok())
        .and_then(|paint| match paint {
            svgtypes::Paint::Color(c) => Some(c),
            _ => None,
        });

    let mut tree = Tree {
        size,
        root: Group::empty(),
        linear_gradients: Vec::new(),
        radial_gradients: Vec::new(),
        sweep_gradients: Vec::new(),
        patterns: Vec::new(),
        clip_paths: Vec::new(),
        masks: Vec::new(),
        filters: Vec::new(),
        fontdb: opt.fontdb.clone(),
        limited: false,
        truncated: false,
        depth: 0,
        nesting: opt.nesting,
    };

    if !svg.is_visible_element(opt) {
        return Ok(tree);
    }

    let state = State {
        image_resolver,
        font_provider,
        ..State::new(opt, view_box.rect)
    };

    let mut cache = Cache::new(opt.fontdb.clone());
    cache.depth = opt.nesting.groups;
    cache.deepest = opt.nesting.groups;
    cache.references = opt.nesting.references;

    for node in svg_doc.descendants() {
        if let Some(tag) = node.tag_name() {
            if matches!(
                tag,
                EId::ClipPath
                    | EId::Filter
                    | EId::LinearGradient
                    | EId::Mask
                    | EId::Pattern
                    | EId::RadialGradient
                    | EId::Image
            ) {
                if !node.element_id().is_empty() {
                    cache.all_ids.insert(string_hash(node.element_id()));
                }
            }
        }
    }

    let root_ts = view_box.to_transform(tree.size());
    // Documents that references link follow the root element unrendered.
    if root_ts.is_identity() && background_color.is_none() {
        convert_element(svg, &state, &mut cache, &mut tree.root);
    } else {
        let mut g = Group::empty();

        if let Some(background_color) = background_color {
            if let Some(path) = background_path(background_color, view_box.rect.to_rect()) {
                g.children.push(Node::Path(Box::new(path)));
            }
        }

        g.transform = root_ts;
        g.abs_transform = root_ts;
        convert_element(svg, &state, &mut cache, &mut g);
        g.calculate_bounding_boxes();
        tree.root.children.push(Node::Group(Box::new(g)));
    }

    form_scenes(&mut tree.root);

    // Clear cache to make sure that all `Arc<T>` objects have a single strong reference.
    cache.clip_paths.clear();
    cache.masks.clear();
    cache.filters.clear();
    cache.paint.clear();

    super::paint_server::update_paint_servers(
        &mut tree.root,
        Transform::default(),
        None,
        None,
        &mut cache,
    );
    tree.collect_paint_servers();
    tree.root.isolate_stacking_context();
    tree.root.collect_clip_paths(&mut tree.clip_paths);
    tree.root.collect_masks(&mut tree.masks);
    tree.root.collect_filters(&mut tree.filters);
    tree.root.calculate_bounding_boxes();

    if let Some(error) = cache.style_error.take() {
        return Err(super::Error::Style(error));
    }
    if let Some(error) = state.length_error.borrow_mut().take() {
        return Err(super::Error::Style(error));
    }
    // The fontdb might have been mutated and we want to apply these changes to
    // the tree's fontdb.
    {
        tree.fontdb = cache.fontdb;
    }
    tree.limited = cache.limited;
    tree.truncated = cache.truncated;
    tree.depth = cache.deepest - opt.nesting.groups;

    if restore_viewbox {
        calculate_svg_bbox(&mut tree);
    }

    Ok(tree)
}

fn background_path(background_color: svgtypes::Color, area: Rect) -> Option<Path> {
    let path = PathBuilder::from_rect(area);

    let fill = Fill {
        paint: Paint::Color(Color::new_rgb(
            background_color.red,
            background_color.green,
            background_color.blue,
        )),
        opacity: NormalizedF32::new(background_color.alpha as f32 / 255.0)?,
        ..Default::default()
    };

    let mut path = Path::new_simple(Arc::new(path))?;
    path.fill = Some(fill);

    Some(path)
}

fn resolve_svg_size(
    svg: &SvgNode,
    opt: &Options,
    font_provider: Option<&dyn FontProvider>,
) -> (Result<Size, Error>, bool) {
    use crate::paint::LengthPercentage;
    let view_box = svg.parse_viewbox(svg.effective_zoom());
    let mut state = State::new(
        opt,
        view_box.unwrap_or_else(|| opt.default_size.to_non_zero_rect(0.0, 0.0)),
    );
    state.font_provider = font_provider;
    let dimension = |aid| units::computed_length(*svg, *svg, aid, Units::UserSpaceOnUse, &state);
    let width = dimension(AId::Width);
    let height = dimension(AId::Height);
    let restore_viewbox = view_box.is_none()
        && (!matches!(width, Some(LengthPercentage::Length(_)))
            || !matches!(height, Some(LengthPercentage::Length(_))));
    // `auto` is `100%` (SVG 2 §7.8), which a `calc-size()` can then calculate from.
    let used = |aid, size: Option<LengthPercentage>, basis| match size {
        Some(size) => size.resolve(basis),
        None => units::automatic_size(*svg, aid, basis, &state),
    };
    let size = Size::from_wh(
        used(AId::Width, width, state.view_box.width()),
        used(AId::Height, height, state.view_box.height()),
    );
    if let Some(error) = state.length_error.borrow_mut().take() {
        return (Err(Error::Style(error)), false);
    }
    (size.ok_or(Error::InvalidSize), restore_viewbox)
}

/// Calculates SVG's size and viewBox in case there were not set.
///
/// Simply iterates over all nodes and calculates a bounding box.
fn calculate_svg_bbox(tree: &mut Tree) {
    let bbox = tree.root.abs_bounding_box();
    if let Some(size) = Size::from_wh(bbox.right(), bbox.bottom()) {
        tree.size = size;
    }
}

#[inline(never)]
pub(crate) fn convert_children(
    parent_node: SvgNode,
    state: &State,
    cache: &mut Cache,
    parent: &mut Group,
) {
    for node in parent_node.children() {
        convert_element(node, state, cache, parent);
    }
}

#[inline(never)]
pub(crate) fn convert_element(node: SvgNode, state: &State, cache: &mut Cache, parent: &mut Group) {
    let tag_name = match node.tag_name() {
        Some(v) => v,
        None => return,
    };

    if !tag_name.is_graphic() && !matches!(tag_name, EId::G | EId::Switch | EId::Svg) {
        return;
    }

    if !node.is_visible_element(state.opt) {
        return;
    }

    // References, such as markers in the content of markers, can draw an element many times
    // over: past the node budget the rest of the content is left out.
    crate::work::count(crate::work::Work::Conversion, 1);
    if cache.measuring == 0 {
        if cache.converted >= node_budget() {
            cache.truncated = true;
            return;
        }
        cache.converted += 1;
    }

    if tag_name == EId::Use {
        super::use_node::convert(node, state, cache, parent);
        return;
    }

    if tag_name == EId::Switch {
        super::switch::convert(node, state, cache, parent);
        return;
    }

    if let Some(g) = convert_group(node, state, false, cache, parent, &|cache, g| {
        convert_element_impl(tag_name, node, state, cache, g);
    }) {
        parent.children.push(Node::Group(g));
    }
}

#[inline(never)]
fn convert_element_impl(
    tag_name: EId,
    node: SvgNode,
    state: &State,
    cache: &mut Cache,
    parent: &mut Group,
) {
    match tag_name {
        EId::Rect
        | EId::Circle
        | EId::Ellipse
        | EId::Line
        | EId::Polyline
        | EId::Polygon
        | EId::Path => {
            if let Some(path) = super::shapes::convert(node, state, super::shapes::Purpose::Paint) {
                convert_path(node, path, state, cache, parent);
            }
        }
        EId::Image => {
            super::image::convert(node, state, cache, parent);
        }
        EId::Text => {
            super::text::convert(node, state, cache, parent);
        }
        EId::Svg => {
            if node.is_contents() {
                convert_children(node, state, cache, parent);
            } else if node.parent_element().is_some() {
                super::use_node::convert_svg(node, state, cache, parent);
            } else {
                // Skip root `svg`.
                convert_children(node, state, cache, parent);
            }
        }
        EId::G => {
            convert_children(node, state, cache, parent);
        }
        _ => {}
    }
}

// `clipPath` can have only shape and `text` children.
//
// `line` doesn't impact rendering because stroke is always disabled
// for `clipPath` children.
#[inline(never)]
pub(crate) fn convert_clip_path_elements(
    clip_node: SvgNode,
    state: &State,
    cache: &mut Cache,
    parent: &mut Group,
) {
    for node in clip_node.children() {
        let tag_name = match node.tag_name() {
            Some(v) => v,
            None => continue,
        };

        if !tag_name.is_graphic() {
            continue;
        }

        if !node.is_visible_element(state.opt) {
            continue;
        }

        if tag_name == EId::Use {
            super::use_node::convert(node, state, cache, parent);
            continue;
        }

        if let Some(g) = convert_group(node, state, false, cache, parent, &|cache, g| {
            convert_clip_path_elements_impl(tag_name, node, state, cache, g);
        }) {
            parent.children.push(Node::Group(g));
        }
    }
}

#[inline(never)]
fn convert_clip_path_elements_impl(
    tag_name: EId,
    node: SvgNode,
    state: &State,
    cache: &mut Cache,
    parent: &mut Group,
) {
    match tag_name {
        EId::Rect | EId::Circle | EId::Ellipse | EId::Polyline | EId::Polygon | EId::Path => {
            if let Some(path) = super::shapes::convert(node, state, super::shapes::Purpose::Paint) {
                convert_path(node, path, state, cache, parent);
            }
        }
        EId::Text => {
            super::text::convert(node, state, cache, parent);
        }
        _ => {
            log::warn!("'{}' is no a valid 'clip-path' child.", tag_name);
        }
    }
}

#[derive(Clone, Copy, PartialEq, Debug)]
enum Isolation {
    Auto,
    Isolate,
}

impl Default for Isolation {
    fn default() -> Self {
        Self::Auto
    }
}

impl<'a, 'input: 'a> FromValue<'a, 'input> for Isolation {
    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
        match value {
            "auto" => Some(Isolation::Auto),
            "isolate" => Some(Isolation::Isolate),
            _ => None,
        }
    }
}

/// Whether a viewport's `overflow` clips its x and y axes (SVG 2 §3.11): `hidden`, `scroll`
/// and `clip` do, `visible` and `auto` do not; an absent value clips both.
pub(super) fn overflow_axes(node: SvgNode) -> [bool; 2] {
    let clips = |keyword: &str| !matches!(keyword, "visible" | "auto");
    let Some(value) = node.attribute::<&str>(AId::Overflow) else {
        return [true; 2];
    };
    let mut keywords = value.split_ascii_whitespace();
    let x = keywords.next().is_none_or(clips);
    let y = keywords.next().map_or(x, clips);
    [x, y]
}

/// The clip path of a viewport that `rect` bounds along the axes `axes` clips; along an
/// unclipped axis it spans `content`, the extent of the viewport's content, so that only
/// the other axis is clipped. `None` when neither axis clips.
pub(super) fn viewport_clip(
    cache: &mut Cache,
    rect: NonZeroRect,
    [x, y]: [bool; 2],
    content: NonZeroRect,
) -> Option<Arc<ClipPath>> {
    if !x && !y {
        return None;
    }
    let span = |clipped: bool, start: f32, end: f32, low: f32, high: f32| {
        if clipped {
            [start, end]
        } else {
            [start.min(low), end.max(high)]
        }
    };
    let [left, right] = span(
        x,
        rect.left(),
        rect.right(),
        content.left(),
        content.right(),
    );
    let [top, bottom] = span(
        y,
        rect.top(),
        rect.bottom(),
        content.top(),
        content.bottom(),
    );
    let mut clip_path = ClipPath::empty(cache.gen_clip_path_id());
    let mut path = Path::new_simple(Arc::new(PathBuilder::from_rect(Rect::from_ltrb(
        left, top, right, bottom,
    )?)))?;
    path.fill = Some(Fill::default());
    clip_path.root.children.push(Node::Path(Box::new(path)));
    Some(Arc::new(clip_path))
}

const NON_SCALING_STROKE: &str = "non-scaling-stroke";
const NON_SCALING_SIZE: &str = "non-scaling-size";
const NON_ROTATION: &str = "non-rotation";
const FIXED_POSITION: &str = "fixed-position";

/// Whether the element's `vector-effect` strokes it in the host coordinate space (SVG 2 §13.6):
/// not within a 3D rendering context (CSS Transforms 2 §11).
pub(super) fn non_scaling_stroke(node: SvgNode, state: &State) -> bool {
    node.attribute::<&str>(AId::VectorEffect) == Some(NON_SCALING_STROKE)
        && !node
            .ancestors()
            .skip(1)
            .any(|ancestor| super::motion::preserves_3d(ancestor, state))
}

/// SVG 2 §8.13.1: the transform giving the element whose own transform is `own` the user
/// coordinate system that its `vector-effect` constrains in the host coordinate space, the
/// canvas, given its parent's absolute transform. A singular CTM leaves `non-scaling-size`
/// without effect.
fn vector_effect(node: SvgNode, parent: Transform, own: Transform) -> Transform {
    let ctm = parent.pre_concat(own);
    let [a, b, c, d] = [ctm.sx, ctm.ky, ctm.kx, ctm.sy];
    let scale = (a * d - b * c).abs().sqrt();
    let constrained = match node.attribute::<&str>(AId::VectorEffect) {
        Some(NON_SCALING_SIZE) if scale > 0.0 => {
            Transform::from_row(a / scale, b / scale, c / scale, d / scale, ctm.tx, ctm.ty)
        }
        Some(NON_ROTATION) => Transform::from_row(scale, 0.0, 0.0, scale, ctm.tx, ctm.ty),
        // The element's own translation places its origin in the host space.
        Some(FIXED_POSITION) => Transform::from_row(a, b, c, d, own.tx, own.ty),
        _ => return own,
    };
    parent
        .invert()
        .map_or(own, |to_parent| to_parent.pre_concat(constrained))
}

/// Which content of an element a measurement converts.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub(super) enum Measured {
    /// The element's children.
    Children,
    /// The instance a `use` element places.
    Instance,
}

/// The content of an element, which `collect` converts, measured for the reference box its
/// transform or perspective takes (CSS Transforms 1 §3) before it converts. The content
/// converts once to measure it and once more where it renders, and each element's is measured
/// once: content measured inside a measurement is used as converted, as only its extent
/// matters there, so nested measured elements convert in linear rather than exponential time.
pub(super) struct Content<'f> {
    key: (svgtree::NodeKey, Measured),
    collect: &'f dyn Fn(&mut Cache, &mut Group),
    measured: Option<Group>,
}

impl<'f> Content<'f> {
    pub(super) fn new(
        node: SvgNode,
        measured: Measured,
        collect: &'f dyn Fn(&mut Cache, &mut Group),
    ) -> Self {
        Self {
            key: (node.key(), measured),
            collect,
            measured: None,
        }
    }

    /// The fill and stroke bounding boxes of the content, converted untransformed in the
    /// space of `parent`.
    pub(super) fn boxes(&mut self, cache: &mut Cache, parent: &Group) -> [Rect; 2] {
        if let Some(group) = &self.measured {
            return [group.bounding_box, group.stroke_bounding_box];
        }
        if let Some(boxes) = cache.measured.get(&self.key) {
            return *boxes;
        }
        let mut probe = Group::empty();
        probe.abs_transform = parent.abs_transform;
        cache.measuring += 1;
        (self.collect)(cache, &mut probe);
        cache.measuring -= 1;
        probe.calculate_bounding_boxes();
        let boxes = [probe.bounding_box, probe.stroke_bounding_box];
        cache.measured.insert(self.key, boxes);
        self.measured = Some(probe);
        boxes
    }

    /// The content this element measured, where it is used as converted: inside a measurement.
    pub(super) fn reused(&mut self, cache: &Cache) -> Option<Group> {
        self.measured.take().filter(|_| cache.measuring > 0)
    }

    /// Converts the content into `group`.
    pub(super) fn convert(mut self, cache: &mut Cache, group: &mut Group) {
        match self.reused(cache) {
            Some(measured) => group.children.extend(measured.children),
            None => (self.collect)(cache, group),
        }
    }
}

/// The placement of an element whose content converts untransformed: CSS transform
/// properties, or the `transform` attribute about an origin that, per CSS Transforms 1 §2,
/// lies in the element's object or stroke bounding box when `transform-box` selects one,
/// measured before the transform applies.
pub(super) fn element_transform(
    node: SvgNode,
    state: &State,
    cache: &mut Cache,
    parent: &Group,
    content: &mut Content,
) -> Placement {
    let own = match super::motion::transform(node, state, cache, parent, content) {
        Some(Placement::Affine(own)) => own,
        // CSS Transforms 2 §11: no vector effect applies in 3D.
        Some(placement) => return placement,
        None => match node.attribute::<&str>(AId::TransformBox) {
            Some(reference @ (FILL_BOX | STROKE_BOX)) => {
                let [fill, stroke] = content.boxes(cache, parent);
                let bounds = if reference == FILL_BOX { fill } else { stroke };
                node.resolve_transform_in(AId::Transform, state, Some(bounds))
            }
            _ => node.resolve_transform(AId::Transform, state),
        },
    };
    Placement::Affine(vector_effect(node, parent.abs_transform, own))
}

/// Records the perspective `node` gives its children (CSS Transforms 2 §8), measuring its
/// content where its reference box needs it.
pub(super) fn record_perspective(
    node: SvgNode,
    state: &State,
    cache: &mut Cache,
    parent: &Group,
    content: &mut Content,
) {
    let key = node.key();
    // Content measured for the reference box lies flat, without the perspective it sets up.
    cache.perspectives.remove(&key);
    if let Some(perspective) = super::motion::perspective(node, state, cache, parent, content) {
        cache.perspectives.insert(key, perspective);
    }
}

/// The deepest the groups of the tree and of the resources it references nest as they convert:
/// a tree within its depth limit converts whole, nested `svg` elements converting as two
/// groups each, but references can nest content without bound. Rendering recurses over the
/// converted groups too.
pub(crate) const MAX_CONVERSION_DEPTH: usize = 2 * (MAX_SVG_DEPTH + 1);
/// The most resources that convert each referenced from the content of the last. A resource
/// converts in several large frames before its content does.
pub(crate) const MAX_REFERENCE_DEPTH: usize = 8;

/// The group `node` establishes around the content `collect_children` converts, or `None`
/// where its content joins `parent` directly, it is not rendered, or it nests past
/// `MAX_CONVERSION_DEPTH`. Recursion over the tree passes through here, so the group's own
/// conversion happens in functions of its own whose frames leave the stack before its content
/// converts.
pub(crate) fn convert_group(
    node: SvgNode,
    state: &State,
    force: bool,
    cache: &mut Cache,
    parent: &mut Group,
    collect_children: &dyn Fn(&mut Cache, &mut Group),
) -> Option<Box<Group>> {
    if cache.depth >= MAX_CONVERSION_DEPTH {
        cache.limited = true;
        return None;
    }
    cache.depth += 1;
    cache.deepest = cache.deepest.max(cache.depth);
    let group = nested_group(node, state, force, cache, parent, collect_children);
    cache.depth -= 1;
    group
}

/// `convert_group` within the conversion depth.
fn nested_group(
    node: SvgNode,
    state: &State,
    force: bool,
    cache: &mut Cache,
    parent: &mut Group,
    collect_children: &dyn Fn(&mut Cache, &mut Group),
) -> Option<Box<Group>> {
    if node.attribute(AId::Display) == Some("contents") {
        if !node.is_contents() {
            return None;
        }
        let mut group = Box::new(Group::empty());
        group.abs_transform = parent.abs_transform;
        collect_children(cache, &mut group);
        group.calculate_bounding_boxes();
        return (!group.children.is_empty()).then_some(group);
    }
    let mut content = Content::new(node, Measured::Children, collect_children);
    let mut g = open_group(node, state, cache, parent, &mut content)?;
    content.convert(cache, &mut g);
    close_group(node, state, force, cache, parent, g)
}

/// The group `node` establishes, before its content converts.
#[inline(never)]
fn open_group(
    node: SvgNode,
    state: &State,
    cache: &mut Cache,
    parent: &Group,
    content: &mut Content,
) -> Option<Box<Group>> {
    // A `clipPath` child cannot have an opacity.
    let opacity = if state.parent_clip_path.is_none() {
        node.attribute::<Opacity>(AId::Opacity)
            .unwrap_or(Opacity::ONE)
    } else {
        Opacity::ONE
    };

    let (transform, matrix) = match element_transform(node, state, cache, parent, content) {
        Placement::Affine(transform) => (transform, None),
        Placement::Matrix(matrix) => (Transform::default(), Some(matrix)),
        Placement::Hidden => return None,
    };
    record_perspective(node, state, cache, parent, content);
    let preserves_3d = super::motion::preserves_3d(node, state);
    // CSS Masking 1 §6.1: a clipping path's children contribute geometry only.
    let in_clip_path = state.parent_clip_path.is_some();
    let blend_mode: BlendMode = if in_clip_path {
        BlendMode::Normal
    } else {
        node.attribute(AId::MixBlendMode).unwrap_or_default()
    };
    let linear_light =
        !in_clip_path && node.find_attribute::<&str>(AId::ColorInterpolation) == Some(LINEAR_RGB);
    let isolation: Isolation = node.attribute(AId::Isolation).unwrap_or_default();
    let isolate = isolation == Isolation::Isolate;

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

    let abs_transform = parent.abs_transform.pre_concat(transform);
    let dummy = Rect::from_xywh(0.0, 0.0, 0.0, 0.0).unwrap();
    Some(Box::new(Group {
        id,
        transform,
        matrix,
        scene: false,
        preserves_3d,
        backface_hidden: super::motion::backface_hidden(node),
        abs_transform,
        opacity,
        blend_mode,
        isolate,
        stacking_context: false,
        linear_light,
        clip_path: None,
        mask: None,
        layer_mask: None,
        filters: Vec::new(),
        is_context_element: false,
        bounding_box: dummy,
        abs_bounding_box: dummy,
        stroke_bounding_box: dummy,
        abs_stroke_bounding_box: dummy,
        layer_bounding_box: NonZeroRect::from_xywh(0.0, 0.0, 1.0, 1.0).unwrap(),
        abs_layer_bounding_box: NonZeroRect::from_xywh(0.0, 0.0, 1.0, 1.0).unwrap(),
        children: Vec::new(),
    }))
}

fn is_g_or_use(node: SvgNode) -> bool {
    matches!(node.tag_name(), Some(EId::G) | Some(EId::Use))
}

/// The group `open_group` opened for `node`, with its content converted: with its clip path,
/// mask and filters, or `None` where its content joins `parent` directly or it is not rendered.
#[inline(never)]
fn close_group(
    node: SvgNode,
    state: &State,
    force: bool,
    cache: &mut Cache,
    parent: &mut Group,
    mut g: Box<Group>,
) -> Option<Box<Group>> {
    // We need to know group's bounding box before converting
    // clipPaths, masks and filters.
    let object_bbox = g.calculate_object_bbox();

    // `mask` and `filter` cannot be set on `clipPath` children.
    // But `clip-path` can.

    let mut clip_path = None;
    if let Some(link) = node.attribute::<SvgNode>(AId::ClipPath) {
        clip_path = super::clippath::convert(link, node, state, object_bbox, cache);
        if clip_path.is_none() {
            return None;
        }
    } else if let Some(shape) = node
        .attribute::<&str>(AId::ClipPath)
        .and_then(|value| super::basic_shape::parse(value, node, state))
    {
        g.calculate_bounding_boxes();
        let boxes = reference_boxes(&g, state)?;
        clip_path = Some(super::basic_shape::convert(&shape, &boxes, state, cache)?);
    }

    let mut mask = None;
    let mut layer_mask = None;
    if state.parent_clip_path.is_none() {
        if let Some(link) = node.attribute::<SvgNode>(AId::Mask) {
            mask = super::mask::convert(link, node, state, object_bbox, cache);
            if mask.is_none() {
                return None;
            }
        } else if let Some(masks) = node
            .attribute::<&str>(AId::Mask)
            .and_then(crate::svg::layer_mask_index)
            .and_then(|index| state.opt.styling.layer_masks.get(index))
        {
            g.calculate_bounding_boxes();
            layer_mask = Some(Arc::new(LayerMask {
                masks: masks.clone(),
                boxes: reference_boxes(&g, state)?,
            }));
        }
    }

    let filters = {
        let mut filters = Vec::new();
        if state.parent_clip_path.is_none() {
            if node.attribute(AId::Filter) == Some("none") {
                // Do nothing.
            } else if node.has_attribute(AId::Filter) {
                if let Ok(f) = super::filter::convert(node, state, object_bbox, cache) {
                    filters = f;
                } else {
                    // A filter that not a link or a filter with a link to a non existing element.
                    //
                    // Unlike `clip-path` and `mask`, when a `filter` link is invalid
                    // then the whole element should be ignored.
                    //
                    // This is kinda an undefined behaviour.
                    // In most cases, Chrome, Firefox and rsvg will ignore such elements,
                    // but in some cases Chrome allows it. Not sure why.
                    // Inkscape (0.92) simply ignores such attributes, rendering element as is.
                    // Batik (1.12) crashes.
                    //
                    // Test file: e-filter-051.svg
                    return None;
                }
            }
        }

        filters
    };

    let required = g.opacity.get().approx_ne_ulps(&1.0, 4)
        || clip_path.is_some()
        || mask.is_some()
        || layer_mask.is_some()
        || !filters.is_empty()
        || !g.transform.is_identity()
        || g.matrix.is_some()
        || g.preserves_3d
        || g.blend_mode != BlendMode::Normal
        || g.isolate
        // The group's own children composite in its colour space.
        || g.linear_light != parent.linear_light
        || is_g_or_use(node)
        || force;

    if !required {
        parent.children.append(&mut g.children);
        return None;
    }

    g.clip_path = clip_path;
    g.mask = mask;
    g.layer_mask = layer_mask;
    g.filters = filters;
    if node.tag_name() == Some(EId::Use) {
        g.isolate_stacking_context();
    }

    // Must be called after we set Group::filters
    g.calculate_bounding_boxes();

    Some(g)
}

/// Replaces each group in `group`'s subtree that establishes a 3D rendering context with the
/// context's scene (CSS Transforms 2 §4.1.2); whether any formed.
fn form_scenes(group: &mut Group) -> bool {
    let mut formed = false;
    let extends = group.preserves_3d;
    for child in &mut group.children {
        if let Node::Group(child) = child {
            formed |= form_scenes(child);
            if child.preserves_3d && !extends {
                **child = scene(std::mem::replace(&mut **child, Group::empty()));
                formed = true;
            }
        }
    }
    if formed {
        group.calculate_bounding_boxes();
    }
    formed
}

/// CSS Transforms 2 §4.1.2: the 3D rendering context that `root` establishes, as a group in
/// its parent's space whose children are the context's planes in painting order: `root`'s
/// and those of the 3D transformed elements participating in it, each holding its element's
/// content outside other planes and placed by its accumulated 3D transformation matrix.
fn scene(root: Group) -> Group {
    let mut planes = Vec::new();
    let matrix = root.matrix.unwrap_or(crate::style::transform::IDENTITY);
    let abs_transform = root.abs_transform;
    hoist(root, matrix, &mut planes);
    Group {
        scene: true,
        abs_transform,
        children: planes
            .into_iter()
            .map(|plane| Node::Group(Box::new(plane)))
            .collect(),
        ..Group::empty()
    }
}

/// Adds the plane of `element`, which extends the context, at `accumulated` to `planes`,
/// before the planes of the elements participating through it.
fn hoist(
    mut element: Group,
    accumulated: crate::style::transform::Matrix3d,
    planes: &mut Vec<Group>,
) {
    let index = planes.len();
    planes.push(Group::empty());
    let mut own = Vec::new();
    for child in std::mem::take(&mut element.children) {
        match child {
            Node::Group(group) if group.matrix.is_some() => {
                let placed = crate::style::transform::multiply(
                    &accumulated,
                    &group.matrix.unwrap_or(crate::style::transform::IDENTITY),
                );
                if group.preserves_3d {
                    hoist(*group, placed, planes);
                } else {
                    planes.push(plane(*group, placed));
                }
            }
            other => own.push(other),
        }
    }
    element.children = own;
    planes[index] = plane(element, accumulated);
}

/// `group` as a plane at `accumulated`, empty where it turns a hidden back face to the
/// viewer (§10).
fn plane(mut group: Group, accumulated: crate::style::transform::Matrix3d) -> Group {
    if group.backface_hidden && crate::style::transform::faces_away(&accumulated) {
        group.children.clear();
    }
    group.transform = Transform::default();
    group.matrix = Some(accumulated);
    group.calculate_bounding_boxes();
    group
}

/// The fill, stroke and view boxes of the group `g`, whose bounding boxes are calculated, in
/// points; `None` without a nearest viewport. CSS Masking 1 §6.1: `view-box` places the
/// nearest viewport's viewBox at the origin.
fn reference_boxes(g: &Group, state: &State) -> Option<crate::paint::SvgBoxes> {
    let view = state.view_box;
    let points = |rect: Rect| crate::paint::Rect {
        x: rect.x() * crate::paint::POINTS_PER_PIXEL,
        y: rect.y() * crate::paint::POINTS_PER_PIXEL,
        width: rect.width() * crate::paint::POINTS_PER_PIXEL,
        height: rect.height() * crate::paint::POINTS_PER_PIXEL,
    };
    Some(crate::paint::SvgBoxes {
        fill: points(g.bounding_box),
        stroke: points(g.stroke_bounding_box),
        view: points(Rect::from_xywh(0.0, 0.0, view.width(), view.height())?),
    })
}

fn convert_path(
    node: SvgNode,
    tiny_skia_path: Arc<tiny_skia_path::Path>,
    state: &State,
    cache: &mut Cache,
    parent: &mut Group,
) {
    debug_assert!(tiny_skia_path.len() >= 2);
    if tiny_skia_path.len() < 2 {
        return;
    }

    let has_bbox = tiny_skia_path.bounds().width() > 0.0 && tiny_skia_path.bounds().height() > 0.0;
    let mut fill = super::style::resolve_fill(node, has_bbox, state, cache);
    let mut stroke = super::style::resolve_stroke(node, has_bbox, state, cache);
    let visibility: Visibility = node.find_attribute(AId::Visibility).unwrap_or_default();
    let mut visible = visibility == Visibility::Visible;
    let rendering_mode: ShapeRendering = node
        .find_attribute(AId::ShapeRendering)
        .unwrap_or(state.opt.shape_rendering);

    // TODO: handle `markers` before `stroke`
    let raw_paint_order: svgtypes::PaintOrder =
        node.find_attribute(AId::PaintOrder).unwrap_or_default();
    let paint_order = svg_paint_order_to_usvg(raw_paint_order);
    let path_transform = parent.abs_transform;

    // If a path doesn't have a fill or a stroke then it's invisible.
    // By setting `visibility` to `hidden` we are disabling rendering of this path.
    if fill.is_none() && stroke.is_none() {
        visible = false;
    }

    if let Some(fill) = fill.as_mut() {
        if let Some(ContextElement::PathNode(context_transform, context_bbox)) =
            fill.context_element
        {
            process_paint(
                &mut fill.paint,
                true,
                context_transform,
                context_bbox.map(|r| r.to_rect()),
                path_transform,
                tiny_skia_path.bounds(),
                cache,
            );
            fill.context_element = None;
        }
    }

    if let Some(stroke) = stroke.as_mut() {
        if let Some(ContextElement::PathNode(context_transform, context_bbox)) =
            stroke.context_element
        {
            process_paint(
                &mut stroke.paint,
                true,
                context_transform,
                context_bbox.map(|r| r.to_rect()),
                path_transform,
                tiny_skia_path.bounds(),
                cache,
            );
            stroke.context_element = None;
        }
    }

    let mut marker = None;
    if marker::is_valid(node) && visibility == Visibility::Visible {
        let mut marker_group = Group {
            abs_transform: parent.abs_transform,
            ..Group::empty()
        };

        let mut marker_state = state.clone();

        let bbox = tiny_skia_path
            .compute_tight_bounds()
            .and_then(|r| r.to_non_zero_rect());

        let fill = fill.clone().map(|mut f| {
            f.context_element = Some(ContextElement::PathNode(path_transform, bbox));
            f
        });

        let stroke = stroke.clone().map(|mut s| {
            s.context_element = Some(ContextElement::PathNode(path_transform, bbox));
            s
        });

        marker_state.context_element = Some((fill, stroke));

        marker::convert(
            node,
            &tiny_skia_path,
            &marker_state,
            cache,
            &mut marker_group,
        );
        marker_group.calculate_bounding_boxes();
        marker = Some(marker_group);
    }

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

    let path = Path::new(
        id,
        visible,
        fill,
        stroke,
        paint_order,
        rendering_mode,
        tiny_skia_path,
        path_transform,
    );

    let path = match path {
        Some(path) if non_scaling_stroke(node, state) => path.with_non_scaling_stroke(),
        path => path,
    };
    let Some(path) = path else {
        return;
    };

    match (raw_paint_order.order, marker) {
        ([PaintOrderKind::Markers, _, _], Some(markers_node)) => {
            parent.children.push(Node::Group(Box::new(markers_node)));
            parent.children.push(Node::Path(Box::new(path.clone())));
        }
        ([first, PaintOrderKind::Markers, last], Some(markers_node)) => {
            append_single_paint_path(first, &path, parent);
            parent.children.push(Node::Group(Box::new(markers_node)));
            append_single_paint_path(last, &path, parent);
        }
        ([_, _, PaintOrderKind::Markers], Some(markers_node)) => {
            parent.children.push(Node::Path(Box::new(path.clone())));
            parent.children.push(Node::Group(Box::new(markers_node)));
        }
        _ => parent.children.push(Node::Path(Box::new(path.clone()))),
    }
}

fn append_single_paint_path(paint_order_kind: PaintOrderKind, path: &Path, parent: &mut Group) {
    match paint_order_kind {
        PaintOrderKind::Fill => {
            if path.fill.is_some() {
                let mut fill_path = path.clone();
                fill_path.stroke = None;
                fill_path.id = String::new();
                parent.children.push(Node::Path(Box::new(fill_path)));
            }
        }
        PaintOrderKind::Stroke => {
            if path.stroke.is_some() {
                let mut stroke_path = path.clone();
                stroke_path.fill = None;
                stroke_path.id = String::new();
                parent.children.push(Node::Path(Box::new(stroke_path)));
            }
        }
        _ => {}
    }
}

pub(super) fn svg_paint_order_to_usvg(order: svgtypes::PaintOrder) -> PaintOrder {
    match (order.order[0], order.order[1]) {
        (PaintOrderKind::Stroke, _) => PaintOrder::StrokeAndFill,
        (PaintOrderKind::Markers, PaintOrderKind::Stroke) => PaintOrder::StrokeAndFill,
        _ => PaintOrder::FillAndStroke,
    }
}

impl SvgNode<'_, '_> {
    pub(crate) fn resolve_transform(&self, transform_aid: AId, state: &State) -> Transform {
        self.resolve_transform_in(transform_aid, state, None)
    }

    /// The transform about `transform-origin`, which `reference` positions when given and the
    /// viewport otherwise.
    pub(crate) fn resolve_transform_in(
        &self,
        transform_aid: AId,
        state: &State,
        reference: Option<Rect>,
    ) -> Transform {
        if transform_aid == AId::Transform && self.is_contents() {
            return Transform::default();
        }
        let mut transform: Transform = self.attribute(transform_aid).unwrap_or_default();
        let transform_origin: Option<TransformOrigin> = self.attribute(AId::TransformOrigin);

        if let Some(transform_origin) = transform_origin {
            let offset = |length: Length, start: f32, size: f32, aid| match reference {
                Some(_) if length.unit == Unit::Percent => {
                    start + size * length.number as f32 / PERCENT
                }
                Some(_) => start + convert_length(length, *self, aid, Units::UserSpaceOnUse, state),
                None => convert_length(length, *self, aid, Units::UserSpaceOnUse, state),
            };
            let (x, y, width, height) = reference.map_or((0.0, 0.0, 0.0, 0.0), |bounds| {
                (bounds.x(), bounds.y(), bounds.width(), bounds.height())
            });
            let dx = offset(transform_origin.x_offset, x, width, AId::Width);
            let dy = offset(transform_origin.y_offset, y, height, AId::Height);
            transform = Transform::default()
                .pre_translate(dx, dy)
                .pre_concat(transform)
                .pre_translate(-dx, -dy);
        }

        transform
    }
}