nsh-core 0.6.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
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
//! SVG images for the native backends (feature `svg`), and SVGs as
//! canvas drawings ([`drawing`], what `element::svg` shows).
//!
//! The platforms' image decoders (ImageIO, `BitmapFactory`, WIC, GDK) do not
//! read SVG, so every native backend hands sniffed SVG bytes to this module
//! and draws the premultiplied RGBA [`Raster`] it gets back through its usual
//! bitmap path (tint, blur and `objectFit` included). One renderer, resvg,
//! draws them on every platform, so an SVG looks the same everywhere. The web
//! runtime does not enable the feature: the browser draws SVG itself.
//!
//! An SVG is a self-contained picture here: usvg gets no resources directory,
//! and an `<image>` resolver that reads inline raster `data:` URIs only, so
//! `href`s to files, URLs or nested SVG documents never load. Text is drawn
//! with the system fonts the platform's text engine uses, and inline raster
//! images are decoded: a canvas may draw an SVG generated by the app (a mask,
//! an eraser or a blend group rasterized as one picture), which carries its
//! own text and images. Remote SVGs come through each backend's own fetch,
//! with its capability checks.
//!
//! An SVG from the network is untrusted input, so what drawing one takes is
//! bounded: a document of at most [`MAX_BYTES`] (a `.svgz` once inflated),
//! text of at most [`MAX_TEXT_CHARS`] characters as `<use>`, `<tref>` and
//! resource references expand it, a raster of at most
//! [`MAX_SIDE`] pixels a side and [`MAX_PIXELS`] in all, and layers (resvg
//! draws every group with opacity, a mask, a clip path, filters or a blend
//! mode into a pixmap of its own, and nested ones coexist) of at most
//! [`MAX_LAYER_PIXELS`] at once by a conservative estimate made before
//! drawing (`layers.rs`). The text limit applies before usvg lays the text
//! out, which it does while parsing; the system font database is scanned only
//! when a document lays out text. A panic in the parser or the renderer is an
//! [`Error`] too: the backends call these functions where an unwinding panic
//! would abort the process (GCD blocks, JNI functions).
//!
//! Sizes are in points: a CSS pixel of the SVG (its root `width` / `height`,
//! else its `viewBox`) is one point. Icons and logos carry a `viewBox`; one
//! without a size and a `viewBox` reaches as far as what it draws.

use std::{
    borrow::Cow,
    collections::{HashMap, HashSet},
    fmt,
    io::Read,
    panic,
};

use resvg::{
    tiny_skia,
    usvg::{self, roxmltree},
};

use crate::geometry::{DevicePixels, Points, Size};

mod drawing;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) mod drawings;
mod layers;
mod sniff;
#[cfg(test)]
mod tests;

pub use self::drawing::drawing;
use self::sniff::sniff_text;

/// How much of a compressed SVG (`.svgz`) [`sniff`] inflates to find the
/// root element.
const SNIFF_INFLATED: u64 = 4096;

/// The largest SVG document read, in bytes (a `.svgz` once inflated):
/// larger ones are refused rather than filling memory.
pub const MAX_BYTES: usize = 16 << 20;

/// The most characters of `<text>` one SVG may hold. usvg lays out and
/// outlines every glyph while parsing, before the layer estimate runs, and
/// each glyph costs most of a kilobyte and time quadratic in the text
/// length; a document over this is refused rather than stalling a decode
/// thread or exhausting memory.
pub const MAX_TEXT_CHARS: usize = 64 * 1024;

/// The deepest nesting usvg parses: its `parse_xml_node` refuses a document
/// past this depth, and the text walk stops at the same depth. A resource
/// edge counts four levels: a chain of clip paths or masks is flat XML but
/// recurses through several of the walk's frames, so it must stop sooner.
const MAX_DEPTH: u32 = 1024;

/// The xlink namespace: `<use>` and `<tref>` take `xlink:href` over `href`.
const XLINK_NS: &str = "http://www.w3.org/1999/xlink";

/// The longest side of a raster, in pixels: a sanity limit, as large as
/// the textures GPUs take.
pub const MAX_SIDE: u32 = 8192;

/// The most pixels of a raster (64 MiB of RGBA): a full-screen image on a
/// 5K display (14.7 million pixels) fits. A raster asked for larger is drawn
/// smaller, with its aspect ratio.
pub const MAX_PIXELS: u32 = 1 << 24;

/// The most pixels of layers drawing an SVG may hold at once beside its
/// raster, four rasters' worth (256 MiB), by the estimate of `layers.rs`:
/// an SVG over it is refused.
pub const MAX_LAYER_PIXELS: u32 = 4 * MAX_PIXELS;

/// How many pixels per point backends that draw one raster at every size
/// (Windows, Linux, GPUI) render an SVG at, so it stays sharp when shown
/// larger than its intrinsic size or on high-density screens.
pub const OVERSAMPLE: u32 = 4;

/// The longest side of an oversampled raster ([`rasterize_oversampled`]),
/// in pixels.
pub const MAX_OVERSAMPLED_SIDE: u32 = 2048;

/// A drawn SVG: premultiplied RGBA, row by row without padding.
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct Raster {
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
    /// `width * height * 4` bytes of premultiplied RGBA.
    pub pixels: Vec<u8>,
    /// The SVG's intrinsic size (what [`size`] returns).
    pub size: Size<Points>,
}

/// Why an SVG could not be read or drawn.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// The bytes are no SVG document: not UTF-8, malformed XML or gzip
    /// data, or a root that is not `<svg>`; what the parser said.
    Invalid(String),
    /// The document is larger than [`MAX_BYTES`] (a `.svgz` once inflated).
    TooLarge,
    /// The document holds more than [`MAX_TEXT_CHARS`] characters of text.
    TooMuchText,
    /// The SVG has no area: a width or height of zero or less, or neither a
    /// size, a `viewBox` nor anything drawn to measure it by.
    NoArea,
    /// The raster asked for has no pixels (a size or scale of zero).
    NoPixels,
    /// Drawing it would hold more than [`MAX_LAYER_PIXELS`] pixels of
    /// layers at once: about `pixels`.
    OverBudget {
        /// The estimate, in pixels.
        pixels: u64,
    },
    /// Walking or drawing it would visit more nodes than a document may
    /// hold, or nest deeper than 1024 elements: a `<use>` target counts at
    /// each use, and shared patterns, masks and clip paths count each time
    /// they are drawn.
    TooManyNodes,
    /// The parser or the renderer panicked on it.
    Panicked,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Invalid(reason) => write!(f, "invalid SVG: {reason}"),
            Error::TooLarge => write!(
                f,
                "the SVG document is larger than {} MiB (a .svgz once inflated)",
                MAX_BYTES >> 20
            ),
            Error::TooMuchText => write!(
                f,
                "the SVG holds more than {MAX_TEXT_CHARS} characters of text"
            ),
            Error::NoArea => write!(
                f,
                "the SVG has no area: a zero width or height, or nothing to size it by"
            ),
            Error::NoPixels => write!(f, "an SVG raster of no pixels was asked for"),
            Error::OverBudget { pixels } => write!(
                f,
                "drawing the SVG would hold about {pixels} pixels of layers at once, over the \
                 {MAX_LAYER_PIXELS} allowed"
            ),
            Error::TooManyNodes => write!(
                f,
                "walking or drawing the SVG would visit more than {} nodes, or nest more than \
                 {MAX_DEPTH} elements deep",
                layers::MAX_VISITS
            ),
            Error::Panicked => write!(f, "the SVG renderer panicked on this document"),
        }
    }
}

impl std::error::Error for Error {}

/// Whether `bytes` are an SVG image: the root element is `<svg`, after an
/// optional byte order mark, XML declaration, comments and doctype, or the
/// same compressed with gzip (`.svgz`). File names and MIME types are never
/// trusted; this looks at the bytes.
pub fn sniff(bytes: &[u8]) -> bool {
    if bytes.starts_with(&[0x1f, 0x8b]) {
        let mut head = Vec::new();
        // A truncated read still holds the start of the document.
        let _ = flate2::read::GzDecoder::new(bytes)
            .take(SNIFF_INFLATED)
            .read_to_end(&mut head);
        return sniff_text(&head);
    }
    sniff_text(bytes)
}

/// Runs `f`, turning a panic into [`Error::Panicked`].
fn guarded<T>(f: impl FnOnce() -> Result<T, Error>) -> Result<T, Error> {
    // Nothing `f` touches outlives it, so a half-done parse or drawing is
    // never seen again.
    panic::catch_unwind(panic::AssertUnwindSafe(f)).unwrap_or(Err(Error::Panicked))
}

/// The USVGs font database, loaded once: text in an SVG drawn by a canvas
/// (an app-generated mask or effect) uses the system fonts the rest of the
/// app measures with.
static SYSTEM_FONTS: std::sync::LazyLock<std::sync::Arc<usvg::fontdb::Database>> =
    std::sync::LazyLock::new(|| {
        use usvg::fontdb::{Family, Query, Stretch, Style, Weight};

        let mut fontdb = usvg::fontdb::Database::new();
        fontdb.load_system_fonts();
        // fontdb has no system path for these platforms (its Linux branch
        // does not build on Android or iOS).
        #[cfg(target_os = "android")]
        fontdb.load_fonts_dir("/system/fonts");
        #[cfg(target_os = "ios")]
        {
            fontdb.load_fonts_dir("/System/Library/Fonts");
            fontdb.load_fonts_dir("/Library/Fonts");
        }
        // A document that names no family (or a generic one) asks usvg for
        // `Serif`, and fontdb names that generic after a desktop font the
        // system may not have ("Times New Roman"): Android has neither it
        // nor Arial. Point a generic family that does not resolve at a text
        // family the system does have, so such text draws instead of
        // disappearing.
        if let Some(family) = TEXT_FAMILIES.iter().copied().find(|family| {
            fontdb
                .query(&Query {
                    families: &[Family::Name(family)],
                    weight: Weight::NORMAL,
                    stretch: Stretch::Normal,
                    style: Style::Normal,
                })
                .is_some()
        }) {
            let missing = |db: &usvg::fontdb::Database, generic| {
                db.query(&Query {
                    families: &[generic],
                    weight: Weight::NORMAL,
                    stretch: Stretch::Normal,
                    style: Style::Normal,
                })
                .is_none()
            };
            if missing(&fontdb, Family::Serif) {
                fontdb.set_serif_family(family);
            }
            if missing(&fontdb, Family::SansSerif) {
                fontdb.set_sans_serif_family(family);
            }
            if missing(&fontdb, Family::Monospace) {
                fontdb.set_monospace_family(family);
            }
            if missing(&fontdb, Family::Cursive) {
                fontdb.set_cursive_family(family);
            }
            if missing(&fontdb, Family::Fantasy) {
                fontdb.set_fantasy_family(family);
            }
        }
        std::sync::Arc::new(fontdb)
    });

/// Families a Windows, macOS, Linux, Android or iOS system has for text, in
/// the order a document that names none prefers them. The first one the
/// system has stands in for a generic family fontdb names but lacks.
const TEXT_FAMILIES: &[&str] = &[
    "Segoe UI",
    "Helvetica Neue",
    "Helvetica",
    "Roboto",
    "Noto Sans",
    "DejaVu Sans",
    "Liberation Sans",
    "Arial",
    "Noto Sans CJK JP",
    "Times New Roman",
];

/// The safe options: no resources directory, and `<image>` `href`s that are
/// not inline raster `data:` never load. A canvas drawing an SVG generated by
/// the app may carry text and inline raster images, so system fonts and
/// `data:image/{png,jpeg,gif,webp}` are available; files, URLs and nested SVG
/// documents (`data:image/svg+xml`) still resolve to nothing. A nested SVG
/// would hide its own tree and images from [`layers`]' budget and from
/// [`MAX_BYTES`], so it is refused rather than drawn unbounded.
fn options(with_text: bool) -> usvg::Options<'static> {
    let mut options = usvg::Options {
        resources_dir: None,
        image_href_resolver: usvg::ImageHrefResolver {
            resolve_data: Box::new(
                |mime: &str, data: std::sync::Arc<Vec<u8>>, _: &usvg::Options<'_>| match mime {
                    // Only the MIME the document declares: sniffing a
                    // `text/plain` data URI could find SVG bytes, which
                    // bypass the image budget.
                    "image/jpg" | "image/jpeg" => Some(usvg::ImageKind::JPEG(data)),
                    "image/png" => Some(usvg::ImageKind::PNG(data)),
                    "image/gif" => Some(usvg::ImageKind::GIF(data)),
                    "image/webp" => Some(usvg::ImageKind::WEBP(data)),
                    _ => None,
                },
            ),
            resolve_string: Box::new(|_, _| None),
        },
        ..usvg::Options::default()
    };
    // Loading the system fonts maps every font file; a document with no text
    // (an icon, a logo) must not pay that on its first parse.
    if with_text {
        options.fontdb = SYSTEM_FONTS.clone();
    }
    options
}

/// Parses an SVG (or gzip-compressed SVG), loading the system fonts only when
/// the document actually lays out text.
fn parse(bytes: &[u8]) -> Result<usvg::Tree, Error> {
    let text = text_of(bytes)?;
    let doc = xml(&text)?;
    let has_text = check_text(&doc)?;
    parse_tree(doc, &text, &options(has_text))
}

/// Parses an SVG for a canvas drawing, which drops text, without loading the
/// system fonts.
pub(crate) fn parse_drawing(text: &str) -> Result<usvg::Tree, Error> {
    parse_text(text, &options(false))
}

/// The document's text, decompressed and validated: a `.svgz` is inflated.
fn text_of(bytes: &[u8]) -> Result<Cow<'_, str>, Error> {
    if bytes.starts_with(&[0x1f, 0x8b]) {
        return String::from_utf8(inflate(bytes)?)
            .map(Cow::Owned)
            .map_err(|_| Error::Invalid("not UTF-8".into()));
    }
    if bytes.len() > MAX_BYTES {
        return Err(Error::TooLarge);
    }
    std::str::from_utf8(bytes)
        .map(Cow::Borrowed)
        .map_err(|_| Error::Invalid("not UTF-8".into()))
}

#[cfg(test)]
fn parse_with(bytes: &[u8], options: &usvg::Options<'_>) -> Result<usvg::Tree, Error> {
    parse_text(&text_of(bytes)?, options)
}

fn parse_text(text: &str, options: &usvg::Options<'_>) -> Result<usvg::Tree, Error> {
    let doc = xml(text)?;
    check_text(&doc)?;
    parse_tree(doc, text, options)
}

/// Converts a checked document, completing a one-sided root first.
fn parse_tree(
    doc: roxmltree::Document<'_>,
    text: &str,
    options: &usvg::Options<'_>,
) -> Result<usvg::Tree, Error> {
    let Some(side) = OneSide::of(&doc, text) else {
        return convert(&doc, options);
    };
    // A root with only a width or only a height takes the other from the
    // viewBox's aspect ratio, as in browsers (usvg makes it 100%). The
    // missing side goes into the text before usvg converts it, which takes
    // the given side in points: read here for absolute units, else from a
    // first conversion.
    let given = match side.points() {
        Some(points) => points,
        None => side.given(convert(&doc, options)?.size()),
    };
    let completed = side.completed(text, given);
    let doc = xml(&completed)?;
    check_text(&doc)?;
    convert(&doc, options)
}

/// Refuses a document whose laid-out text is longer than [`MAX_TEXT_CHARS`]:
/// usvg lays out and outlines every glyph while parsing, before any other
/// budget runs, at a large and superlinear cost per glyph. Returns whether the
/// document lays out text, so a document without any skips the system font
/// scan.
///
/// `<use>` copies its target subtree and `<tref>` takes the text of another
/// element, so counting only the source `<text>` nodes undercounts what usvg
/// lays out. This walk expands both references, memoising a target's
/// expansion by (id, inside text) so a fan-out is counted once per target
/// rather than once per path. Text in a resource (a clip path, mask, pattern,
/// marker or filter) is laid out when the resource is converted, not where it
/// is written, so a reference from an element adds the resource's expansion;
/// a marker is laid out once per vertex. The document is also walked no deeper
/// than usvg parses it, so a deep `<use>` chain is refused before it can
/// overflow the stack. Every visited element also counts against
/// [`layers::MAX_VISITS`], the bound usvg itself lays a document out under.
fn check_text(doc: &roxmltree::Document<'_>) -> Result<bool, Error> {
    // `<use>` and `<tref>` resolve an id to the first element that carries
    // it; every other link (`clip-path`, `mask`, `filter`, markers, paints,
    // `feImage` and resource `href`s) goes through svgtree's link table,
    // where the last one wins.
    let mut ids: HashMap<&str, roxmltree::Node<'_, '_>> = HashMap::new();
    let mut links: HashMap<&str, roxmltree::Node<'_, '_>> = HashMap::new();
    for node in doc.descendants().filter(roxmltree::Node::is_element) {
        if let Some(id) = node.attribute("id") {
            ids.entry(id).or_insert(node);
            links.insert(id, node);
        }
    }
    let mut resources = HashMap::new();
    for (&id, &node) in &links {
        if let Some(kind) = ResourceKind::of(node.tag_name().name()) {
            resources.insert(id, Resource { kind, node });
        }
    }
    let mut scan = TextScan {
        ids,
        links,
        resources,
        memo: HashMap::new(),
        link_memo: HashMap::new(),
        text_memo: HashMap::new(),
        resource_memo: HashMap::new(),
        counted: HashSet::new(),
        visits: 0,
    };
    let mut total = Expansion::default();
    let mut visiting = Vec::new();
    for child in doc.root().children() {
        total.add(scan.expand(child, false, false, 0, &mut visiting)?)?;
    }
    scan.stylesheet_references(doc, &mut total, &mut visiting)?;
    Ok(total.has_text)
}

/// What a rendered subtree expands to: its text, and the elements usvg
/// creates for it (a `<use>` copies its target).
#[derive(Clone, Copy, Default)]
struct Expansion {
    chars: usize,
    nodes: u64,
    /// Path-like shapes and their vertex bound, expanded through `<use>`:
    /// what a marker inherited by this subtree is drawn on.
    shapes: u64,
    vertices: u64,
    has_text: bool,
}

/// The shapes of a subtree a marker property applies to.
#[derive(Clone, Copy, Default)]
struct MarkerTarget {
    shapes: u64,
    vertices: u64,
}

impl Expansion {
    fn marker_target(&self) -> MarkerTarget {
        MarkerTarget {
            shapes: self.shapes,
            vertices: self.vertices,
        }
    }

    fn add(&mut self, other: Expansion) -> Result<(), Error> {
        self.chars = self.chars.saturating_add(other.chars);
        if self.chars > MAX_TEXT_CHARS {
            return Err(Error::TooMuchText);
        }
        self.nodes = self.nodes.saturating_add(other.nodes);
        if self.nodes > u64::from(layers::MAX_VISITS) {
            return Err(Error::TooManyNodes);
        }
        self.shapes = self.shapes.saturating_add(other.shapes);
        self.vertices = self.vertices.saturating_add(other.vertices);
        self.has_text |= other.has_text;
        Ok(())
    }

    /// The expansion repeated `multiplier` times: a marker is laid out once
    /// per vertex of the shape that uses it.
    fn scaled(self, multiplier: u64) -> Result<Self, Error> {
        if multiplier <= 1 {
            return Ok(self);
        }
        // No text, no text-layout cost to bound. A text-free arrow marker on
        // many paths must not be refused as if its paths were glyphs.
        if self.chars == 0 {
            return Ok(Expansion::default());
        }
        let chars = (self.chars as u64).saturating_mul(multiplier);
        if chars > MAX_TEXT_CHARS as u64 {
            return Err(Error::TooMuchText);
        }
        let nodes = self.nodes.saturating_mul(multiplier);
        if nodes > u64::from(layers::MAX_VISITS) {
            return Err(Error::TooManyNodes);
        }
        Ok(Self {
            chars: chars as usize,
            nodes,
            shapes: self.shapes.saturating_mul(multiplier),
            vertices: self.vertices.saturating_mul(multiplier),
            has_text: self.has_text,
        })
    }
}

/// The resource elements whose content usvg lays out away from where it is
/// written.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ResourceKind {
    ClipPath,
    Mask,
    Pattern,
    Marker,
    Filter,
}

impl ResourceKind {
    fn of(tag: &str) -> Option<Self> {
        Some(match tag {
            "clipPath" => Self::ClipPath,
            "mask" => Self::Mask,
            "pattern" => Self::Pattern,
            "marker" => Self::Marker,
            "filter" => Self::Filter,
            _ => return None,
        })
    }

    /// The presentation attribute or style property naming this resource.
    /// CSS property names are case-insensitive.
    fn property(name: &str) -> Option<Self> {
        if name.eq_ignore_ascii_case("clip-path") {
            Some(Self::ClipPath)
        } else if name.eq_ignore_ascii_case("mask") {
            Some(Self::Mask)
        } else if name.eq_ignore_ascii_case("filter") {
            Some(Self::Filter)
        } else if name.eq_ignore_ascii_case("fill") || name.eq_ignore_ascii_case("stroke") {
            Some(Self::Pattern)
        } else if name.eq_ignore_ascii_case("marker-start")
            || name.eq_ignore_ascii_case("marker-mid")
            || name.eq_ignore_ascii_case("marker-end")
        {
            Some(Self::Marker)
        } else {
            None
        }
    }

    /// Whether usvg converts the resource once and caches it for every
    /// reference, rather than converting it once per reference.
    fn cached(self, node: roxmltree::Node<'_, '_>) -> bool {
        match self {
            Self::ClipPath => node.attribute("clipPathUnits") != Some("objectBoundingBox"),
            // `maskContentUnits` defaults to userSpaceOnUse, so only an
            // explicit objectBoundingBox makes the mask uncacheable.
            Self::Mask => {
                node.attribute("maskUnits") == Some("userSpaceOnUse")
                    && node.attribute("maskContentUnits") != Some("objectBoundingBox")
            }
            // `filterUnits` defaults to objectBoundingBox and
            // `primitiveUnits` to userSpaceOnUse.
            Self::Filter => {
                node.attribute("filterUnits") == Some("userSpaceOnUse")
                    && node.attribute("primitiveUnits") != Some("objectBoundingBox")
            }
            Self::Pattern => true,
            Self::Marker => false,
        }
    }
}

#[derive(Clone, Copy)]
struct Resource<'a, 'input> {
    kind: ResourceKind,
    node: roxmltree::Node<'a, 'input>,
}

struct TextScan<'a, 'input> {
    /// First element per id, for `<use>` and `<tref>`.
    ids: HashMap<&'a str, roxmltree::Node<'a, 'input>>,
    /// Last element per id, for resource links and `<feImage>`.
    links: HashMap<&'a str, roxmltree::Node<'a, 'input>>,
    resources: HashMap<&'a str, Resource<'a, 'input>>,
    /// A referenced subtree's expansion by (id, inside text): a `<use>` chain
    /// that fans out is counted once per target, not once per path.
    memo: HashMap<(&'a str, bool), Expansion>,
    /// The same for a link resolved by its last definition.
    link_memo: HashMap<(&'a str, bool), Expansion>,
    /// The text content of a `<tref>` target, by id.
    text_memo: HashMap<&'a str, usize>,
    /// A resource's own content, before references multiply it.
    resource_memo: HashMap<&'a str, Expansion>,
    /// Resources usvg converts once and reuses.
    counted: HashSet<&'a str>,
    visits: u32,
}

impl<'a, 'input> TextScan<'a, 'input> {
    fn expand_ref(
        &mut self,
        id: &'a str,
        in_text: bool,
        depth: u32,
        last: bool,
        visiting: &mut Vec<&'a str>,
    ) -> Result<Expansion, Error> {
        if depth > MAX_DEPTH {
            return Err(Error::TooManyNodes);
        }
        if visiting.contains(&id) {
            return Ok(Expansion::default());
        }
        let cached = if last {
            self.link_memo.get(&(id, in_text)).copied()
        } else {
            self.memo.get(&(id, in_text)).copied()
        };
        if let Some(expansion) = cached {
            return Ok(expansion);
        }
        let target = if last {
            self.links.get(id).copied()
        } else {
            self.ids.get(id).copied()
        };
        let Some(target) = target else {
            return Ok(Expansion::default());
        };
        visiting.push(id);
        let expansion = self.expand(target, in_text, true, depth, visiting);
        visiting.pop();
        let expansion = expansion?;
        if last {
            self.link_memo.insert((id, in_text), expansion);
        } else {
            self.memo.insert((id, in_text), expansion);
        }
        Ok(expansion)
    }

    fn expand(
        &mut self,
        node: roxmltree::Node<'a, 'input>,
        in_text: bool,
        expanded: bool,
        depth: u32,
        visiting: &mut Vec<&'a str>,
    ) -> Result<Expansion, Error> {
        if depth > MAX_DEPTH {
            return Err(Error::TooManyNodes);
        }
        if node.is_text() {
            return self.text_node(node, in_text);
        }
        if !node.is_element() {
            return Ok(Expansion::default());
        }
        self.visits = self.visits.saturating_add(1);
        if self.visits > layers::MAX_VISITS {
            return Err(Error::TooManyNodes);
        }
        match node.tag_name().name() {
            // Definitions are not drawn where they are written; `<use>`
            // reaches them from its own position, and a presentation
            // attribute reaches a resource from the element that names it.
            "defs" | "clipPath" | "mask" | "pattern" | "marker" | "linearGradient"
            | "radialGradient" | "filter" | "style" | "title" | "desc" | "metadata" | "script" => {
                Ok(Expansion::default())
            }
            "symbol" if !expanded => Ok(Expansion::default()),
            // The branches are separate functions so the recursive walk
            // keeps its frames small: a document at the depth limit must not
            // overflow the stack of the thread parsing it.
            "text" => self.expand_text(node, depth, visiting),
            "tref" => self.expand_tref(node, depth, visiting),
            "use" => self.expand_use(node, in_text, depth, visiting),
            _ => self.expand_children(node, in_text, depth, visiting),
        }
    }

    fn text_node(
        &mut self,
        node: roxmltree::Node<'a, 'input>,
        in_text: bool,
    ) -> Result<Expansion, Error> {
        if !in_text {
            return Ok(Expansion::default());
        }
        let mut out = Expansion::default();
        out.add(Expansion {
            chars: node.text().unwrap_or_default().chars().count(),
            nodes: 0,
            has_text: true,
            ..Expansion::default()
        })?;
        Ok(out)
    }

    fn expand_text(
        &mut self,
        node: roxmltree::Node<'a, 'input>,
        depth: u32,
        visiting: &mut Vec<&'a str>,
    ) -> Result<Expansion, Error> {
        let mut out = Expansion {
            nodes: 1,
            has_text: true,
            ..Expansion::default()
        };
        for child in node.children() {
            out.add(self.expand(child, true, false, depth + 1, visiting)?)?;
        }
        out.add(self.references(node, MarkerTarget::default(), depth, visiting)?)?;
        Ok(out)
    }

    fn expand_tref(
        &mut self,
        node: roxmltree::Node<'a, 'input>,
        depth: u32,
        visiting: &mut Vec<&'a str>,
    ) -> Result<Expansion, Error> {
        let Some(id) = href(node) else {
            return Ok(Expansion::default());
        };
        let chars = self.text_chars(id)?;
        let mut out = Expansion {
            chars,
            nodes: 1,
            has_text: chars > 0,
            ..Expansion::default()
        };
        out.add(self.references(node, MarkerTarget::default(), depth, visiting)?)?;
        Ok(out)
    }

    fn expand_use(
        &mut self,
        node: roxmltree::Node<'a, 'input>,
        in_text: bool,
        depth: u32,
        visiting: &mut Vec<&'a str>,
    ) -> Result<Expansion, Error> {
        let Some(id) = href(node) else {
            return Ok(Expansion::default());
        };
        // `parse_svg_use_element` parses the target one level deeper than
        // the element that referred to it, so a use counts two.
        let mut out = self.expand_ref(id, in_text, depth + 2, false, visiting)?;
        out.add(Expansion {
            nodes: 1,
            ..Expansion::default()
        })?;
        let target = out.marker_target();
        out.add(self.references(node, target, depth, visiting)?)?;
        Ok(out)
    }

    fn expand_children(
        &mut self,
        node: roxmltree::Node<'a, 'input>,
        in_text: bool,
        depth: u32,
        visiting: &mut Vec<&'a str>,
    ) -> Result<Expansion, Error> {
        let mut out = Expansion {
            nodes: 1,
            shapes: u64::from(is_marker_shape(node)),
            vertices: vertex_bound(node),
            ..Expansion::default()
        };
        for child in node.children() {
            out.add(self.expand(child, in_text, false, depth + 1, visiting)?)?;
        }
        let target = out.marker_target();
        out.add(self.references(node, target, depth, visiting)?)?;
        Ok(out)
    }

    /// The text a node draws through its own attributes: a clip path, mask,
    /// filter, pattern or marker it names, and an `<feImage>` it embeds.
    fn references(
        &mut self,
        node: roxmltree::Node<'a, 'input>,
        target: MarkerTarget,
        depth: u32,
        visiting: &mut Vec<&'a str>,
    ) -> Result<Expansion, Error> {
        let mut out = Expansion::default();
        if node.tag_name().name() == "feImage"
            && let Some(id) = href(node)
        {
            let mut image = self.expand_ref(id, false, depth + 2, true, visiting)?;
            // What `feImage` draws is not part of the marker inheritance of
            // the element that embeds it.
            image.shapes = 0;
            image.vertices = 0;
            out.add(image)?;
        }
        for attribute in node.attributes() {
            match attribute.name() {
                "style" => {
                    out.add(self.inline_style(
                        attribute.value(),
                        node,
                        target,
                        depth,
                        visiting,
                    )?)?;
                }
                name => {
                    out.add(self.property_use(
                        node,
                        name,
                        attribute.value(),
                        target,
                        depth,
                        visiting,
                    )?)?;
                }
            }
        }
        Ok(out)
    }

    /// One presentation attribute or style declaration, resolving
    /// `inherit` and walking every URL in a `filter` list.
    fn property_use(
        &mut self,
        node: roxmltree::Node<'a, 'input>,
        name: &str,
        value: &'a str,
        target: MarkerTarget,
        depth: u32,
        visiting: &mut Vec<&'a str>,
    ) -> Result<Expansion, Error> {
        let Some(kind) = ResourceKind::property(name) else {
            return Ok(Expansion::default());
        };
        let value = value.trim();
        if value.eq_ignore_ascii_case("inherit") {
            // An inherited marker reference is counted by the ancestor that
            // sets it, over this whole subtree.
            if kind == ResourceKind::Marker {
                return Ok(Expansion::default());
            }
            let Some(value) = inherited_value(node, name) else {
                return Ok(Expansion::default());
            };
            return self.value_use(name, kind, value, target, depth, visiting);
        }
        self.value_use(name, kind, value, target, depth, visiting)
    }

    fn value_use(
        &mut self,
        name: &str,
        kind: ResourceKind,
        value: &'a str,
        target: MarkerTarget,
        depth: u32,
        visiting: &mut Vec<&'a str>,
    ) -> Result<Expansion, Error> {
        let mut out = Expansion::default();
        // A `filter` value is a list: `url(#a) url(#b)` converts and lays
        // out both.
        if kind == ResourceKind::Filter {
            for id in func_iris(value) {
                out.add(self.resource_use(id, kind, name, target, depth, visiting)?)?;
            }
        } else if let Some(id) = func_iri(value) {
            out.add(self.resource_use(id, kind, name, target, depth, visiting)?)?;
        }
        Ok(out)
    }

    fn inline_style(
        &mut self,
        style: &'a str,
        node: roxmltree::Node<'a, 'input>,
        target: MarkerTarget,
        depth: u32,
        visiting: &mut Vec<&'a str>,
    ) -> Result<Expansion, Error> {
        let mut out = Expansion::default();
        // usvg parses a style attribute with simplecss: comments before a
        // name are skipped, a leading `*` is dropped, and `marker` expands
        // to the three marker properties.
        for declaration in simplecss::DeclarationTokenizer::from(style) {
            if declaration.name.eq_ignore_ascii_case("marker") {
                for property in ["marker-start", "marker-mid", "marker-end"] {
                    out.add(self.property_use(
                        node,
                        property,
                        declaration.value,
                        target,
                        depth,
                        visiting,
                    )?)?;
                }
            } else {
                out.add(self.property_use(
                    node,
                    declaration.name,
                    declaration.value,
                    target,
                    depth,
                    visiting,
                )?)?;
            }
        }
        Ok(out)
    }

    fn resource_use(
        &mut self,
        id: &'a str,
        kind: ResourceKind,
        property: &str,
        target: MarkerTarget,
        depth: u32,
        visiting: &mut Vec<&'a str>,
    ) -> Result<Expansion, Error> {
        let Some(resource) = self.resources.get(id).copied() else {
            return Ok(Expansion::default());
        };
        if resource.kind != kind {
            return Ok(Expansion::default());
        }
        if resource.kind.cached(resource.node) && !self.counted.insert(id) {
            return Ok(Expansion::default());
        }
        let mut body = self.resource_body(id, resource, depth + 4, visiting)?;
        // A resource's shapes are drawn where it is used, not as marker
        // targets of the element that references it.
        body.shapes = 0;
        body.vertices = 0;
        let multiplier = if kind == ResourceKind::Marker {
            marker_multiplier(property, target)
        } else {
            1
        };
        body.scaled(multiplier)
    }

    fn resource_body(
        &mut self,
        id: &'a str,
        resource: Resource<'a, 'input>,
        depth: u32,
        visiting: &mut Vec<&'a str>,
    ) -> Result<Expansion, Error> {
        if let Some(body) = self.resource_memo.get(id) {
            return Ok(*body);
        }
        if visiting.contains(&id) {
            return Ok(Expansion::default());
        }
        if depth > MAX_DEPTH {
            return Err(Error::TooManyNodes);
        }
        visiting.push(id);
        let mut body = Expansion::default();
        if let Some(link) = href(resource.node)
            && let Some(linked) = self.resources.get(link).copied()
            && linked.kind == resource.kind
        {
            body.add(self.resource_body(link, linked, depth + 4, visiting)?)?;
        }
        for child in resource.node.children() {
            body.add(self.expand(child, false, true, depth + 1, visiting)?)?;
        }
        // A clip path can name another clip path in `clip-path`, and a mask
        // another mask in `mask`; usvg converts the linked resource too.
        let target = body.marker_target();
        body.add(self.references(resource.node, target, depth, visiting)?)?;
        visiting.pop();
        self.resource_memo.insert(id, body);
        Ok(body)
    }

    /// Text in a resource named by a `<style>` element can be laid out for
    /// every element the rule matches; charge it as if it matched every
    /// element, and a marker once per vertex of every shape.
    fn stylesheet_references(
        &mut self,
        doc: &roxmltree::Document<'_>,
        total: &mut Expansion,
        visiting: &mut Vec<&'a str>,
    ) -> Result<(), Error> {
        let mut mentioned: HashSet<&str> = HashSet::new();
        for style in doc
            .descendants()
            .filter(|node| node.is_element() && node.tag_name().name() == "style")
        {
            let Some(text) = style.text() else {
                continue;
            };
            mentioned.extend(func_iris(text));
        }
        let resources: Vec<(&'a str, Resource<'a, 'input>)> = self
            .resources
            .iter()
            .filter(|(id, _)| mentioned.contains(**id))
            .map(|(&id, &resource)| (id, resource))
            .collect();
        if resources.is_empty() {
            return Ok(());
        }
        // A stylesheet can apply to every expanded element, including the
        // copies a `<use>` makes; the walk's node and vertex counts bound it.
        let expanded = total.nodes.max(1);
        let vertices = total.vertices.max(1);
        for (id, resource) in resources {
            if resource.kind.cached(resource.node) && self.counted.contains(id) {
                continue;
            }
            let body = self.resource_body(id, resource, 0, visiting)?;
            let multiplier = match resource.kind {
                // A marker is laid out once per end and vertex of every
                // element the rule matches.
                ResourceKind::Marker => vertices,
                // A cached resource is converted once however many rules
                // name it; an objectBoundingBox clip path or mask is
                // converted per element.
                kind if kind.cached(resource.node) => 1,
                _ => expanded,
            };
            total.add(body.scaled(multiplier)?)?;
        }
        Ok(())
    }

    /// The characters a `<tref>` to `id` lays out: every text node under the
    /// referenced element. Unlike a `<use>`, a `tref` reads the target's text
    /// without expanding it, so it cannot cycle.
    fn text_chars(&mut self, id: &'a str) -> Result<usize, Error> {
        if let Some(chars) = self.text_memo.get(id) {
            return Ok(*chars);
        }
        let Some(target) = self.ids.get(id).copied() else {
            return Ok(0);
        };
        let mut chars = 0usize;
        for node in target.descendants().filter(roxmltree::Node::is_text) {
            chars = chars.saturating_add(node.text().unwrap_or_default().chars().count());
            if chars > MAX_TEXT_CHARS {
                return Err(Error::TooMuchText);
            }
        }
        self.text_memo.insert(id, chars);
        Ok(chars)
    }
}

/// How many times a marker is laid out for `user`: once at each end, and once
/// per vertex for middle markers. The shape and vertex counts are the
/// subtree's expanded ones, so `<use>` copies count.
fn marker_multiplier(property: &str, target: MarkerTarget) -> u64 {
    if property.eq_ignore_ascii_case("marker-start") || property.eq_ignore_ascii_case("marker-end")
    {
        target.shapes.max(1)
    } else {
        target.vertices.max(1)
    }
}

fn is_marker_shape(node: roxmltree::Node<'_, '_>) -> bool {
    matches!(
        node.tag_name().name(),
        "path" | "line" | "polyline" | "polygon" | "rect" | "circle" | "ellipse"
    )
}

/// An upper bound on the vertices a shape has, for counting middle markers:
/// the length of its path data or points list, as counting characters cannot
/// overrun the number of vertices.
fn vertex_bound(node: roxmltree::Node<'_, '_>) -> u64 {
    match node.tag_name().name() {
        "path" => node.attribute("d").map_or(1, |d| d.len().max(1) as u64),
        "polyline" | "polygon" => node
            .attribute("points")
            .map_or(1, |p| p.len().max(1) as u64),
        "line" => 2,
        "rect" | "circle" | "ellipse" => 8,
        _ => 0,
    }
}

/// The parent's computed value of a property when a node says `inherit`.
/// `clip-path`, `mask` and `filter` are not inherited: only a direct parent
/// with an explicit value supplies one, and a parent that itself says
/// `inherit` resolves up the chain.
fn inherited_value<'a, 'input>(
    node: roxmltree::Node<'a, 'input>,
    property: &str,
) -> Option<&'a str> {
    let mut parent = node.parent_element()?;
    loop {
        match property_value(parent, property) {
            Some(value) if value.trim().eq_ignore_ascii_case("inherit") => {
                parent = parent.parent_element()?;
            }
            value => return value,
        }
    }
}

/// A property's presentation-attribute or inline-style value, as usvg reads
/// a style attribute (simplecss declarations).
fn property_value<'a, 'input>(
    node: roxmltree::Node<'a, 'input>,
    property: &str,
) -> Option<&'a str> {
    if let Some(value) = node.attribute(property) {
        return Some(value);
    }
    let style = node.attribute("style")?;
    let mut value = None;
    for declaration in simplecss::DeclarationTokenizer::from(style) {
        if declaration.name.eq_ignore_ascii_case(property) {
            value = Some(declaration.value);
        }
    }
    value
}

/// The id a `<use>`, `<tref>` or resource `href` refers to, when it is in
/// this document. usvg takes `xlink:href` before `href`, then parses the value
/// as an IRI: spaces around it are ignored and the id runs to the first space.
fn href<'a, 'input>(node: roxmltree::Node<'a, 'input>) -> Option<&'a str> {
    let value = node
        .attribute((XLINK_NS, "href"))
        .or_else(|| node.attribute("href"))?;
    iri(value)
}

fn iri(value: &str) -> Option<&str> {
    let value = value.trim_start_matches(|c: char| c.is_ascii_whitespace());
    let value = value.strip_prefix('#')?;
    let end = value.find(' ').unwrap_or(value.len());
    let id = &value[..end];
    if id.is_empty() || value[end..].chars().any(|c| !c.is_ascii_whitespace()) {
        return None;
    }
    Some(id)
}

/// The id in a `url(#id)` value, ignoring surrounding quotes and spaces.
fn func_iri(value: &str) -> Option<&str> {
    let start = value.find("url(")? + "url(".len();
    let rest = value[start..].trim_start();
    let (rest, quote) = match rest.chars().next() {
        Some(quote @ ('\'' | '"')) => (&rest[quote.len_utf8()..], Some(quote)),
        _ => (rest, None),
    };
    let rest = rest.trim_start();
    let rest = rest.strip_prefix('#')?;
    let end = rest
        .char_indices()
        .find(|&(_, c)| Some(c) == quote || c == ')' || c.is_ascii_whitespace())
        .map(|(index, _)| index)?;
    if end == 0 {
        return None;
    }
    Some(&rest[..end])
}

/// Every `url(#id)` in a stylesheet's text.
fn func_iris(text: &str) -> Vec<&str> {
    let mut ids = Vec::new();
    let mut rest = text;
    while let Some(start) = rest.find("url(") {
        if let Some(id) = func_iri(&rest[start..]) {
            ids.push(id);
        }
        let after = &rest[start + "url(".len()..];
        rest = match after.find(')') {
            Some(end) => &after[end + 1..],
            None => break,
        };
    }
    ids
}

fn xml(text: &str) -> Result<roxmltree::Document<'_>, Error> {
    let options = roxmltree::ParsingOptions {
        allow_dtd: true,
        ..roxmltree::ParsingOptions::default()
    };
    roxmltree::Document::parse_with_options(text, options)
        .map_err(|e| Error::Invalid(e.to_string()))
}

fn convert(
    doc: &roxmltree::Document<'_>,
    options: &usvg::Options<'_>,
) -> Result<usvg::Tree, Error> {
    usvg::Tree::from_xmltree(doc, options).map_err(|e| match e {
        usvg::Error::InvalidSize => Error::NoArea,
        e => Error::Invalid(e.to_string()),
    })
}

/// A root `<svg>` with a `viewBox` and only one of `width` and `height`
/// (not a percentage).
struct OneSide<'a> {
    /// `width` is the one given (else `height`).
    width: bool,
    /// Its value as written.
    value: &'a str,
    /// The `viewBox`'s width and height.
    view_box: (f32, f32),
    /// Where the missing attribute goes in the text: after the root's tag
    /// name.
    at: usize,
}

impl<'a> OneSide<'a> {
    fn of(doc: &'a roxmltree::Document<'_>, text: &str) -> Option<OneSide<'a>> {
        let root = doc.root_element();
        let view_box: Vec<f32> = root
            .attribute("viewBox")?
            .split(|c: char| c.is_ascii_whitespace() || c == ',')
            .filter(|s| !s.is_empty())
            .filter_map(|s| s.parse().ok())
            .collect();
        let [_, _, vw, vh] = view_box[..] else {
            return None;
        };
        if !(vw > 0.0 && vh > 0.0) {
            return None;
        }
        let (width, value) = match (root.attribute("width"), root.attribute("height")) {
            (Some(value), None) => (true, value),
            (None, Some(value)) => (false, value),
            _ => return None,
        };
        if value.trim_end().ends_with('%') {
            return None;
        }
        Some(OneSide {
            width,
            value,
            view_box: (vw, vh),
            at: root_attributes_at(doc, text),
        })
    }

    /// The given side in points (CSS pixels), for a number in an absolute
    /// unit; `None` for the others (`em`, `ex`), which usvg resolves.
    fn points(&self) -> Option<f32> {
        let value = self.value.trim();
        // Longer ones are no length anyone writes: usvg reads them.
        if value.len() > 32 {
            return None;
        }
        let (number, unit) = (1..=value.len())
            .rev()
            .filter(|&i| value.is_char_boundary(i))
            .find_map(|i| Some((value[..i].parse::<f32>().ok()?, &value[i..])))?;
        let per_unit = match unit {
            "" | "px" => 1.0,
            "in" => 96.0,
            "cm" => 96.0 / 2.54,
            "mm" => 96.0 / 25.4,
            "pt" => 4.0 / 3.0,
            "pc" => 16.0,
            _ => return None,
        };
        Some(number * per_unit).filter(|p| p.is_finite())
    }

    /// The given side of a tree usvg converted with it (and the other at
    /// 100%).
    fn given(&self, size: usvg::Size) -> f32 {
        if self.width {
            size.width()
        } else {
            size.height()
        }
    }

    /// `text` with the missing side added, `given` points being the other.
    fn completed(&self, text: &str, given: f32) -> String {
        let (vw, vh) = self.view_box;
        let added = if self.width {
            format!(" height=\"{}\"", given * vh / vw)
        } else {
            format!(" width=\"{}\"", given * vw / vh)
        };
        let mut fixed = String::with_capacity(text.len() + added.len());
        fixed.push_str(&text[..self.at]);
        fixed.push_str(&added);
        fixed.push_str(&text[self.at..]);
        fixed
    }
}

/// Where an attribute added to the root element goes in `text`, the
/// document `doc` was parsed from: after the root's tag name.
fn root_attributes_at(doc: &roxmltree::Document<'_>, text: &str) -> usize {
    let start = doc.root_element().range().start + 1;
    text[start..]
        .find(|c: char| c.is_ascii_whitespace() || c == '>' || c == '/')
        .map_or(text.len(), |i| start + i)
}

/// Inflates a `.svgz` up to [`MAX_BYTES`].
fn inflate(bytes: &[u8]) -> Result<Vec<u8>, Error> {
    let mut inflated = Vec::new();
    flate2::read::GzDecoder::new(bytes)
        .take(MAX_BYTES as u64 + 1)
        .read_to_end(&mut inflated)
        .map_err(|_| Error::Invalid("malformed gzip data".into()))?;
    if inflated.len() > MAX_BYTES {
        return Err(Error::TooLarge);
    }
    Ok(inflated)
}

/// The size of usvg's tree, typed.
fn points(size: usvg::Size) -> Size<Points> {
    Size::new(Points(size.width()), Points(size.height()))
}

/// The intrinsic size of an SVG in points: its root `width` and `height`
/// (percentages of the `viewBox`; one of them alone takes the other from
/// the `viewBox`'s aspect ratio), else the `viewBox`'s size. An SVG with
/// neither a size nor a `viewBox` reaches as far as what it draws.
pub fn size(bytes: &[u8]) -> Result<Size<Points>, Error> {
    guarded(|| Ok(points(parse(bytes)?.size())))
}

/// The size `onLoad` and `Image.getSize` report for an SVG of `size`
/// points: whole points, at least one, carried in [`DevicePixels`] as
/// bitmaps' sizes in pixels are.
pub fn reported_size(size: Size<Points>) -> Size<DevicePixels> {
    let whole = |p: Points| DevicePixels(p.0.round().clamp(1.0, i32::MAX as f32) as i32);
    Size::new(whole(size.width), whole(size.height))
}

/// Draws an SVG with its longest side `max_px` pixels long, keeping its
/// aspect ratio (within [`MAX_SIDE`] and [`MAX_PIXELS`]).
pub fn rasterize(bytes: &[u8], max_px: u32) -> Result<Raster, Error> {
    guarded(|| {
        let tree = parse(bytes)?;
        draw(&tree, max_px as f32, MAX_SIDE)
    })
}

/// Draws an SVG with its shorter side `px` pixels long, keeping its aspect
/// ratio (within [`MAX_SIDE`] and [`MAX_PIXELS`]): the raster of backends
/// that decode per view, where `px` is the view's longer side in pixels.
/// Shown in such a view, an image's shorter side is never longer than
/// that, so the raster is never enlarged, in any resize mode (`cover`
/// included).
pub fn rasterize_covering(bytes: &[u8], px: u32) -> Result<Raster, Error> {
    guarded(|| {
        let tree = parse(bytes)?;
        let size = tree.size();
        let (long, short) = (
            size.width().max(size.height()),
            size.width().min(size.height()),
        );
        draw(&tree, px as f32 * long / short, MAX_SIDE)
    })
}

/// Draws an SVG at its intrinsic size, `scale` pixels per point (a
/// display's scale factor; within [`MAX_SIDE`] and [`MAX_PIXELS`]): the
/// raster of an image shown at its natural size.
pub fn rasterize_scaled(bytes: &[u8], scale: f32) -> Result<Raster, Error> {
    guarded(|| {
        let tree = parse(bytes)?;
        let size = tree.size();
        draw(&tree, size.width().max(size.height()) * scale, MAX_SIDE)
    })
}

/// Draws an SVG at [`OVERSAMPLE`] pixels per point, its longest side at most
/// [`MAX_OVERSAMPLED_SIDE`]: the raster of backends that draw one bitmap at
/// every size the image is shown at.
pub fn rasterize_oversampled(bytes: &[u8]) -> Result<Raster, Error> {
    guarded(|| {
        let tree = parse(bytes)?;
        let size = tree.size();
        let longest = size.width().max(size.height()) * OVERSAMPLE as f32;
        draw(&tree, longest, MAX_OVERSAMPLED_SIDE)
    })
}

/// The raster size of an SVG of `size` drawn with its longest side
/// `longest` pixels long: its aspect ratio kept, each side at least a pixel
/// and at most `max_side`, and at most [`MAX_PIXELS`] in all.
fn raster_size(size: usvg::Size, longest: f32, max_side: u32) -> Result<(u32, u32), Error> {
    if longest.is_nan() || longest <= 0.0 {
        return Err(Error::NoPixels);
    }
    let (w, h) = (f64::from(size.width()), f64::from(size.height()));
    let longest = f64::from(longest).clamp(1.0, f64::from(max_side));
    let scale = longest / w.max(h);
    let side = |v: f64| v.clamp(1.0, f64::from(max_side)) as u32;
    let (width, height) = (side((w * scale).round()), side((h * scale).round()));
    if u64::from(width) * u64::from(height) <= u64::from(MAX_PIXELS) {
        return Ok((width, height));
    }
    // Rounded down, so that the product stays within the budget.
    let scale = scale
        * (f64::from(MAX_PIXELS) / (w * h * scale * scale))
            .sqrt()
            .min(1.0);
    Ok((side((w * scale).floor()), side((h * scale).floor())))
}

/// Draws `tree` with its longest side `longest` pixels long ([`raster_size`]),
/// unless its layers are over [`MAX_LAYER_PIXELS`].
fn draw(tree: &usvg::Tree, longest: f32, max_side: u32) -> Result<Raster, Error> {
    let size = tree.size();
    let (width, height) = raster_size(size, longest, max_side)?;
    let transform = tiny_skia::Transform::from_scale(
        width as f32 / size.width(),
        height as f32 / size.height(),
    );
    let layers = layers::peak(tree, transform, (width, height)).ok_or(Error::TooManyNodes)?;
    if layers > f64::from(MAX_LAYER_PIXELS) {
        return Err(Error::OverBudget {
            pixels: layers as u64,
        });
    }
    // `None` only for a zero side or rows past `i32::MAX` bytes, which
    // `raster_size` never gives.
    let mut pixmap = tiny_skia::Pixmap::new(width, height).ok_or(Error::NoPixels)?;
    resvg::render(tree, transform, &mut pixmap.as_mut());
    Ok(Raster {
        width,
        height,
        pixels: pixmap.take(),
        size: points(size),
    })
}